5.自定义Spring Security AuthenticationFilter
最后,让我们编写JWTAuthenticationFilter
从请求中获取 JWT 令牌,对其进行验证,加载与令牌关联的用户,并将其传递给 Spring Security -
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JwtTokenProvider tokenProvider;
@Autowired
private CustomUserDetailsService customUserDetailsService;
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}
在上面filter
,我们首先解析从Authorization
请求头中检索到的 JWT 并获取用户的 Id。之后,我们从数据库中加载用户的详细信息,并在 Spring Security 的上下文中设置身份验证。
注意,上面的数据库命中filter
是可选的。您还可以在 JWT 声明中对用户的用户名和角色进行编码,并UserDetails
通过解析来自 JWT 的声明来创建对象。这将避免数据库命中。
但是,从数据库加载用户的当前详细信息可能仍然有帮助。例如,如果用户的角色已更改,或者用户在创建此 JWT 后更新了他的密码,您可能希望禁止使用此 JWT 登录。
6.自定义注释访问当前登录的用户
Spring security 提供了一个注解@AuthenticationPrincipal
,用于访问控制器中当前经过身份验证的用户。
以下CurrentUser
注释是注释的包装@AuthenticationPrincipal
。
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {
}
我们创建了一个元注释,这样我们就不会在项目中的任何地方都被 Spring Security 相关的注释所束缚。这减少了对 Spring Security 的依赖。因此,如果我们决定从我们的项目中删除 Spring Security,我们可以通过简单地更改CurrentUser
注解轻松地做到这一点——
好吧,伙计们!我们已完成所需的所有安全配置。