标签: spring-resource-server

为什么 Spring Security 6 没有调用我的 OAuth2TokenValidator 的 validate 方法?

我有以下代码...


public class AudienceValidator implements OAuth2TokenValidator<Jwt> {

    private final String audience;

    public AudienceValidator(String audience) {
        this.audience = audience;
    }

    @Override
    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        if (jwt.getAudience().contains(audience)) {
            return OAuth2TokenValidatorResult.success();
        } else {
            return OAuth2TokenValidatorResult.failure(error);
        }
    }
}

@EnableWebSecurity
public class SecurityConfig{

    @Value("${auth0.audience}")
    private String audience;

    @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
    private String issuer;
    @Bean
    public JwtDecoder jwtDecoder() {
        NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
                JwtDecoders.fromOidcIssuerLocation(issuer);

        OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator(audience);
        OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuer);
        OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

        jwtDecoder.setJwtValidator(withAudience);

        return jwtDecoder;
    }
    @Bean …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot spring-resource-server

5
推荐指数
0
解决办法
386
查看次数

为什么 Java 中的 JWT 令牌无效或过期时,我的 CustomAuthenticationEntryPoint 开始方法没有被调用?

当 jwt 令牌无效或过期时,为什么不调用此开始方法?当令牌为空时会调用它。奇怪的是,在调试时我发现当令牌无效或过期时,会调用 BearerTokenAuthenticationEntryPoint.commence() 方法。这个类是标准java库的一部分,并且是最终的,所以不能扩展。但它实现了与我实现相同的接口 - AuthenticationEntryPoint,但我的开始方法仍然没有被调用。仅当令牌为空时才会调用它。

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
  public CustomAuthenticationEntryPoint() {
  }

  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException authenticationException) throws IOException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    HttpStatus status = HttpStatus.UNAUTHORIZED;

    final Map<String, Object> body = new HashMap<>();
    body.put("status", status.name());
    body.put("statusCode", status.value());
    body.put("message", "You need to login first in order to perform this action");

    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(response.getOutputStream(), body);
  }
}
Run Code Online (Sandbox Code Playgroud)

我这样使用它:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .authorizeHttpRequests((authorize) -> …
Run Code Online (Sandbox Code Playgroud)

java spring-security jwt spring-resource-server

3
推荐指数
1
解决办法
972
查看次数