ソースを参照

shiro 排除swagger路径

laowo 3 年 前
コミット
5cedece306

+ 58 - 23
src/main/java/com/usky/config/shiro/MyRedisSerializer.java

@@ -1,5 +1,7 @@
 package com.usky.config.shiro;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.data.redis.serializer.RedisSerializer;
 import org.springframework.data.redis.serializer.SerializationException;
  
@@ -9,35 +11,68 @@ import java.io.*;
  * 重写序列化 序列化为字节码
  */
 public class MyRedisSerializer implements RedisSerializer {
- 
- 
+
+    private static Logger logger = LoggerFactory.getLogger(MyRedisSerializer.class);
+
+    public static boolean isEmpty(byte[] data) {
+        return (data == null || data.length == 0);
+    }
+
+    /**
+     * 序列化
+     * @param object
+     * @return
+     * @throws SerializationException
+     */
     @Override
-    public byte[] serialize(Object o) throws SerializationException {
-        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
-        ObjectOutputStream objOut;
-        try {
-            objOut = new ObjectOutputStream(byteOut);
-            objOut.writeObject(o);
-        } catch (IOException e) {
-            e.printStackTrace();
+    public byte[] serialize(Object object) throws SerializationException {
+        byte[] result = null;
+
+        if (object == null) {
+            return new byte[0];
         }
-        return byteOut.toByteArray();
+        try (
+                ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
+                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)
+        ){
+
+            if (!(object instanceof Serializable)) {
+                throw new IllegalArgumentException(MyRedisSerializer.class.getSimpleName() + " requires a Serializable payload " +
+                        "but received an object of type [" + object.getClass().getName() + "]");
+            }
+
+            objectOutputStream.writeObject(object);
+            objectOutputStream.flush();
+            result =  byteStream.toByteArray();
+        } catch (Exception ex) {
+            logger.error("Failed to serialize",ex);
+        }
+        return result;
     }
- 
+
+    /**
+     * 反序列化
+     * @param bytes
+     * @return
+     * @throws SerializationException
+     */
     @Override
     public Object deserialize(byte[] bytes) throws SerializationException {
-        if(bytes == null) return null;
-        ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
-        ObjectInputStream objIn;
-        Object obj;
-        try {
-            objIn = new ObjectInputStream(byteIn);
-            obj =objIn.readObject();
-        } catch (IOException | ClassNotFoundException e) {
-            e.printStackTrace();
+
+        Object result = null;
+
+        if (isEmpty(bytes)) {
             return null;
         }
-        return obj;
+
+        try (
+                ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
+                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)
+        ){
+            result = objectInputStream.readObject();
+        } catch (Exception e) {
+            logger.error("Failed to deserialize",e);
+        }
+        return result;
     }
- 
 }

+ 27 - 21
src/main/java/com/usky/config/shiro/ShiroConfig.java

@@ -10,6 +10,8 @@ import org.apache.shiro.session.mgt.SessionManager;
 import org.apache.shiro.session.mgt.eis.SessionDAO;
 import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
 import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
+import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
+import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
 import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
 import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
 import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
@@ -32,22 +34,26 @@ public class ShiroConfig {
     public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager) {
         ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
         shiroFilterFactoryBean.setSecurityManager(securityManager);
-        shiroFilterFactoryBean.setLoginUrl("/page/toLogin");
-
+        //登录
+        shiroFilterFactoryBean.setLoginUrl("/sys/login");
         //控制 访问xx资源 需要xx权限
-        Map filterChainMap = new LinkedHashMap<String,String>();
-        filterChainMap.put("/sys/login","anon"); //访问登录页面 直接放行
-        filterChainMap.put("/","anon"); //访问登录页面 直接放行
-        filterChainMap.put("/user/all","perms[user:select]"); //查询所有用户 需要认证(登录)
-
-        //当用户查看仓库列表时,需要有仓库权限
-        filterChainMap.put("/storage/all","perms[storage:select]");
-        //当用户删除用户时,需要有超级管理员角色
-//        filterChainMap.put("/user/del/*","roles[role_superman]");
-
-        filterChainMap.put("/backend/logout","logout");
-
+        Map<String, String> filterChainMap = new LinkedHashMap<>();
+
+        //swagger接口权限 开放
+        filterChainMap.put("/doc.html", "anon");
+        filterChainMap.put("/webjars/**/**","anon");
+        filterChainMap.put("/swagger-ui.html", "anon");
+        filterChainMap.put("/webjars/**", "anon");
+        filterChainMap.put("/v2/**", "anon");
+        filterChainMap.put("/swagger-resources/**", "anon");
+        //退出
+        filterChainMap.put("/logout", "logout");
+        filterChainMap.put("/static/**", "anon");
+        filterChainMap.put("/templates/**", "anon");
+        //swagger接口权限 开放
+        filterChainMap.put("/**", "authc");
         shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
+
         return shiroFilterFactoryBean;
     }
 
@@ -72,9 +78,8 @@ public class ShiroConfig {
 //        return defaultWebSecurityManager;
 //    }
 
-    //realm
     @Bean
-    public Realm myRealm(){
+    public Realm myRealm() {
         MyRealm myRealm = new MyRealm();
         //告诉realm密码匹配方式
         myRealm.setCredentialsMatcher(credentialsMatcher());
@@ -88,13 +93,13 @@ public class ShiroConfig {
 
     //缓存管理
     @Bean
-    public CacheManager MycacheManager(){
+    public CacheManager MycacheManager() {
         MyRedisCacheManager cacheManager = new MyRedisCacheManager();
         return cacheManager;
     }
 
     @Bean
-    public CredentialsMatcher credentialsMatcher(){
+    public CredentialsMatcher credentialsMatcher() {
         HashedCredentialsMatcher hashedMatcher = new HashedCredentialsMatcher();
         hashedMatcher.setHashAlgorithmName("md5");
 //        hashedMatcher.setHashIterations(1);
@@ -120,12 +125,13 @@ public class ShiroConfig {
     }
 
     @Bean
-    public ShiroDialect shiroDialect(){
+    public ShiroDialect shiroDialect() {
         return new ShiroDialect();
     }
 
     /**
      * 会话管理器
+     *
      * @return
      */
     @Bean
@@ -134,7 +140,7 @@ public class ShiroConfig {
         sessionManager.setSessionDAO(redisSessionDAO());
 
         //设置会话过期时间
-        sessionManager.setGlobalSessionTimeout(3*60*1000); //默认半小时
+        sessionManager.setGlobalSessionTimeout(3 * 60 * 1000); //默认半小时
         sessionManager.setDeleteInvalidSessions(true); //默认自定调用SessionDAO的delete方法删除会话
         //设置会话定时检查
         //        sessionManager.setSessionValidationInterval(180000); //默认一小时
@@ -143,7 +149,7 @@ public class ShiroConfig {
     }
 
     @Bean
-    public SessionDAO redisSessionDAO(){
+    public SessionDAO redisSessionDAO() {
         ShiroRedisSessionDao redisDAO = new ShiroRedisSessionDao();
         return redisDAO;
     }

+ 15 - 23
src/main/java/com/usky/controller/login/LoginController.java

@@ -1,7 +1,6 @@
 package com.usky.controller.login;
 
-import com.usky.entity.sys.SysUserDTO;
-import com.usky.service.user.UserService;
+import com.usky.exception.user.UserPasswordNotMatchException;
 import com.usky.utils.Result;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
@@ -13,7 +12,6 @@ import org.apache.shiro.authc.AuthenticationException;
 import org.apache.shiro.authc.AuthenticationToken;
 import org.apache.shiro.authc.UsernamePasswordToken;
 import org.apache.shiro.subject.Subject;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
@@ -34,25 +32,19 @@ public class LoginController {
             @ApiImplicitParam(name = "username", value = "登录名", required = true, paramType = "query"),
             @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query")
     })
-    public Result<?> login(String username, String password, Boolean rememberMe) {
-//        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
-//        Subject subject = SecurityUtils.getSubject();
-//        try {
-//            subject.login(token);
-//            return Result.OK();
-//        } catch (AuthenticationException e) {
-//            String msg = "用户或密码错误";
-//            if (StringUtils.isNotEmpty(e.getMessage())) {
-//                msg = e.getMessage();
-//            }
-//            return Result.error(msg);
-//        }
-//    }
-
-        // subject - securityManager - realm
-        Subject subject = SecurityUtils.getSubject();
-        AuthenticationToken token = new UsernamePasswordToken(username, password);
-        subject.login(token);
-        return Result.OK("登录成功");
+    public Result<?> login(String username, String password) {
+        try {
+            //获取登录用户
+            Subject subject = SecurityUtils.getSubject();
+            AuthenticationToken token = new UsernamePasswordToken(username, password);
+            subject.login(token);
+            return Result.OK("登录成功");
+        } catch (AuthenticationException e) {
+            String msg = "用户或密码错误";
+            if (StringUtils.isEmpty(e.getMessage())) {
+                throw new UserPasswordNotMatchException();
+            }
+            return Result.error(msg);
+        }
     }
 }

+ 10 - 11
src/main/java/com/usky/exception/GloableExceptionResolver.java

@@ -89,19 +89,18 @@ public class GloableExceptionResolver {
 
 
     @ExceptionHandler(BaseException.class)
-    public Object businessException(HttpServletRequest request, BaseException e)
-    {
+    public Object businessException(HttpServletRequest request, BaseException e) {
         log.error(e.getMessage(), e);
-        if (ServletUtils.isAjaxRequest(request))
-        {
+        if (ServletUtils.isAjaxRequest(request)) {
             return Result.error(e.getMessage());
-        }
-        else
-        {
-            ModelAndView modelAndView = new ModelAndView();
-            modelAndView.addObject("errorMessage", e.getMessage());
-            modelAndView.setViewName("error/business");
-            return modelAndView;
+        } else {
+
+            //  ModelAndView modelAndView = new ModelAndView(); //TODO 异常页面跳转设置
+            //  modelAndView.addObject("errorMessage", e.getMessage());
+            //  modelAndView.setViewName("error/business");
+            //  return modelAndView;
+
+            return null;
         }
     }