修复使用jwt后导致的用户管理功能异常

pull/829/head
648540858 2023-04-15 09:03:41 +08:00
parent d46fc9de82
commit cf1696e0d6
9 changed files with 29 additions and 122 deletions

View File

@ -117,7 +117,8 @@ QQ群不再接受新成员直接进入希望大家多多参考文档用户
# 授权协议 # 授权协议
本项目自有代码使用宽松的MIT协议在保留版权信息的情况下可以自由应用于各自商用、非商业的项目。 但是本项目也零碎的使用了一些其他的开源代码,在商用的情况下请自行替代或剔除; 由于使用本项目而产生的商业纠纷或侵权行为一概与本项目及开发者无关,请自行承担法律风险。 在使用本项目代码时,也应该在授权协议中同时表明本项目依赖的第三方库的协议 本项目自有代码使用宽松的MIT协议在保留版权信息的情况下可以自由应用于各自商用、非商业的项目。 但是本项目也零碎的使用了一些其他的开源代码,在商用的情况下请自行替代或剔除; 由于使用本项目而产生的商业纠纷或侵权行为一概与本项目及开发者无关,请自行承担法律风险。 在使用本项目代码时,也应该在授权协议中同时表明本项目依赖的第三方库的协议
# 付费技术支持 # 技术支持
建议加入[知识星球](https://t.zsxq.com/0drbw002x)可以获取更多的教程以及更加及时的回复。
如果项目需要一对一的技术支持或者棘手的问题需要解决请发送邮件到648540858@qq.com 如果项目需要一对一的技术支持或者棘手的问题需要解决请发送邮件到648540858@qq.com
# 致谢 # 致谢

View File

@ -2,6 +2,8 @@ package com.genersoft.iot.vmp.conf.security;
import com.genersoft.iot.vmp.conf.UserSetting; import com.genersoft.iot.vmp.conf.UserSetting;
import com.genersoft.iot.vmp.conf.security.dto.JwtUser; 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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -75,7 +77,13 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
} }
// 构建UsernamePasswordAuthenticationToken,这里密码为null是因为提供了正确的JWT,实现自动登录 // 构建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); SecurityContextHolder.getContext().setAuthentication(token);
chain.doFilter(request, response); chain.doFilter(request, response);
} }

View File

@ -37,7 +37,7 @@ public class JwtUtils {
*/ */
public static final long expirationTime = 30; 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 { try {
/** /**
* iss (issuer) * iss (issuer)
@ -64,6 +64,7 @@ public class JwtUtils {
//添加自定义参数,必须是字符串类型 //添加自定义参数,必须是字符串类型
claims.setClaim("username", username); claims.setClaim("username", username);
claims.setClaim("password", password); claims.setClaim("password", password);
claims.setClaim("roleId", roleId);
//jws //jws
JsonWebSignature jws = new JsonWebSignature(); JsonWebSignature jws = new JsonWebSignature();
@ -118,8 +119,10 @@ public class JwtUtils {
String username = (String) claims.getClaimValue("username"); String username = (String) claims.getClaimValue("username");
String password = (String) claims.getClaimValue("password"); String password = (String) claims.getClaimValue("password");
Long roleId = (Long) claims.getClaimValue("roleId");
jwtUser.setUserName(username); jwtUser.setUserName(username);
jwtUser.setPassword(password); jwtUser.setPassword(password);
jwtUser.setRoleId(roleId.intValue());
return jwtUser; return jwtUser;
} catch (InvalidJwtException e) { } catch (InvalidJwtException e) {

View File

@ -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<String, Object> map = new HashMap<>();
map.put("code","0");
map.put("msg","登录失败");
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(map));
}
}

View File

@ -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);
}
}

View File

@ -53,14 +53,10 @@ public class SecurityUtils {
Authentication authentication = getAuthentication(); Authentication authentication = getAuthentication();
if(authentication!=null){ if(authentication!=null){
Object principal = authentication.getPrincipal(); Object principal = authentication.getPrincipal();
if(principal!=null && !"anonymousUser".equals(principal)){ if(principal!=null && !"anonymousUser".equals(principal.toString())){
// LoginUser user = (LoginUser) authentication.getPrincipal();
String username = (String) principal; User user = (User) principal;
User user = new User(); return new LoginUser(user, LocalDateTime.now());
user.setUsername(username);
LoginUser loginUser = new LoginUser(user, LocalDateTime.now());
return loginUser;
} }
} }
return null; return null;

View File

@ -47,16 +47,6 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
* *
*/ */
@Autowired @Autowired
private LoginFailureHandler loginFailureHandler;
/**
*
*/
@Autowired
private LoginSuccessHandler loginSuccessHandler;
/**
*
*/
@Autowired
private LogoutHandler logoutHandler; private LogoutHandler logoutHandler;
/** /**
* *

View File

@ -25,6 +25,8 @@ public class JwtUser {
private String password; private String password;
private int roleId;
private TokenStatus status; private TokenStatus status;
public String getUserName() { public String getUserName() {
@ -50,4 +52,12 @@ public class JwtUser {
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
} }

View File

@ -57,7 +57,7 @@ public class UserController {
if (user == null) { if (user == null) {
throw new ControllerException(ErrorCode.ERROR100.getCode(), "用户名或密码错误"); throw new ControllerException(ErrorCode.ERROR100.getCode(), "用户名或密码错误");
}else { }else {
String jwt = JwtUtils.createToken(username, password); String jwt = JwtUtils.createToken(username, password, user.getRole().getId());
response.setHeader(JwtUtils.getHeader(), jwt); response.setHeader(JwtUtils.getHeader(), jwt);
user.setAccessToken(jwt); user.setAccessToken(jwt);
} }