浏览代码

07 26 01 shiro配置

hr 4 年之前
父节点
当前提交
9e4e96ccf8

+ 1 - 0
.gitignore

@@ -18,6 +18,7 @@ target/
 *.iws
 *.iml
 *.ipr
+logs/
 
 ### NetBeans ###
 /nbproject/private/

+ 48 - 48
src/main/java/com/imed/costaccount/common/config/CorsConfig.java

@@ -1,56 +1,56 @@
-//package com.imed.costaccount.common.config;
-//
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.context.annotation.Bean;
-//import org.springframework.context.annotation.Configuration;
-//import org.springframework.web.cors.CorsConfiguration;
-//import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
-//import org.springframework.web.filter.CorsFilter;
-//import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-//
-///**
-// * @author huangrui
-// */
-//@Configuration
-//public class CorsConfig implements WebMvcConfigurer {
-//
-//
-//
+package com.imed.costaccount.common.config;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.cors.CorsConfiguration;
+import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
+import org.springframework.web.filter.CorsFilter;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+/**
+ * @author huangrui
+ */
+@Configuration
+public class CorsConfig implements WebMvcConfigurer {
+
+
+
 //    @Value("${file.filelocal}")
 //    private String fileLocal;
-//
-//    @Bean
-//    public CorsFilter corsFilter() {
-//        // 初始化cors配置对象
-//        CorsConfiguration configuration = new CorsConfiguration();
-//        // 允许跨域的域名,如果要携带cookie,不能写*。*:代表所有域名都可以跨域访问
-//        configuration.addAllowedOrigin("*");
-//        configuration.setAllowCredentials(true); // 允许携带cookie
-//        configuration.addAllowedMethod("*"); // 代表所有的请求方法:GET POST PUT Delete。。。。
-//        configuration.addAllowedHeader("*"); // 允许携带任何头信息
-//
-//        // 初始化cors配置源对象
-//        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
-//        configurationSource.registerCorsConfiguration("/**", configuration);
-//
-//        // 返回corsFilter实例,参数:cors配置源对象
-//        return new CorsFilter(configurationSource);
-//    }
-//
-//    /**
-//     * 实现静态资源访问,但是这里仅仅提供了classpath下static文件夹的转发
-//     * 对于解决其他目录的需要重新修改
-//     * @param registry
-//     */
+
+    @Bean
+    public CorsFilter corsFilter() {
+        // 初始化cors配置对象
+        CorsConfiguration configuration = new CorsConfiguration();
+        // 允许跨域的域名,如果要携带cookie,不能写*。*:代表所有域名都可以跨域访问
+        configuration.addAllowedOrigin("*");
+        configuration.setAllowCredentials(true); // 允许携带cookie
+        configuration.addAllowedMethod("*"); // 代表所有的请求方法:GET POST PUT Delete。。。。
+        configuration.addAllowedHeader("*"); // 允许携带任何头信息
+
+        // 初始化cors配置源对象
+        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
+        configurationSource.registerCorsConfiguration("/**", configuration);
+
+        // 返回corsFilter实例,参数:cors配置源对象
+        return new CorsFilter(configurationSource);
+    }
+
+    /**
+     * 实现静态资源访问,但是这里仅仅提供了classpath下static文件夹的转发
+     * 对于解决其他目录的需要重新修改
+     * @param registry
+     */
 //    @Override
 //    public void addResourceHandlers(ResourceHandlerRegistry registry) {
 //        registry.addResourceHandler("/**")
 //                .addResourceLocations("classpath:/static/**")
 //                .addResourceLocations(fileLocal);//映射本地静态资源
 //    }
-//
-//
-//
-//
-//}
+
+
+
+
+}

+ 164 - 164
src/main/java/com/imed/costaccount/common/shiro/OAuth2Filter.java

@@ -1,164 +1,164 @@
-//package com.imed.costaccount.common.shiro;
-//
-//import cn.hutool.core.util.StrUtil;
-//import cn.hutool.json.JSONUtil;
-//import com.imed.costaccount.common.util.Result;
-//import com.imed.costaccount.common.config.RedisUtil;
-//import com.imed.costaccount.common.token.JwtUtil;
-//import com.imed.costaccount.common.token.ThreadLocalToken;
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.shiro.authc.AuthenticationException;
-//import org.apache.shiro.authc.AuthenticationToken;
-//import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.context.annotation.Scope;
-//import org.springframework.stereotype.Component;
-//import org.springframework.web.bind.annotation.RequestMethod;
-//
-//import javax.servlet.FilterChain;
-//import javax.servlet.ServletException;
-//import javax.servlet.ServletRequest;
-//import javax.servlet.ServletResponse;
-//import javax.servlet.http.HttpServletRequest;
-//import javax.servlet.http.HttpServletResponse;
-//import java.io.IOException;
-//
-//@Slf4j
-//@Scope("prototype")
-//@Component
-//public class OAuth2Filter extends AuthenticatingFilter {
-//
-//    @Autowired
-//    private JwtUtil jwtUtil;
-//
-//    @Autowired
-//    private ThreadLocalToken local;
-//
-//    @Autowired
-//    private RedisUtil redisUtil;
-//
-//
-//    @Value("${pfm.jwt.expire}")
-//    private int expire;
-//
-//    /**
-//     * 判断是否需要交由shiro处理,一般options 请求类型不需要
-//     * @return <code>true</code> if request should be allowed access
-//     * @param request
-//     * @param response
-//     * @param mappedValue
-//     */
-//    @Override
-//    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
-//        HttpServletRequest req = (HttpServletRequest) request;
-//        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
-//            return true;
-//        }
-//        return false;
-//    }
-//
-//    /**
-//     * 将token封装为auth2Token 返回交由shiro处理
-//     * @param servletRequest
-//     * @param servletResponse
-//     * @return
-//     * @throws Exception
-//     */
-//    @Override
-//    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
-//        HttpServletRequest request = (HttpServletRequest) servletRequest;
-//        String token = this.getRequestToken(request);
-//        if (StrUtil.isBlank(token)) {
-//            return null;
-//        }
-//        return new OAuth2Token(token);
-//    }
-//
-//    /**
-//     * 验证token,并进行相应处理(是否过期,续期等)
-//     * @param request
-//     * @param response
-//     * @return
-//     * @throws Exception
-//     */
-//    @Override
-//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
-//        HttpServletRequest req = (HttpServletRequest) request;
-//        HttpServletResponse resp = (HttpServletResponse) response;
-//        resp.setContentType("text/html");
-//        resp.setCharacterEncoding("UTF-8");
-//        // 允许跨域
-//        resp.setHeader("Access-Control-Allow-Credentials", "true");
-//        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
-//
-//        local.clear();
-//        String token = this.getRequestToken(req);
-//        if (StrUtil.isBlank(token)) {
-//            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
-//            resp.getWriter().print(json);
-//            return false;
-//        }
-//        // 判断redis中是否存在该用户的token,如果不存在或者不一致那么标识token无效
-//        int userId = jwtUtil.getUserId(token);
-//        String str = (String) redisUtil.get(userId + "");
-//        if (StrUtil.isBlank(str)) {
-//            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
-//            resp.getWriter().print(json);
-//            return false;
-//        }
-//        if (!str.equalsIgnoreCase(token)) {
-//            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
-//            resp.getWriter().print(json);
-//            return false;
-//        }
-//
-//        // 内容是否过期
-//        try {
-//            jwtUtil.verifierToken(token);
-//        } catch (Exception e) {
-////            // 无效的令牌
-//            resp.setStatus(400);
-//            resp.getWriter().print("无效的令牌");
-//            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌"));
-//            resp.getWriter().print(json);
-//            return false;
-//        }
-//        // 执行realm
-//        local.setToken(token);
-//        return executeLogin(request, response);
-//    }
-//
-//    @Override
-//    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
-//        HttpServletRequest req = (HttpServletRequest) request;
-//        HttpServletResponse resp = (HttpServletResponse) response;
-//        resp.setContentType("text/html");
-//        resp.setCharacterEncoding("UTF-8");
-//        // 允许跨域
-//        resp.setHeader("Access-Control-Allow-Credentials", "true");
-//        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
-//        resp.setStatus(400);
-//        try {
-//            resp.getWriter().print(e.getMessage());
-//        } catch (IOException ioException) {
-//            ioException.printStackTrace();
-//        }
-//        return false;
-//    }
-//
-//
-//    private String getRequestToken(HttpServletRequest request) {
-//        String token = request.getHeader("token");
-//
-//        if (StrUtil.isBlank(token)) {
-//            token = request.getParameter("token");
-//        }
-//        return token;
-//    }
-//
-//    @Override
-//    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
-//        super.doFilterInternal(request, response, chain);
-//    }
-//}
+package com.imed.costaccount.common.shiro;
+
+import cn.hutool.core.util.StrUtil;
+import cn.hutool.json.JSONUtil;
+import com.imed.costaccount.common.token.RedisUtil;
+import com.imed.costaccount.common.util.Result;
+import com.imed.costaccount.common.token.JwtUtil;
+import com.imed.costaccount.common.token.ThreadLocalToken;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Slf4j
+@Scope("prototype")
+@Component
+public class OAuth2Filter extends AuthenticatingFilter {
+
+    @Autowired
+    private JwtUtil jwtUtil;
+
+    @Autowired
+    private ThreadLocalToken local;
+
+    @Autowired
+    private RedisUtil redisUtil;
+
+
+    @Value("${pfm.jwt.expire}")
+    private int expire;
+
+    /**
+     * 判断是否需要交由shiro处理,一般options 请求类型不需要
+     * @return <code>true</code> if request should be allowed access
+     * @param request
+     * @param response
+     * @param mappedValue
+     */
+    @Override
+    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
+        HttpServletRequest req = (HttpServletRequest) request;
+        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * 将token封装为auth2Token 返回交由shiro处理
+     * @param servletRequest
+     * @param servletResponse
+     * @return
+     * @throws Exception
+     */
+    @Override
+    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
+        HttpServletRequest request = (HttpServletRequest) servletRequest;
+        String token = this.getRequestToken(request);
+        if (StrUtil.isBlank(token)) {
+            return null;
+        }
+        return new OAuth2Token(token);
+    }
+
+    /**
+     * 验证token,并进行相应处理(是否过期,续期等)
+     * @param request
+     * @param response
+     * @return
+     * @throws Exception
+     */
+    @Override
+    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
+        HttpServletRequest req = (HttpServletRequest) request;
+        HttpServletResponse resp = (HttpServletResponse) response;
+        resp.setContentType("text/html");
+        resp.setCharacterEncoding("UTF-8");
+        // 允许跨域
+        resp.setHeader("Access-Control-Allow-Credentials", "true");
+        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
+
+        local.clear();
+        String token = this.getRequestToken(req);
+        if (StrUtil.isBlank(token)) {
+            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
+            resp.getWriter().print(json);
+            return false;
+        }
+        // 判断redis中是否存在该用户的token,如果不存在或者不一致那么标识token无效
+        int userId = jwtUtil.getUserId(token);
+        String str = (String) redisUtil.get(userId + "");
+        if (StrUtil.isBlank(str)) {
+            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
+            resp.getWriter().print(json);
+            return false;
+        }
+        if (!str.equalsIgnoreCase(token)) {
+            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌,请登录"));
+            resp.getWriter().print(json);
+            return false;
+        }
+
+        // 内容是否过期
+        try {
+            jwtUtil.verifierToken(token);
+        } catch (Exception e) {
+//            // 无效的令牌
+            resp.setStatus(400);
+            resp.getWriter().print("无效的令牌");
+            String json = JSONUtil.toJsonStr(Result.errorMsg(499, "无效的令牌"));
+            resp.getWriter().print(json);
+            return false;
+        }
+        // 执行realm
+        local.setToken(token);
+        return executeLogin(request, response);
+    }
+
+    @Override
+    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
+        HttpServletRequest req = (HttpServletRequest) request;
+        HttpServletResponse resp = (HttpServletResponse) response;
+        resp.setContentType("text/html");
+        resp.setCharacterEncoding("UTF-8");
+        // 允许跨域
+        resp.setHeader("Access-Control-Allow-Credentials", "true");
+        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
+        resp.setStatus(400);
+        try {
+            resp.getWriter().print(e.getMessage());
+        } catch (IOException ioException) {
+            ioException.printStackTrace();
+        }
+        return false;
+    }
+
+
+    private String getRequestToken(HttpServletRequest request) {
+        String token = request.getHeader("token");
+
+        if (StrUtil.isBlank(token)) {
+            token = request.getParameter("token");
+        }
+        return token;
+    }
+
+    @Override
+    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
+        super.doFilterInternal(request, response, chain);
+    }
+}

+ 82 - 88
src/main/java/com/imed/costaccount/common/shiro/OAuth2Realm.java

@@ -1,90 +1,84 @@
-//package com.imed.costaccount.common.shiro;
-//
-//import cn.hutool.core.util.StrUtil;
-//import com.imed.costaccount.common.token.JwtUtil;
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.shiro.authc.AuthenticationException;
-//import org.apache.shiro.authc.AuthenticationInfo;
-//import org.apache.shiro.authc.AuthenticationToken;
-//import org.apache.shiro.authc.SimpleAuthenticationInfo;
-//import org.apache.shiro.authz.AuthorizationInfo;
-//import org.apache.shiro.authz.SimpleAuthorizationInfo;
-//import org.apache.shiro.realm.AuthorizingRealm;
-//import org.apache.shiro.subject.PrincipalCollection;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.stereotype.Component;
-//
-//import java.util.Arrays;
-//import java.util.Objects;
-//import java.util.Set;
-//import java.util.stream.Collectors;
-//
-///**
-// * 认证和授权在这里操作
-// */
-//@Slf4j
-//@Component
-//public class OAuth2Realm extends AuthorizingRealm {
-//
-//    @Autowired
-//    private JwtUtil jwtUtil;
-//
-//
-//    /**
-//     * 是否需要认证
-//     * @param token
-//     * @return
-//     */
-//    @Override
-//    public boolean supports(AuthenticationToken token) {
-//        return token instanceof com.imed.costaccount.common.shiro.OAuth2Token;
-//    }
-//
-//    /**
-//     * 登录认证
-//     * @param token token
-//     * @return
-//     * @throws AuthenticationException
-//     */
-//    @Override
-//    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
-//        String principal = (String) token.getPrincipal();
-//        if (StrUtil.isEmpty(principal)) {
-//            log.error("当前请求未携带token");
-////            throw new PfmException(PfmExceptionEnum.ForbiddenException);
-//            // TODO: 2021/7/23
+package com.imed.costaccount.common.shiro;
+
+import cn.hutool.core.util.StrUtil;
+import com.imed.costaccount.common.token.JwtUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shiro.authc.AuthenticationException;
+import org.apache.shiro.authc.AuthenticationInfo;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.realm.AuthorizingRealm;
+import org.apache.shiro.subject.PrincipalCollection;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * 认证和授权在这里操作
+ */
+@Slf4j
+@Component
+public class OAuth2Realm extends AuthorizingRealm {
+
+    @Autowired
+    private JwtUtil jwtUtil;
+
+
+    /**
+     * 是否需要认证
+     * @param token
+     * @return
+     */
+    @Override
+    public boolean supports(AuthenticationToken token) {
+        return token instanceof com.imed.costaccount.common.shiro.OAuth2Token;
+    }
+
+    /**
+     * 登录认证
+     * @param token token
+     * @return
+     * @throws AuthenticationException
+     */
+    @Override
+    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+        String principal = (String) token.getPrincipal();
+        if (StrUtil.isEmpty(principal)) {
+            log.error("当前请求未携带token");
+//            throw new PfmException(PfmExceptionEnum.ForbiddenException);
+            // TODO: 2021/7/23
+        }
+        int userId = jwtUtil.getUserId(principal);
+//        SysEmployee employee = employeeService.queryById(userId);
+//        if (Objects.isNull(employee)) {
+//            log.error("当前token{}", principal);
+//            throw new PfmException(499, "登录失败,请重新登录");
 //        }
-//        int userId = jwtUtil.getUserId(principal);
-////        SysEmployee employee = employeeService.queryById(userId);
-////        if (Objects.isNull(employee)) {
-////            log.error("当前token{}", principal);
-////            throw new PfmException(499, "登录失败,请重新登录");
-////        }
-//
-//        // TODO: 2021/7/23
-//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(null, principal, getName());
+
+        // TODO: 2021/7/23
+        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(null, principal, getName());
+        return info;
+    }
+
+    /**
+     * 授权对象
+     * @param principals
+     * @return
+     */
+    @Override
+    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+//        SysEmployee employee = (SysEmployee) principals.getPrimaryPrincipal();
+
+        // todo 根据后续需求完成动态配置
+//        String managerRole = employee.getManagerRole();
+//        String[] split = managerRole.split(StrUtil.COMMA);
+//        Set<String> permissions = Arrays.stream(split).map(RoleEnum::getRole).collect(Collectors.toSet());
+//        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
+//        info.setStringPermissions(permissions);
 //        return info;
-//    }
-//
-//    /**
-//     * 授权对象
-//     * @param principals
-//     * @return
-//     */
-//    @Override
-//    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
-////        SysEmployee employee = (SysEmployee) principals.getPrimaryPrincipal();
-//
-//        // todo 根据后续需求完成动态配置
-////        String managerRole = employee.getManagerRole();
-////        String[] split = managerRole.split(StrUtil.COMMA);
-////        Set<String> permissions = Arrays.stream(split).map(RoleEnum::getRole).collect(Collectors.toSet());
-////        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
-////        info.setStringPermissions(permissions);
-////        return info;
-//        // TODO: 2021/7/23
-//        return null;
-//    }
-//
-//
-//}
+        // TODO: 2021/7/23
+        return null;
+    }
+
+
+}

+ 37 - 37
src/main/java/com/imed/costaccount/common/shiro/OAuth2Token.java

@@ -1,37 +1,37 @@
-//package com.imed.costaccount.common.shiro;
-//
-//import org.apache.shiro.authc.AuthenticationToken;
-//
-//public class OAuth2Token implements AuthenticationToken {
-//    private String token;
-//
-//    public OAuth2Token(String token) {
-//        this.token = token;
-//    }
-//
-//    public String getToken() {
-//        return token;
-//    }
-//
-//    public void setToken(String token) {
-//        this.token = token;
-//    }
-//
-//    /**
-//     * 返回授权主体
-//     * @return
-//     */
-//    @Override
-//    public Object getPrincipal() {
-//        return token;
-//    }
-//
-//    /**
-//     * 返回授权凭证
-//     * @return
-//     */
-//    @Override
-//    public Object getCredentials() {
-//        return token;
-//    }
-//}
+package com.imed.costaccount.common.shiro;
+
+import org.apache.shiro.authc.AuthenticationToken;
+
+public class OAuth2Token implements AuthenticationToken {
+    private String token;
+
+    public OAuth2Token(String token) {
+        this.token = token;
+    }
+
+    public String getToken() {
+        return token;
+    }
+
+    public void setToken(String token) {
+        this.token = token;
+    }
+
+    /**
+     * 返回授权主体
+     * @return
+     */
+    @Override
+    public Object getPrincipal() {
+        return token;
+    }
+
+    /**
+     * 返回授权凭证
+     * @return
+     */
+    @Override
+    public Object getCredentials() {
+        return token;
+    }
+}

+ 77 - 77
src/main/java/com/imed/costaccount/common/shiro/ShiroConfig.java

@@ -1,77 +1,77 @@
-//package com.imed.costaccount.common.shiro;
-//
-//import org.apache.shiro.mgt.SecurityManager;
-//import org.apache.shiro.spring.LifecycleBeanPostProcessor;
-//import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
-//import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
-//import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
-//import org.springframework.context.annotation.Bean;
-//import org.springframework.context.annotation.Configuration;
-//
-//import javax.servlet.Filter;
-//import java.util.HashMap;
-//import java.util.LinkedHashMap;
-//import java.util.Map;
-//
-//@Configuration
-//public class ShiroConfig {
-//
-//    @Bean("securityManager")
-//    public SecurityManager securityManager(OAuth2Realm realm) {
-//        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
-//        defaultWebSecurityManager.setRealm(realm);
-//        defaultWebSecurityManager.setRememberMeManager(null);
-//        return defaultWebSecurityManager;
-//    }
-//
-//    @Bean("shiroFilter")
-//    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager,OAuth2Filter filter) {
-//        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
-//        filterFactoryBean.setSecurityManager(securityManager);
-//        // OAuth2过滤
-//        Map<String, Filter> filters = new HashMap<>();
-//        filters.put("oauth2", filter);
-//        filterFactoryBean.setFilters(filters);
-//
-//        // HTTP请求过滤
-//        Map<String, String> filterMap = new LinkedHashMap<>();
-//        filterMap.put("/webjars/**", "anon");
-//        filterMap.put("/druid/**", "anon");
-//        filterMap.put("/app/**", "anon");
-//        filterMap.put("/sys/login", "anon");
-//        filterMap.put("/swagger/**", "anon");
-//        filterMap.put("/v2/api-docs", "anon");
-//        filterMap.put("/swagger-ui.html", "anon");
-//        filterMap.put("/static/js/**", "anon");
-//        filterMap.put("/doc.html", "anon");
-//        filterMap.put("/swagger-resources/**", "anon");
-//        filterMap.put("/captcha.jpg", "anon");
-//        filterMap.put("/user/register", "anon");
-//        filterMap.put("/employee/demo", "anon");
-//        filterMap.put("/employee/login", "anon");
-//        filterMap.put("/**/*.jpg", "anon");
-//        filterMap.put("/**/*.png", "anon");
-//
-//        // 除了以上的,其他的都使用oauth2过滤器
-//        filterMap.put("/**", "oauth2");
-//        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
-//        return filterFactoryBean;
-//    }
-//
-//    @Bean("lifecycleBeanPostProcessor")
-//    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
-//        return new LifecycleBeanPostProcessor();
-//    }
-//
-//    /**
-//     * AOP 使用 的通知点增强点
-//     * @param securityManager
-//     * @return
-//     */
-//    @Bean
-//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
-//        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
-//        advisor.setSecurityManager(securityManager);
-//        return advisor;
-//    }
-//}
+package com.imed.costaccount.common.shiro;
+
+import org.apache.shiro.mgt.SecurityManager;
+import org.apache.shiro.spring.LifecycleBeanPostProcessor;
+import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
+import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
+import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import javax.servlet.Filter;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+@Configuration
+public class ShiroConfig {
+
+    @Bean("securityManager")
+    public SecurityManager securityManager(OAuth2Realm realm) {
+        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
+        defaultWebSecurityManager.setRealm(realm);
+        defaultWebSecurityManager.setRememberMeManager(null);
+        return defaultWebSecurityManager;
+    }
+
+    @Bean("shiroFilter")
+    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager,OAuth2Filter filter) {
+        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
+        filterFactoryBean.setSecurityManager(securityManager);
+        // OAuth2过滤
+        Map<String, Filter> filters = new HashMap<>();
+        filters.put("oauth2", filter);
+        filterFactoryBean.setFilters(filters);
+
+        // HTTP请求过滤
+        Map<String, String> filterMap = new LinkedHashMap<>();
+        filterMap.put("/webjars/**", "anon");
+        filterMap.put("/druid/**", "anon");
+        filterMap.put("/app/**", "anon");
+        filterMap.put("/sys/login", "anon");
+        filterMap.put("/swagger/**", "anon");
+        filterMap.put("/v2/api-docs", "anon");
+        filterMap.put("/swagger-ui.html", "anon");
+        filterMap.put("/static/js/**", "anon");
+        filterMap.put("/doc.html", "anon");
+        filterMap.put("/swagger-resources/**", "anon");
+        filterMap.put("/captcha.jpg", "anon");
+        filterMap.put("/user/register", "anon");
+        filterMap.put("/employee/demo", "anon");
+        filterMap.put("/employee/login", "anon");
+        filterMap.put("/**/*.jpg", "anon");
+        filterMap.put("/**/*.png", "anon");
+
+        // 除了以上的,其他的都使用oauth2过滤器
+        filterMap.put("/**", "oauth2");
+        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
+        return filterFactoryBean;
+    }
+
+    @Bean("lifecycleBeanPostProcessor")
+    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
+        return new LifecycleBeanPostProcessor();
+    }
+
+    /**
+     * AOP 使用 的通知点增强点
+     * @param securityManager
+     * @return
+     */
+    @Bean
+    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
+        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
+        advisor.setSecurityManager(securityManager);
+        return advisor;
+    }
+}

+ 45 - 45
src/main/java/com/imed/costaccount/common/token/JwtUtil.java

@@ -1,45 +1,45 @@
-//package com.imed.costaccount.common.token;
-//
-//import cn.hutool.core.date.DateField;
-//import cn.hutool.core.date.DateTime;
-//import cn.hutool.core.date.DateUtil;
-//import com.auth0.jwt.JWT;
-//import com.auth0.jwt.algorithms.Algorithm;
-//import com.auth0.jwt.interfaces.DecodedJWT;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.beans.factory.annotation.Value;
-//import org.springframework.stereotype.Component;
-//
-//import java.time.Duration;
-//import java.util.Date;
-//
-//@Component
-//public class JwtUtil {
-//
-//    @Value("${pfm.jwt.secret}")
-//    private String secret;
-//
-//    @Value("${pfm.jwt.expire}")
-//    private Integer expire;
-//
-//    @Autowired
-//    private RedisUtil redisUtil;
-//
-//    public String createToken(int empId) {
-//        Date date = DateUtil.offset(new DateTime(), DateField.DAY_OF_YEAR, expire).toJdkDate();
-//        Algorithm algorithm = Algorithm.HMAC256(secret);
-//        String token = JWT.create().withClaim("userId", empId).withExpiresAt(date).sign(algorithm);
-//        redisUtil.set(empId + "", token, Duration.ofDays(expire));
-//        return token;
-//    }
-//
-//    public int getUserId(String token) {
-//        DecodedJWT decode = JWT.decode(token);
-//        return decode.getClaim("userId").asInt();
-//    }
-//
-//    public void verifierToken(String token) {
-//        Algorithm algorithm = Algorithm.HMAC256(secret);
-//        JWT.require(algorithm).build().verify(token);
-//    }
-//}
+package com.imed.costaccount.common.token;
+
+import cn.hutool.core.date.DateField;
+import cn.hutool.core.date.DateTime;
+import cn.hutool.core.date.DateUtil;
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import java.time.Duration;
+import java.util.Date;
+
+@Component
+public class JwtUtil {
+
+    @Value("${cost.jwt.secret}")
+    private String secret;
+
+    @Value("${cost.jwt.expire}")
+    private Integer expire;
+
+    @Autowired
+    private RedisUtil redisUtil;
+
+    public String createToken(int empId) {
+        Date date = DateUtil.offset(new DateTime(), DateField.DAY_OF_YEAR, expire).toJdkDate();
+        Algorithm algorithm = Algorithm.HMAC256(secret);
+        String token = JWT.create().withClaim("userId", empId).withExpiresAt(date).sign(algorithm);
+        redisUtil.set(empId + "", token, Duration.ofDays(expire));
+        return token;
+    }
+
+    public int  getUserId(String token) {
+        DecodedJWT decode = JWT.decode(token);
+        return decode.getClaim("userId").asInt();
+    }
+
+    public void verifierToken(String token) {
+        Algorithm algorithm = Algorithm.HMAC256(secret);
+        JWT.require(algorithm).build().verify(token);
+    }
+}

+ 6 - 0
src/main/resources/application.yml

@@ -1,3 +1,9 @@
 spring:
   profiles:
     active: dev
+
+
+cost:
+  jwt:
+    secret: 12321312asdsdsfdfsd
+    expire: 1