提问人:Bartolinio Kooperinio 提问时间:9/29/2023 更新时间:10/1/2023 访问量:32
Java 安全状态 403
Java security status 403
问:
我已根据 JWT 令牌和角色配置了简单的安全性。我已经在邮递员中进行了测试,每个请求的状态都为 403 禁止。我不知道是什么阻止了我的请求,因为即使我评论了每个过滤器并只留下 permitAllAll,它仍然每次都说 403。
安全配置代码:
@Configuration
@RequiredArgsConstructor
public class SpringSecurityConfig {
@Value("${jwt.secret}")
private String jwtSecret;
@Value("${jwt.issuer}")
private String jwtIssuer;
@Bean
public JWTVerifier jwtVerifier() {
Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
return JWT.require(algorithm)
.withIssuer(jwtIssuer)
.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/api/users/**").permitAll()
//.requestMatchers("/api/librarian/**").hasAnyRole("librarian", "programmer")
//.requestMatchers("/api/reader/**").hasAnyRole("reader", "programmer")
//.anyRequest().authenticated()
)
.cors(Customizer.withDefaults())
.csrf(Customizer.withDefaults());
//http.addFilterBefore(new JWTFilter(jwtVerifier()), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
JWT 令牌过滤器代码:
@AllArgsConstructor
public class JWTFilter extends UsernamePasswordAuthenticationFilter {
private final JWTVerifier jwtVerifier;
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String token = extractToken(request);
if (token != null) {
try {
DecodedJWT jwt = jwtVerifier.verify(token);
Authentication authentication = createAuthenticationFromToken(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
} catch (JWTVerificationException e) {
}
}
chain.doFilter(request, response);
}
private Authentication createAuthenticationFromToken(DecodedJWT jwt) {
String username = jwt.getClaim("username").asString();
List<SimpleGrantedAuthority> authorities = jwt.getClaim("roles")
.asList(String.class)
.stream()
.map(SimpleGrantedAuthority::new)
.toList();
return new UsernamePasswordAuthenticationToken(username, null, authorities);
}
// Extract the JWT token from the request
private String extractToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
return null;
}
}
答:
1赞
Manuel
10/1/2023
#1
可能是因为在您的方法中,您提取了 but return .extractToken
token
null
对于将来的问题,请提供一些 JUnit 测试,或您通过 Postman 发送的请求。此外,spring-security DEBUG日志也会有所帮助。
评论