当前前端获得token之后 每次请求只需要发送token就行 就不必在认证过滤
前端的token获取之后 是存储在请求头中authorization:dasdqwdqwdwqd(token)
1)获取请求头中的键为authorization的值
2)判断是否为null 如果为null就交给下一个过滤器去登录(就是认证过滤器)
3)就从token中获取权限字符串和用户名
4)通过用户名和token集合生成后端的token对象
5)把此token对象存入安全上下文
6)交给下一个过滤器
/*** @author by itheima* @Date 2022/1/23* @Description 权限认证filter*/public class AuthenticationFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {//1.从http请求头中获取tokenString token = request.getHeader(JwtTokenUtil.TOKEN_HEADER);if (token==null) {//用户未登录,则放行,去登录拦截filterChain.doFilter(request,response);return;}//2.token存在则,安全校验try {String username = JwtTokenUtil.getUsername(token);//获取以逗号间隔的权限拼接字符串String userRole = JwtTokenUtil.getUserRole(token);//组装tokenUsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.commaSeparatedStringToAuthorityList(userRole));//将生成的token存入上下文SecurityContextHolder.getContext().setAuthentication(authenticationToken);//放行资源filterChain.doFilter(request,response);} catch (Exception e) {e.printStackTrace();// throw new RuntimeException("token无效");response.setContentType(MediaType.APPLICATION_JSON_VALUE);HashMap<String, String> info = new HashMap<>();info.put("status","0");info.put("ex","无效的token凭证");response.getWriter().write(new Gson().toJson(info));}}}
把此过滤器对象加入到ioc容器 并设置过滤器前后执行顺序 (此过滤器先于认证过滤器)
/*** 配置授权策略* @param http* @throws Exception*/@Overrideprotected void configure(HttpSecurity http) throws Exception {http//坑-过滤器要添加在默认过滤器之前,否则,登录失效.addFilterBefore(myUserNamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)//上面的是认证过滤器 下面的是权限过滤器.authenticationFilter(), MyUsernamePasswordAuthenticationFilter.class).csrf().disable();}@Beanpublic AuthenticationFilter authenticationFilter() throws Exception {//设置默认登录路径AuthenticationFilter authenticationFilter =new AuthenticationFilter();return authenticationFilter;}
