springSecurity使用中AuthenticationService与预期不符
@Service
public class AuthenticationServiceImpl implements AuthenticationService {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache<UsersLogin> redisCache;
@Override
public ResponseWrapper<Object> login(RequestWrapper<UsersLogin> requestWrapper) {
//AuthenticationManager authentication进行用户认证
UsersLogin usersLogin=requestWrapper.getData();
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(usersLogin.getUsername(),usersLogin.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if (Objects.isNull(authenticate)){
throw new RuntimeException("用户名或密码错误");
}
//如果认证通过。使用userid生成jwt 。jwt存入ResponseWrapper返回
UsersLogin user= (UsersLogin) authenticate.getPrincipal();
String userId = user.getUserId().toString();
String jwt = JwtTokenUtil.generateToken("login"+userId);
//把完整的用户信息存入redis userId作为key
redisCache.cacheObject("login"+userId,user,10, TimeUnit.MINUTES);
//把token响应给前端
return ResponseWrapper.success(null,jwt);
}
}
如果密码错误,上面这段代码执行到Authentication authenticate = authenticationManager.authenticate(authenticationToken);时抛出异常:
org.springframework.security.authentication.BadCredentialsException: 用户名或密码错误
并没有像网上的教程那样把authenticate 赋值为null
这是我练习的参考案例
感觉网上security的教程都是这里判断是否为null,而Ai软件的提示是这样的:
在代码中,使用authenticationManager.authenticate(authenticationToken)方法进行用户认证后,如果认证失败,会抛出AuthenticationException异常,而不是返回null。因此,判断authenticate是否为null是不正确的。应该使用try-catch语句来捕获AuthenticationException异常,如果捕获到异常,则说明认证失败。正确代码应该是下面这样的
try {
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
// 如果认证通过了 使用userid 生成一个jwt jwt 存入ResponseResult 返回
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
String userId = loginUser.getUser().getId().toString();
String jwt = JwtUtil.createJWT(userId);
HashMap<String,String> map = new HashMap<>();
map.put("token",jwt);
// 把完整的用户信息存入redis userid 作为key
redisCache.setCacheObject("login:"+userId,loginUser);
return new ResponseResult(200,"登录成功",map);
} catch (AuthenticationException e) {
throw new RuntimeException("登录失败");
}
现在不知道到底该怎么做了