• springsecurity-微服务-springsecurity认证过滤器


    之前学习过一个过滤器UsernamePasswordAuthenticationFilter,里面有3个重要的方法,如下:

      1.attemptAuthentication:接收表单传过来的用户名和密码,并封装到一个类中返回

      2.successfulAuthentication:认证成功调用的方法

      3.unsuccessfulAuthentication:认证失败调用的方法。

    目前需要重写这3个方法,完成我们自己的逻辑,代码如下:

    public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    
        private AuthenticationManager authenticationManager;
        private TokenManager tokenManager;
        private RedisTemplate redisTemplate;
    
        public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
            this.authenticationManager = authenticationManager;
            this.tokenManager = tokenManager;
            this.redisTemplate = redisTemplate;
            this.setPostOnly(false);
            this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
        }
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
                throws AuthenticationException {
            try {
                User user = new ObjectMapper().readValue(req.getInputStream(), User.class);  //该User对象是我们自己提供的
    
                return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), new ArrayList<>()));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    
        }
    
        /**
         * 登录成功
         * @param req
         * @param res
         * @param chain
         * @param auth
         * @throws IOException
         * @throws ServletException
          认证成功后,把用户名和权限列表保存到redis中
    */ @Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { SecurityUser user = (SecurityUser) auth.getPrincipal(); String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername()); redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList()); ResponseUtil.out(res, R.ok().data("token", token)); } /** * 登录失败 * @param request * @param response * @param e * @throws IOException * @throws ServletException */ @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { ResponseUtil.out(response, R.error()); } }
  • 相关阅读:
    在线预览Office文档
    花生壳内网穿透
    Net core跨域
    EF链表查询
    Python冒泡排序、选择排序、插入排序、希尔排序、归并排序
    竟然可以这样学python!
    如何使用python打印9乘9乘法口诀表?
    python爬取小视频
    —用python写PDF转换器
    从0到1搭建个人博客-Django(三)
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384769.html
Copyright © 2020-2023  润新知