当前前端获得token之后 每次请求只需要发送token就行 就不必在认证过滤
    前端的token获取之后 是存储在请求头中authorization:dasdqwdqwdwqd(token)
    1)获取请求头中的键为authorization的值
    2)判断是否为null 如果为null就交给下一个过滤器去登录(就是认证过滤器)
    3)就从token中获取权限字符串和用户名
    4)通过用户名和token集合生成后端的token对象
    5)把此token对象存入安全上下文
    6)交给下一个过滤器

    1. /**
    2. * @author by itheima
    3. * @Date 2022/1/23
    4. * @Description 权限认证filter
    5. */
    6. public class AuthenticationFilter extends OncePerRequestFilter {
    7. @Override
    8. protected void doFilterInternal(HttpServletRequest request,
    9. HttpServletResponse response,
    10. FilterChain filterChain) throws ServletException, IOException {
    11. //1.从http请求头中获取token
    12. String token = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
    13. if (token==null) {
    14. //用户未登录,则放行,去登录拦截
    15. filterChain.doFilter(request,response);
    16. return;
    17. }
    18. //2.token存在则,安全校验
    19. try {
    20. String username = JwtTokenUtil.getUsername(token);
    21. //获取以逗号间隔的权限拼接字符串
    22. String userRole = JwtTokenUtil.getUserRole(token);
    23. //组装token
    24. UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.commaSeparatedStringToAuthorityList(userRole));
    25. //将生成的token存入上下文
    26. SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    27. //放行资源
    28. filterChain.doFilter(request,response);
    29. } catch (Exception e) {
    30. e.printStackTrace();
    31. // throw new RuntimeException("token无效");
    32. response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    33. HashMap<String, String> info = new HashMap<>();
    34. info.put("status","0");
    35. info.put("ex","无效的token凭证");
    36. response.getWriter().write(new Gson().toJson(info));
    37. }
    38. }
    39. }

    把此过滤器对象加入到ioc容器 并设置过滤器前后执行顺序 (此过滤器先于认证过滤器)

    1. /**
    2. * 配置授权策略
    3. * @param http
    4. * @throws Exception
    5. */
    6. @Override
    7. protected void configure(HttpSecurity http) throws Exception {
    8. http
    9. //坑-过滤器要添加在默认过滤器之前,否则,登录失效
    10. .addFilterBefore(myUserNamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
    11. //上面的是认证过滤器 下面的是权限过滤器
    12. .authenticationFilter(), MyUsernamePasswordAuthenticationFilter.class)
    13. .csrf().disable();
    14. }
    15. @Bean
    16. public AuthenticationFilter authenticationFilter() throws Exception {
    17. //设置默认登录路径
    18. AuthenticationFilter authenticationFilter =
    19. new AuthenticationFilter();
    20. return authenticationFilter;
    21. }