zoukankan      html  css  js  c++  java
  • springsecurity-微服务-springsecurity授权过滤器

    当用户登录后再次访问时,我们需要拿到用户的token,去查redis的用户权限,并赋予用户权限。差不多就这个过程,但很多步骤,springsecurity都封装好了,下面写一个授权过滤器,主要重写一个方法doFilterInternal,该方法的目的的话就是获取redis中用户的权限列表,并设置到一个类里面,方便下一个过滤器来使用。

    public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
        private TokenManager tokenManager;
        private RedisTemplate redisTemplate;
    
        public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,RedisTemplate redisTemplate) {
            super(authManager);
            this.tokenManager = tokenManager;
            this.redisTemplate = redisTemplate;
        }
    
        @Override
        protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            logger.info("================="+req.getRequestURI());
            if(req.getRequestURI().indexOf("admin") == -1) {
                chain.doFilter(req, res);
                return;
            }
    
            UsernamePasswordAuthenticationToken authentication = null;
            try {
                authentication = getAuthentication(req);
            } catch (Exception e) {
                ResponseUtil.out(res, R.error());
            }
    
            if (authentication != null) {
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                ResponseUtil.out(res, R.error());
            }
            chain.doFilter(req, res);
        }
    
        private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
            // token置于header里
            String token = request.getHeader("token");
            if (token != null && !"".equals(token.trim())) {
                String userName = tokenManager.getUserFromToken(token);
    
                List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                for(String permissionValue : permissionValueList) {
                    if(StringUtils.isEmpty(permissionValue)) continue;
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                    authorities.add(authority);
                }
    
                if (!StringUtils.isEmpty(userName)) {
                    return new UsernamePasswordAuthenticationToken(userName, token, authorities);
                }
                return null;
            }
            return null;
        }
    }
  • 相关阅读:
    win10右键在此处打开CMD
    练习1-20 编写程序detab,将输入中的制表符替换成适当数目的空格.
    编写一个程序,打印输入中单词长度的直方图.垂直方向
    王爽 汇编 实验14
    python 文件
    函数和方法
    python-格式化字符串
    MPC&MAGIC
    python-super1
    小知识点
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384828.html
Copyright © 2011-2022 走看看