generated from Java-2025Fall/final-vibevault-template
更新 src/main/java/com/vibevault/security/JwtAuthenticationFilter.java
This commit is contained in:
parent
4e464d5957
commit
768876a4ce
@ -30,6 +30,9 @@ import java.util.List;
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@ -45,18 +48,47 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
@NonNull FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
|
||||
// TODO: 实现 JWT 认证逻辑
|
||||
// 1. 从请求头获取 Authorization
|
||||
final String authHeader = request.getHeader(AUTHORIZATION_HEADER);
|
||||
final String jwt;
|
||||
final String username;
|
||||
|
||||
// 2. 检查是否以 "Bearer " 开头
|
||||
// 3. 提取 token 并验证
|
||||
// 4. 如果有效,创建 Authentication 并设置到 SecurityContextHolder
|
||||
//
|
||||
// 提示:
|
||||
// - 使用 request.getHeader("Authorization") 获取头
|
||||
// - 使用 jwtService.extractUsername() 和 jwtService.isTokenValid()
|
||||
// - 使用 UsernamePasswordAuthenticationToken 创建认证对象
|
||||
// - 使用 SecurityContextHolder.getContext().setAuthentication() 设置
|
||||
|
||||
if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. 提取 token
|
||||
jwt = authHeader.substring(BEARER_PREFIX.length());
|
||||
username = jwtService.extractUsername(jwt); // 从token中提取用户名
|
||||
|
||||
// 4. 验证token有效性 + 安全上下文未被填充
|
||||
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
// 从数据库查询用户
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElse(null); // 若用户不存在,跳过认证
|
||||
|
||||
if (user != null && jwtService.isTokenValid(jwt, user)) {
|
||||
// [Challenge] 读取用户角色并构造权限列表
|
||||
List<SimpleGrantedAuthority> authorities = Collections.singletonList(
|
||||
new SimpleGrantedAuthority(user.getRole())
|
||||
);
|
||||
|
||||
// 创建认证对象
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
user,
|
||||
null,
|
||||
authorities
|
||||
);
|
||||
// 设置请求详情
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
// 将认证对象存入安全上下文
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
}
|
||||
|
||||
// 继续执行过滤器链
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user