• 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;
        }
    }
  • 相关阅读:
    javascript运算符
    javascript字符串转数字
    javascript的变量声明和数据类型
    javascript的历史和入门
    CSS中定位
    CSS中盒子模型
    CSS操作表格的边框和表格的属性示例代码
    常用的CSS样式示例代码
    CSS伪类选择器
    CSS选择器
  • 原文地址:https://www.cnblogs.com/ibcdwx/p/14384828.html
Copyright © 2020-2023  润新知