Spring Security JWT(Json Web Token) 登录实现
使用 Spring Security 实现 JWT 登录,我们只需要在 Spring Security 的众多 Filter 中添加一个我们用于 JWT 登录的 Filter,以下是一个demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class JwtAuthenticationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER); if(null == tokenHeader || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) { filterChain.doFilter(request, response); return; } try { String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, ""); String username = JwtTokenUtils.getUserName(token); List<Role> roleList = JwtTokenUtils.getUserRole(token); List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>(); roleList.forEach(item -> { roles.add(new GrantedAuthority() { @Override public String getAuthority() { return item.getName(); } }); }); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, roles); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } catch (Exception e) { logger.error("无法验证令牌"); } filterChain.doFilter(request, response); } }
|
1 2 3 4 5 6 7 8
| @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { RestUtil.response(response, SystemCode.AccessTokenError); } }
|
1 2 3 4 5 6 7 8
| @Component public class JwtAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException { RestUtil.response(httpServletResponse, SystemCode.AccessDenied); } }
|
完成以上,我们只需要把这些配置进 Spring Security 就可以了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @Configuration @EnableWebSecurity public class SecurityConfig {
@Configuration public static class SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.headers().frameOptions().disable(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).accessDeniedHandler(jwtAccessDeniedHandler) .and().csrf().disable() .cors(); } } }
|
至此,我们已经完成了 Spring Security 中使用 JWT 的基本操作了。