• 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()); } }
  • 相关阅读:
    用MFC(C++)实现拼音搜索
    MFC里ON_COMMAND_RANGE消息映射的ID问题
    01:MFC应用程序编程
    MFC笔记(DN)
    linuxmint系统定制与配置(2)-输入法
    linuxmint系统定制与配置(3)-字体
    linuxmint系统定制与配置(1)-系统初始配置
    笔记-读官方Git教程(2)~安装与配置
    笔记-读官方Git教程(1)~认识Git
    Python中多层List展平为一层
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384769.html
Copyright © 2020-2023  润新知