zoukankan      html  css  js  c++  java
  • 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()); } }
  • 相关阅读:
    http和https
    openstack
    openstack安全问题
    openstack优势
    java多线程实现方式
    python多进程实现的几种方式
    Java 在提取url 生成图片以及正则表达式
    idea 生成 可执行文件
    dw cs6 支持高分辨率
    svchost.exe 大量占用的问题
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384769.html
Copyright © 2011-2022 走看看