From 8e8bb38d07ae0dbb013cab0ab850e43773b463f3 Mon Sep 17 00:00:00 2001 From: 2510220824 <2510220824@qq.com> Date: Tue, 28 Sep 2021 18:13:27 +0800 Subject: [PATCH] =?UTF-8?q?add:=E5=A2=9E=E5=8A=A0IDM=E5=8D=95=E7=82=B9?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E5=8F=8A=E4=BF=AE=E6=94=B9=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exception/SysRuntimeExceptionHandler.java | 31 +++ .../exception/TokenRuntimeException.java | 24 +++ .../da/login/rest/LoginRestController.java | 197 +++++------------- .../com/adc/da/login/security/JWTFilter.java | 158 -------------- .../com/adc/da/login/security/JWTRealm.java | 145 ------------- .../com/adc/da/login/security/JWTToken.java | 32 --- .../da/login/security/TokenInterceptor.java | 80 +++++++ .../adc/da/login/security/WebMvcConfig.java | 38 ++++ .../com/adc/da/login/util/CacheUtils.java | 84 -------- .../java/com/adc/da/login/util/IDMUtil.java | 72 +++++++ .../java/com/adc/da/login/util/JWTUtil.java | 79 ------- .../java/com/adc/da/login/util/JwtUtils.java | 60 ++++++ .../java/com/adc/da/login/util/UserUtils.java | 13 -- .../main/advice/AdcDaBaseExceptionAdvice.java | 1 + .../da/main/advice/ShiroExceptionAdvice.java | 41 ---- .../da/main/config/DefinitionUrlConfig.java | 44 ---- .../com/adc/da/main/config/ShiroConfig.java | 151 -------------- .../da/main/config/ShiroConfiguration.java | 92 -------- .../java/com/adc/da/sys/entity/UserEO.java | 9 + 19 files changed, 364 insertions(+), 987 deletions(-) create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/SysRuntimeExceptionHandler.java create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/TokenRuntimeException.java delete mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTFilter.java delete mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTRealm.java delete mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTToken.java create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/security/TokenInterceptor.java create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java delete mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/util/CacheUtils.java create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/util/IDMUtil.java delete mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/util/JWTUtil.java create mode 100644 adc-da-jwtLogin/src/main/java/com/adc/da/login/util/JwtUtils.java delete mode 100644 adc-da-main/src/main/java/com/adc/da/main/advice/ShiroExceptionAdvice.java delete mode 100644 adc-da-main/src/main/java/com/adc/da/main/config/DefinitionUrlConfig.java delete mode 100644 adc-da-main/src/main/java/com/adc/da/main/config/ShiroConfig.java delete mode 100644 adc-da-main/src/main/java/com/adc/da/main/config/ShiroConfiguration.java diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/SysRuntimeExceptionHandler.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/SysRuntimeExceptionHandler.java new file mode 100644 index 00000000..93006848 --- /dev/null +++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/SysRuntimeExceptionHandler.java @@ -0,0 +1,31 @@ +package com.adc.da.login.exception; + +import com.adc.da.http.ResponseMessage; +import com.adc.da.http.Result; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +/** + * 全局异常处理 + * + * @author ch + * @version 1.0.0 + * @since 1.0.0 + *
+ * Created at 2020/8/6 5:03 下午 + */ +@RestControllerAdvice +public class SysRuntimeExceptionHandler { + + @ExceptionHandler(TokenRuntimeException.class) + public ResponseMessage tokenRuntimeException(TokenRuntimeException e) { + e.printStackTrace(); + return Result.error(e.getCode(), e.getMsg()); + } + + @ExceptionHandler(Exception.class) + public ResponseMessage handlerException(Exception e){ + e.printStackTrace(); + return Result.error(); + } +} diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/TokenRuntimeException.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/TokenRuntimeException.java new file mode 100644 index 00000000..089bf175 --- /dev/null +++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/exception/TokenRuntimeException.java @@ -0,0 +1,24 @@ +package com.adc.da.login.exception; + +import lombok.Data; + +/** + * 自定义 token 异常 + * + * @author ch + * @version 1.0.0 + * @since 1.0.0 + *
+ * Created at 2020/8/6 4:58 下午 + */ +@Data +public class TokenRuntimeException extends RuntimeException{ + + private String code = "401"; + private String msg; + + public TokenRuntimeException(String msg) { + this.msg = msg; + } + +} diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/rest/LoginRestController.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/rest/LoginRestController.java index 589c05a9..65f4d611 100644 --- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/rest/LoginRestController.java +++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/rest/LoginRestController.java @@ -3,14 +3,11 @@ package com.adc.da.login.rest; import com.adc.da.http.ResponseMessage; import com.adc.da.http.Result; -import com.adc.da.login.util.JWTUtil; -import com.adc.da.login.util.UserUtils; -import com.adc.da.login.vo.LoginVO; -import com.adc.da.sys.entity.MenuEO; +import com.adc.da.login.exception.TokenRuntimeException; +import com.adc.da.login.util.IDMUtil; +import com.adc.da.login.util.JwtUtils; import com.adc.da.sys.entity.UserEO; import com.adc.da.sys.service.IUserEOService; -import com.adc.da.sys.vo.UserVO; -import com.adc.da.util.Encodes; import com.adc.da.util.PasswordUtils; import com.alibaba.fastjson.JSON; import io.swagger.annotations.Api; @@ -18,20 +15,20 @@ import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import sun.misc.BASE64Encoder; +import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.constraints.NotNull; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; @Validated @@ -43,84 +40,10 @@ public class LoginRestController { @Autowired private IUserEOService userService; - - - /** - * 读取配置文件判断是否需要开启Base64加密,默认值为false - */ - @Value("${isPassEncrypted:false}") - private boolean isPassEncrypted; - - /** - * 无缓存,用于校验 - */ - private static final String NO_CACHE = "no-cache"; - - /** - * 登录失败Map字段 - */ - private static final String LOGIN_FAIL_MAP = "loginFailMap"; - - /** - * 验证码 - */ - private static final Object VERIFY_CODE = "VerifyCode"; - - /** - * 10分钟内最大错误次数 - */ - @Value("${maxLoginErrorCount:3}") - private int maxLoginErrorCount; - - - /** - * 读取验证码模式配置, - * 1为不开启,2为开启,3为三次输错用户名或密码才开启, - * 默认为1 - *
- * 若配置文件缺少该参数,将设置为1
- */
- @Value("${verifyCodeMode:1}")
- private int verifyCodeMode;
-
-
-// @ApiOperation(value = "登录")
-// @PostMapping(value = "/login")
-// @ResponseBody
-// public ResponseMessage
- * 权限信息.(授权):
- * 1、如果用户正常退出,缓存自动清空;
- * 2、如果用户非正常退出,缓存自动清空;
- * 3、如果我们修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
- * (需要手动编程进行实现;放在service进行调用)
- * 在权限修改后调用realm中的方法,realm已经由spring管理,所以从spring中获取realm实例,调用clearCached方法;
- * :Authorization 是授权访问控制,用于对用户进行的操作授权,证明该用户是否允许进行当前操作,如访问某个链接,某个资源文件等。
- *
- * @param principalCollection
- * @return
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- String username = JWTUtil.getUsername(principalCollection.toString());
- if (username == null) {
- return null;
- }
- UserEO user = userEOService.getUserByLoginNameNotDeleted(username);
- if (user != null) {
- try {
- return UserUtils.getAuthInfo();
- } catch (NumberFormatException e) {
- logger.error("AuthorizationInfo NumberFormatException", e);
- } catch (Exception e) {
- logger.error("AuthorizationInfo Exception", e);
- }
- }
- return null;
- }
-
- /**
- * 认证信息(身份验证)
- * Authentication 是用来验证用户身份
- *
- * @param authenticationToken
- * @return
- * @throws AuthenticationException
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
- String token = (String) authenticationToken.getCredentials();
- // 解密获得username,用于和数据库进行对比
- String username = JWTUtil.getUsername(token);
- if (username == null) {
- throw new AuthenticationException("token 无效!");
- }
-
- UserEO user = userEOService.getUserByLoginNameNotDeleted(username);
- if (user == null) {
- throw new AuthenticationException("用户"+username+"不存在") ;
- }
-
- if (!JWTUtil.verify(token, username,user.getUsid(),user.getPassword())) {
- throw new AuthenticationException("账户密码错误!");
- }
- return new SimpleAuthenticationInfo(token, token, "jwtRealm");
- }
-
- /**
- * 授权用户信息
- */
- public static class Principal implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- private String id;
-
- private String loginName;
-
- private transient Map
+ * Created at 2020/7/30 2:19 下午
+ */
+@Component
+@Slf4j
+public class TokenInterceptor extends HandlerInterceptorAdapter {
+
+ // 注入jwt工具类
+ @Autowired
+ private JwtUtils jwtUtils;
+
+ // 重写 前置拦截方法
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+ // 1、从请求头中获取token
+ String token = request.getHeader("token");
+
+ // 2、判断 token 是否存在
+ if (token == null ||"".equals(token)) {
+ log.error("未登录");
+ // 这里可以自定义 抛出 token 异常
+ throw new TokenRuntimeException("未登录");
+ }
+
+ // 3、解析token
+ Claims claim = jwtUtils.getClaimsByToken(token);
+
+ if (null == claim) {
+ System.out.println("token 解析错误");
+ // 这里可以自定义 抛出 token 异常
+ throw new TokenRuntimeException("token 解析错误");
+ }
+
+ // 4、判断 token 是否过期
+ Date expiration = claim.getExpiration();
+ boolean tokenExpired = jwtUtils.isTokenExpired(expiration);
+ if (tokenExpired) {
+ System.out.println("token已过期,请重新登录");
+ // 这里可以自定义 抛出 token 异常
+ throw new TokenRuntimeException("token已过期,请重新登录");
+ }
+
+ // 5、 从 token 中获取员工信息
+ String subject = claim.getSubject();
+
+ // 6、去数据库中匹配 id 是否存在 (这里直接写死了)
+ if (null == subject ) {
+ System.out.println("员工不存在");
+ // 这里可以自定义 抛出 token 异常
+ throw new TokenRuntimeException("员工不存在");
+ }
+
+ // 7、成功后 设置想设置的属性,比如员工姓名
+ request.setAttribute("userId", subject);
+ request.setAttribute("userName", "张三");
+
+ return true;
+ }
+}
diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java
new file mode 100644
index 00000000..f1762d8b
--- /dev/null
+++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/WebMvcConfig.java
@@ -0,0 +1,38 @@
+package com.adc.da.login.security;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
+import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+@Configuration
+public class WebMvcConfig implements WebMvcConfigurer {
+
+ @Autowired
+ private TokenInterceptor interceptor;
+
+ @Bean
+ public TokenInterceptor getSecurityInterceptor() {
+ return new TokenInterceptor();
+ }
+
+ /**
+ * 重写添加拦截器
+ */
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
+
+ addInterceptor.excludePathPatterns("/api/login");
+ addInterceptor.excludePathPatterns("/v2/api-docs");
+ addInterceptor.excludePathPatterns("/webjars/**");
+ addInterceptor.excludePathPatterns("/swagger-resources/**");
+ addInterceptor.excludePathPatterns("/swagger-ui.html");
+ addInterceptor.excludePathPatterns("/doc.html");
+
+ // 添加自定义拦截器,并拦截对应 url
+ addInterceptor.addPathPatterns("/**");
+ }
+}
diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/CacheUtils.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/CacheUtils.java
deleted file mode 100644
index a855ef5b..00000000
--- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/CacheUtils.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package com.adc.da.login.util;
-
-import com.adc.da.util.SpringContextHolder1;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-
-/**
- * Cache工具类
- */
-public class CacheUtils {
-
- private CacheUtils() {
- super();
- }
-
- private static CacheManager cacheManager = (CacheManager) SpringContextHolder1.getBean("ehCacheManagerFactoryBean");
-
- private static final String SYS_CACHE = "sysCache";
-
- private static final String ERROR_CACHE = "errorCache";
-
- public static Object get(String key) {
- return get(SYS_CACHE, key);
- }
-
- public static void put(String key, Object value) {
- put(SYS_CACHE, key, value);
- }
-
- public static void remove(String key) {
- remove(SYS_CACHE, key);
- }
-
- //配合main模块下resource/cache/ehcache-local.xml
- //
+ * Created at 2020/7/30 2:23 下午
+ */
+@Component
+public class JwtUtils {
+
+ // 过期时间
+ private static long expire = 604800;
+ // 秘钥
+ private static String secret = "HSyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
+
+ /**
+ * 创建一个token
+ *
+ * @param userId
+ * @return
+ */
+ public String generateToken(String userId) {
+ Date now = new Date();
+ Date expireDate = new Date(now.getTime() + expire);
+ return Jwts.builder().setHeaderParam("type", "JWT").setSubject(userId).setIssuedAt(now)
+ .setExpiration(expireDate).signWith(
+ SignatureAlgorithm.HS512, secret).compact();
+ }
+
+ /**
+ * 解析token
+ */
+ public Claims getClaimsByToken(String token) {
+ try {
+ return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
+ } catch (Exception e) {
+ System.out.println("validate is token error");
+ return null;
+ }
+ }
+
+ /**
+ * 判断 token 是否过期
+ */
+ public boolean isTokenExpired(Date expiration){
+ return expiration.before(new Date());
+ }
+
+}
diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/UserUtils.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/UserUtils.java
index 0a8b15db..01507f03 100644
--- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/UserUtils.java
+++ b/adc-da-jwtLogin/src/main/java/com/adc/da/login/util/UserUtils.java
@@ -1,8 +1,6 @@
package com.adc.da.login.util;
import cn.hutool.core.util.ObjectUtil;
-import com.adc.da.login.security.JWTRealm;
-import com.adc.da.login.security.JWTRealm.Principal;
import com.adc.da.sys.entity.MenuEO;
import com.adc.da.sys.entity.RoleEO;
import com.adc.da.sys.entity.UserEO;
@@ -12,13 +10,11 @@ import com.adc.da.sys.service.IUserEOService;
import com.adc.da.util.SpringContextHolder1;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.session.InvalidSessionException;
-import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -218,15 +214,6 @@ public class UserUtils {
public static Map 字段列表:> userMenu(){
- return Result.success(UserUtils.getMenuList());
+ @ApiOperation(value = "登出")
+ @PostMapping(value = "/logout")
+ public void logout(HttpServletRequest request, HttpServletResponse response){
+ Cookie[] cookies = request.getCookies();
+ try {
+ for(int i=0;i < cookies.length;i++) {
+ Cookie cookie = new Cookie(cookies[i].getName(), null);
+ cookie.setMaxAge(0);
+ cookie.setPath("testsso1.foton.com.cn");//根据你创建cookie的路径进行填写
+ response.addCookie(cookie);
+ }
+ }catch(Exception ex) {
+ System.out.println("清空Cookies发生异常!");
+
+ }
}
- /**
- * 修改当前登录用户密码
- */
- @ApiOperation(value = "修改密码")
- @PutMapping("/updatePassword")
- @ResponseBody
- public ResponseMessage updatePassword(@NotNull(message = "请输入旧密码") @RequestParam String oldPassword,
- @NotNull(message = "请输入新密码") @RequestParam String newPassword) {
- // 前台如果base64传输密文,则需要解码
- if (isPassEncrypted) {
- oldPassword = new String(Encodes.decodeBase64(oldPassword), StandardCharsets.UTF_8);
- newPassword = new String(Encodes.decodeBase64(newPassword), StandardCharsets.UTF_8);
- }
- if (!newPassword.matches("^(?![0-9]*$)[a-zA-Z0-9]{6,10}$")) {
- return Result.error("r0018", "新密码必须6-10位且不能纯数字");
- }
- userService.updatePassword(UserUtils.getUserId(), oldPassword, newPassword);
- return Result.success();
- }
}
diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTFilter.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTFilter.java
deleted file mode 100644
index 03366e66..00000000
--- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTFilter.java
+++ /dev/null
@@ -1,158 +0,0 @@
-package com.adc.da.login.security;
-
-import com.alibaba.fastjson.JSONObject;
-import com.alibaba.fastjson.serializer.SerializerFeature;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.subject.Subject;
-import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
-import org.springframework.http.HttpStatus;
-import org.springframework.web.bind.annotation.RequestMethod;
-
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.PrintWriter;
-
-/**
- * JWT过滤器,针对请求进行拦截过滤
- */
-@Slf4j
-public class JWTFilter extends BasicHttpAuthenticationFilter {
- //10分钟后刷新token
- private static final int tokenRefreshInterval = 60 * 10;
-
- /**
- * 这里我们详细说明下为什么最终返回的都是true,即允许访问
- *例如我们提供一个地址 GET /article
- *登入用户和游客看到的内容是不同的
- *如果在这里返回了false,请求会被直接拦截,用户看不到任何东西
- *所以我们在这里返回true,Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入
- *如果有些资源只有登入用户才能访问,我们只需要在方法上面加上 @RequiresAuthentication 注解即可
- *但是这样做有一个缺点,就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法),但实际上对应用影响不大
- */
- @Override
- protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
- if (isLoginAttempt(request, response)) {
- try {
- return executeLogin(request, response);
- } catch (Exception e) {
- responseError(request, response);
- return false;
- }
- }else{
- return false;
- }
-
- }
-
-
- /**
- * 检测header里面是否包含Authorization字段
- * @param request
- * @param response
- * @return
- */
- @Override
- protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
- HttpServletRequest req = (HttpServletRequest) request;
- String authorization = req.getHeader("Authorization");
- log.debug("判断用户是否想要登录:{}",authorization);
- return authorization != null;
- }
-
-
- /**
- * 认证失败后调用的方法
- * @param request
- * @param response
- * @return
- * @throws Exception
- */
- @Override
- protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
- this.responseError(request,response);
- return false;
- }
-
- @Override
- protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception{
- HttpServletRequest httpServletRequest = (HttpServletRequest) request;
- String authorization = httpServletRequest.getHeader("Authorization");
- log.debug("用户开始认证x:{}",authorization);
- JWTToken token = new JWTToken(authorization);
- // 提交给realm进行登入,如果错误他会抛出异常并被捕获
- getSubject(request, response).login(token);
- // 如果没有抛出异常则代表登入成功,返回true
- return true;
- }
-
- @Override
- protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
- if(token instanceof JWTToken){
- JWTToken jwtToken= (JWTToken) token;
- //TODO 此处需要设置token自动续期功能
- }
-
- return true;
- }
-
- @Override
- protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
- HttpServletRequest httpServletRequest = (HttpServletRequest) request;
- HttpServletResponse httpServletResponse = (HttpServletResponse) response;
- httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
- httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
- httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
- httpServletResponse.addHeader("Access-Control-Allow-Headers", "Authorization");
- // 跨域时会首先发送一个option请求,这里我们给option请求直接返回正常状态
- if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
- httpServletResponse.setStatus(HttpStatus.OK.value());
- return false;
- }
- return super.preHandle(request, response);
- }
-
- /**
- * 将非法请求跳转到 /401
- */
- private void responseError(ServletRequest req, ServletResponse resp) {
- try {
- HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
- if(httpServletResponse.isCommitted()){
- return;
- }
- //此处需要返回统一的错误对象 以便应对统一的异常处理
- JSONObject result=new JSONObject();
- result.put("respCode","A404");
- result.put("ok",false);
- result.put("message","认证失败");
- result.put("data",null);
- httpServletResponse.setHeader("Content-Type", "application/json");
- httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
- httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST");
- httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
- httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
- // response.setHeader("Content-type", "application/json;charset=UTF-8");
- httpServletResponse.setStatus(HttpServletResponse.SC_OK);
- httpServletResponse.setContentType("application/json;charset=UTF-8");
- httpServletResponse.setCharacterEncoding("UTF-8");
- PrintWriter printWriter = httpServletResponse.getWriter();
- printWriter.append(result.toString(SerializerFeature.WriteMapNullValue));
- printWriter.flush();
-// httpServletResponse.sendRedirect("/401");
- } catch (IOException e) {
- log.error(e.getMessage());
- }
- }
-
-
- private boolean shouldTokenRefresh(JWTToken jwtToken) {
-// LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
-// return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
- return true;
- }
-
-}
diff --git a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTRealm.java b/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTRealm.java
deleted file mode 100644
index 529af2b5..00000000
--- a/adc-da-jwtLogin/src/main/java/com/adc/da/login/security/JWTRealm.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package com.adc.da.login.security;
-
-import com.adc.da.login.util.JWTUtil;
-import com.adc.da.login.util.UserUtils;
-import com.adc.da.sys.entity.UserEO;
-import com.adc.da.sys.service.IUserEOService;
-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.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import java.io.Serializable;
-import java.util.*;
-
-@Service
-public class JWTRealm extends AuthorizingRealm {
-
- private static final Logger logger = LoggerFactory.getLogger(JWTRealm.class);
-
- private IUserEOService userEOService;
-
- /**
- * JWT签名密钥
- */
- public static final String SECRET = "AyX3TWpHIkPfE9rqaDiYV416d0nguURLQ8vhNzBlK7MGcOJjmoZ2w5stSeCFxb16";
-
- @Autowired
- public void setUserEOService(IUserEOService userEOService) {
- this.userEOService = userEOService;
- }
-
- /**
- * 必须重写此方法,不然Shiro会报错
- */
- @Override
- public boolean supports(AuthenticationToken token) {
- return token instanceof JWTToken;
- }
-
-
-
- /**
- * 此方法调用hasRole,hasPermission的时候才会进行回调.
- *
*