Spring Security JWT

Posted cearnach

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Security JWT相关的知识,希望对你有一定的参考价值。

当登录成功的时候,返回以个authentication 的请求头,用户下次请求的时候,只需要附上这个请求头,就可以直接进行资源的访问了.

pom.xml

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.7.0</version>
</dependency>

 

编写一个过滤器

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private static final String APPLICATION_JSON = "application/json;charset=utf-8";

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authToken = request.getHeader(jwtProperties.getHeader());
        if (!StringUtils.isEmpty(authToken)) {
            JwtToken jwtToken;
            try {
                jwtToken = jwtTokenUtil.getJwtToken(authToken);
                String username = jwtToken.getUsername();
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.info("认证通过:{}", username);
                    }
                }
            } catch (InvalidJwtTokenException invalidJwtTokenException) {
                response.setContentType(APPLICATION_JSON);
                log.error(InvalidJwtTokenException.INVALID_JWT_TOKEN_EXCEPTION);
                ResultVO<String> resultVO = new ResultVO<>();
                resultVO.setSuccess(false);
                resultVO.setMsg(InvalidJwtTokenException.INVALID_JWT_TOKEN_EXCEPTION);
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultVO));
                writer.close();
                return;
            }
        }
        chain.doFilter(request, response);
    }
}

然后在配置类里面添加

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}

 





以上是关于Spring Security JWT的主要内容,如果未能解决你的问题,请参考以下文章

Spring Security + JWT 实现单点登录,还有谁不会??

Spring Security jwt 身份验证

Sping Boot + Spring Security + Mybaits + Logback + JWT验证项目开发框架搭建

Spring Security OAuth2 在没有 JWT 的情况下无法工作

社交登录,spring-security-oauth2 和 spring-security-jwt?

Spring Security + JWT 实现单点登录,还有谁不会。。。