由于我的验证器失败,我无法在尝试解码jwt时发生错误时捕获身份验证失败事件。我使用的是springsecurity 5.2.1。请注意,当我根本不在“authorization”头中传递令牌时,我会捕获授权失败事件。我想一些额外的配置必须与spring配置一起完成。
引发异常:
org.springframework.security.oauth2.core.OAuth2AuthenticationException: An
error occurred while attempting to decode the Jwt: This aud claim does not
contain configured audience
审计的实施如下所述:https://www.baeldung.com/spring-boot-authentication-audit
当前spring安全配置:
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final OAuth2Error INVALID_AUDIENCE =
new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST,
"This aud claim does not contain configured audience",
"https://tools.ietf.org/html/rfc6750#section-3.1");
@Value("${spring.security.oauth2.claim-to-validate.audience}")
private String audience;
@Value("${spring.security.oauth2.claim-to-validate.scope}")
private String scope;
@Value("${spring.security.oauth2.resourceserver.jwt.public-key-location:#{null}}")
private RSAPublicKey publicKeyLocation;
@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri:#{null}}")
private String jwkSetUri;
@Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri:#{null}}")
private String issuerUri;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers( "/v1/resource/**")
.hasAuthority("SCOPE_" + scope)
.and()
.oauth2ResourceServer()
.jwt();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
@Bean
public JwtDecoder jwtDecoder() {
final OAuth2TokenValidator<Jwt> withAudience = audienceValidator(audience);
final JwtDecoder jwtDecoder;
if (publicKeyLocation != null) {
jwtDecoder = NimbusJwtDecoder.withPublicKey(publicKeyLocation).build();
} else if (StringUtils.hasLength(jwkSetUri)) {
jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
} else if (StringUtils.hasLength(issuerUri)) {
jwtDecoder = JwtDecoders.fromOidcIssuerLocation(issuerUri);
} else {
throw new IllegalStateException(
"Invalid OAuth2 configuration: provide value for any of " +
"'publicKeyLocation', 'jwkSetUri' or 'issuerUri'");
}
((NimbusJwtDecoder) jwtDecoder).setJwtValidator(withAudience);
return jwtDecoder;
}
OAuth2TokenValidator<Jwt> audienceValidator(String audience) {
return jwt -> {
Assert.notNull(jwt, "token cannot be null");
final List<String> audiences = jwt.getAudience();
return audiences.contains(audience) ?
OAuth2TokenValidatorResult.success() :
OAuth2TokenValidatorResult.failure(INVALID_AUDIENCE);
};
}
}
1条答案
按热度按时间bvpmtnay1#
将spring security更新至5.3.0或更高版本,并在spring security配置中声明自定义authenticationeventpublisher bean,如下所示:
请注意,在5.3.0中,您可以直接添加Map,而无需属性结构。
如果您需要继续使用5.2.x,请使用此处指出的解决方法:https://github.com/spring-projects/spring-security/issues/7793