• 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;
        }
    }
  • 相关阅读:
    写在之前
    Fedora Core 3安装杂记(三)
    Fedora Core 3安装杂记(一)
    Firefox 1.0真的挺好用的
    发现Google加了英文页面翻译功能(Beta)
    Fedora Core 3安装杂记(四)
    在FC3的日子里……
    ASP面向对象编程探讨及比较
    显卡千万不能买带风扇的……
    字符串(strcat)
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384828.html
Copyright © 2020-2023  润新知