From cf1696e0d6f148445bb21dca6f066d8e07bc3234 Mon Sep 17 00:00:00 2001 From: 648540858 <648540858@qq.com> Date: Sat, 15 Apr 2023 09:03:41 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BD=BF=E7=94=A8jwt?= =?UTF-8?q?=E5=90=8E=E5=AF=BC=E8=87=B4=E7=9A=84=E7=94=A8=E6=88=B7=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=8A=9F=E8=83=BD=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +- .../security/JwtAuthenticationFilter.java | 10 ++- .../iot/vmp/conf/security/JwtUtils.java | 5 +- .../conf/security/LoginFailureHandler.java | 65 ------------------- .../conf/security/LoginSuccessHandler.java | 36 ---------- .../iot/vmp/conf/security/SecurityUtils.java | 10 +-- .../vmp/conf/security/WebSecurityConfig.java | 10 --- .../iot/vmp/conf/security/dto/JwtUser.java | 10 +++ .../iot/vmp/vmanager/user/UserController.java | 2 +- 9 files changed, 29 insertions(+), 122 deletions(-) delete mode 100644 src/main/java/com/genersoft/iot/vmp/conf/security/LoginFailureHandler.java delete mode 100644 src/main/java/com/genersoft/iot/vmp/conf/security/LoginSuccessHandler.java diff --git a/README.md b/README.md index 9f803675..d3ad3ac4 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,8 @@ QQ群不再接受新成员直接进入,希望大家多多参考文档,用户 # 授权协议 本项目自有代码使用宽松的MIT协议,在保留版权信息的情况下可以自由应用于各自商用、非商业的项目。 但是本项目也零碎的使用了一些其他的开源代码,在商用的情况下请自行替代或剔除; 由于使用本项目而产生的商业纠纷或侵权行为一概与本项目及开发者无关,请自行承担法律风险。 在使用本项目代码时,也应该在授权协议中同时表明本项目依赖的第三方库的协议 -# 付费技术支持 +# 技术支持 +建议加入[知识星球](https://t.zsxq.com/0drbw002x)可以获取更多的教程以及更加及时的回复。 如果项目需要一对一的技术支持,或者棘手的问题需要解决,请发送邮件到648540858@qq.com # 致谢 diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java index 27151eee..f35b5bd8 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtAuthenticationFilter.java @@ -2,6 +2,8 @@ package com.genersoft.iot.vmp.conf.security; import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.security.dto.JwtUser; +import com.genersoft.iot.vmp.storager.dao.dto.Role; +import com.genersoft.iot.vmp.storager.dao.dto.User; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -75,7 +77,13 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { } // 构建UsernamePasswordAuthenticationToken,这里密码为null,是因为提供了正确的JWT,实现自动登录 - UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, jwtUser.getPassword(), new ArrayList<>() ); + User user = new User(); + user.setUsername(jwtUser.getUserName()); + user.setPassword(jwtUser.getPassword()); + Role role = new Role(); + role.setId(jwtUser.getRoleId()); + user.setRole(role); + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, jwtUser.getPassword(), new ArrayList<>() ); SecurityContextHolder.getContext().setAuthentication(token); chain.doFilter(request, response); } diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java index 57911b04..c9c7b680 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/JwtUtils.java @@ -37,7 +37,7 @@ public class JwtUtils { */ public static final long expirationTime = 30; - public static String createToken(String username, String password) { + public static String createToken(String username, String password, Integer roleId) { try { /** * “iss” (issuer) 发行人 @@ -64,6 +64,7 @@ public class JwtUtils { //添加自定义参数,必须是字符串类型 claims.setClaim("username", username); claims.setClaim("password", password); + claims.setClaim("roleId", roleId); //jws JsonWebSignature jws = new JsonWebSignature(); @@ -118,8 +119,10 @@ public class JwtUtils { String username = (String) claims.getClaimValue("username"); String password = (String) claims.getClaimValue("password"); + Long roleId = (Long) claims.getClaimValue("roleId"); jwtUser.setUserName(username); jwtUser.setPassword(password); + jwtUser.setRoleId(roleId.intValue()); return jwtUser; } catch (InvalidJwtException e) { diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/LoginFailureHandler.java b/src/main/java/com/genersoft/iot/vmp/conf/security/LoginFailureHandler.java deleted file mode 100644 index 9bbf2e7d..00000000 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/LoginFailureHandler.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.genersoft.iot.vmp.conf.security; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.*; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -@Component -public class LoginFailureHandler implements AuthenticationFailureHandler { - - private final static Logger logger = LoggerFactory.getLogger(LoginFailureHandler.class); - - @Autowired - private ObjectMapper objectMapper; - - @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { - - String username = request.getParameter("username"); - if (e instanceof AccountExpiredException) { - // 账号过期 - logger.info("[登录失败] - 用户[{}]账号过期", username); - - } else if (e instanceof BadCredentialsException) { - // 密码错误 - logger.info("[登录失败] - 用户[{}]密码/SIP服务器ID 错误", username); - - } else if (e instanceof CredentialsExpiredException) { - // 密码过期 - logger.info("[登录失败] - 用户[{}]密码过期", username); - - } else if (e instanceof DisabledException) { - // 用户被禁用 - logger.info("[登录失败] - 用户[{}]被禁用", username); - - } else if (e instanceof LockedException) { - // 用户被锁定 - logger.info("[登录失败] - 用户[{}]被锁定", username); - - } else if (e instanceof InternalAuthenticationServiceException) { - // 内部错误 - logger.error(String.format("[登录失败] - [%s]内部错误", username), e); - - } else { - // 其他错误 - logger.error(String.format("[登录失败] - [%s]其他错误", username), e); - } - Map map = new HashMap<>(); - map.put("code","0"); - map.put("msg","登录失败"); - response.setContentType("application/json;charset=UTF-8"); - response.getWriter().write(objectMapper.writeValueAsString(map)); - } -} diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/LoginSuccessHandler.java b/src/main/java/com/genersoft/iot/vmp/conf/security/LoginSuccessHandler.java deleted file mode 100644 index d26342ef..00000000 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/LoginSuccessHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.genersoft.iot.vmp.conf.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author lin - */ -@Component -public class LoginSuccessHandler implements AuthenticationSuccessHandler { - - private final static Logger logger = LoggerFactory.getLogger(LoginSuccessHandler.class); - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException { -// String username = request.getParameter("username"); -// httpServletResponse.setContentType("application/json;charset=UTF-8"); -// // 生成JWT,并放置到请求头中 -// String jwt = JwtUtils.createToken(authentication.getName(), ); -// httpServletResponse.setHeader(JwtUtils.getHeader(), jwt); -// ServletOutputStream outputStream = httpServletResponse.getOutputStream(); -// outputStream.write(JSON.toJSONString(ErrorCode.SUCCESS).getBytes(StandardCharsets.UTF_8)); -// outputStream.flush(); -// outputStream.close(); - -// logger.info("[登录成功] - [{}]", username); - } -} diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java b/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java index a8d35681..f012f7ef 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/SecurityUtils.java @@ -53,14 +53,10 @@ public class SecurityUtils { Authentication authentication = getAuthentication(); if(authentication!=null){ Object principal = authentication.getPrincipal(); - if(principal!=null && !"anonymousUser".equals(principal)){ -// LoginUser user = (LoginUser) authentication.getPrincipal(); + if(principal!=null && !"anonymousUser".equals(principal.toString())){ - String username = (String) principal; - User user = new User(); - user.setUsername(username); - LoginUser loginUser = new LoginUser(user, LocalDateTime.now()); - return loginUser; + User user = (User) principal; + return new LoginUser(user, LocalDateTime.now()); } } return null; diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java b/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java index 96ae6b91..1fbe3a4e 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/WebSecurityConfig.java @@ -47,16 +47,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { * 登出成功的处理 */ @Autowired - private LoginFailureHandler loginFailureHandler; - /** - * 登录成功的处理 - */ - @Autowired - private LoginSuccessHandler loginSuccessHandler; - /** - * 登出成功的处理 - */ - @Autowired private LogoutHandler logoutHandler; /** * 未登录的处理 diff --git a/src/main/java/com/genersoft/iot/vmp/conf/security/dto/JwtUser.java b/src/main/java/com/genersoft/iot/vmp/conf/security/dto/JwtUser.java index 1639d1fc..8921a308 100644 --- a/src/main/java/com/genersoft/iot/vmp/conf/security/dto/JwtUser.java +++ b/src/main/java/com/genersoft/iot/vmp/conf/security/dto/JwtUser.java @@ -25,6 +25,8 @@ public class JwtUser { private String password; + private int roleId; + private TokenStatus status; public String getUserName() { @@ -50,4 +52,12 @@ public class JwtUser { public void setPassword(String password) { this.password = password; } + + public int getRoleId() { + return roleId; + } + + public void setRoleId(int roleId) { + this.roleId = roleId; + } } diff --git a/src/main/java/com/genersoft/iot/vmp/vmanager/user/UserController.java b/src/main/java/com/genersoft/iot/vmp/vmanager/user/UserController.java index 157a3a81..5ffb02cb 100644 --- a/src/main/java/com/genersoft/iot/vmp/vmanager/user/UserController.java +++ b/src/main/java/com/genersoft/iot/vmp/vmanager/user/UserController.java @@ -57,7 +57,7 @@ public class UserController { if (user == null) { throw new ControllerException(ErrorCode.ERROR100.getCode(), "用户名或密码错误"); }else { - String jwt = JwtUtils.createToken(username, password); + String jwt = JwtUtils.createToken(username, password, user.getRole().getId()); response.setHeader(JwtUtils.getHeader(), jwt); user.setAccessToken(jwt); }