/**
-
验证用户名密码正确后 生成一个token并将token返回给客户端
-
@author huwei
*/
public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {private final StringRedisTemplate stringRedisTemplate;
private final AuthenticationManager authenticationManager;
public JwtAuthenticationFilter(AuthenticationManager authenticationManager,StringRedisTemplate stringRedisTemplate) {
this.authenticationManager = authenticationManager;
this.stringRedisTemplate = stringRedisTemplate;
}/**
- 验证操作 接收并解析用户凭证
*/
@Override
public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {
// 从输入流中获取到登录的信息
// 创建一个token并调用authenticationManager.authenticate() 让Spring security进行验证
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getParameter(“username”),request.getParameter(“password”)));
}
/**
- 验证【成功】后调用的方法
- 若验证成功 生成token并返回
*/
@Override
protected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response,FilterChain chain,Authentication authResult) throws IOException {
User user= (User) authResult.getPrincipal();
// 从User中获取权限信息
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
// 创建Token
String token = JwtTokenUtils.createToken(user.getUsername(),authorities);
stringRedisTemplate.opsForValue().set(user.getUsername(), token);
// 设置编码 防止乱码问题
response.setCharacterEncoding(“UTF-8”);
response.setContentType(“application/json; charset=utf-8”);
response.setHeader(SecurityConstants.TOKEN_HEADER, token);
response.setContentType(“text/json;charset=utf-8”);
response.getWriter().write(“登录成功”);
}
/**
- 验证【失败】调用的方法
*/
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
String returnData="";
// 账号过期
if (failed instanceof AccountExpiredException) {
returnData=“账号过期”;
}
// 密码错误
else if (failed instanceof BadCredentialsException) {
returnData=“密码错误”;
}
// 密码过期
else if (failed instanceof CredentialsExpiredException) {
returnData=“密码过期”;
}
// 账号不可用
else if (failed instanceof DisabledException) {
returnData=“账号不可用”;
}
//账号锁定
else if (failed instanceof LockedException) {
returnData=“账号锁定”;
}
// 用户不存在
else if (failed instanceof InternalAuthenticationServiceException) {
returnData=“用户不存在”;
}
// 其他错误
else{
returnData=“未知异常”;
}
// 处理编码方式 防止中文乱码
response.setContentType(“text/json;charset=utf-8”);
// 将反馈塞到HttpServletResponse中返回给前台
response.getWriter().write(returnData);
}
}
- 验证操作 接收并解析用户凭证