当前位置:   article > 正文

SpringSecurity分布式整合之重写认证的过滤器_authenticationmanager 重写

authenticationmanager 重写
  1. public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
  2. private AuthenticationManager authenticationManager;
  3. private RsaKeyProperties prop;
  4. public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
  5. this.authenticationManager = authenticationManager;
  6. this.prop = prop;
  7. }
  8. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  9. try {
  10. SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
  11. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
  12. return authenticationManager.authenticate(authRequest);
  13. }catch (Exception e){
  14. try {
  15. response.setContentType("application/json;charset=utf-8");
  16. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  17. PrintWriter out = response.getWriter();
  18. Map resultMap = new HashMap();
  19. resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
  20. resultMap.put("msg", "用户名或密码错误!");
  21. out.write(new ObjectMapper().writeValueAsString(resultMap));
  22. out.flush();
  23. out.close();
  24. }catch (Exception outEx){
  25. outEx.printStackTrace();
  26. }
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
  31. SysUser user = new SysUser();
  32. user.setUsername(authResult.getName());
  33. user.setRoles((List<SysRole>) authResult.getAuthorities());
  34. String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
  35. response.addHeader("Authorization", "Bearer "+token);
  36. try {
  37. response.setContentType("application/json;charset=utf-8");
  38. response.setStatus(HttpServletResponse.SC_OK);
  39. PrintWriter out = response.getWriter();
  40. Map resultMap = new HashMap();
  41. resultMap.put("code", HttpServletResponse.SC_OK);
  42. resultMap.put("msg", "认证通过!");
  43. out.write(new ObjectMapper().writeValueAsString(resultMap));
  44. out.flush();
  45. out.close();
  46. }catch (Exception outEx){
  47. outEx.printStackTrace();
  48. }
  49. }
  50. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/370523
推荐阅读
相关标签
  

闽ICP备14008679号