Spring Security Authentication Provider异常处理

2024-03-08

我有一个身份验证提供程序,它抛出我的自定义异常。 该提供程序在向控制器发出的每个请求上验证令牌。控制器中的异常由控制器建议处理,但提供程序在控制器之前工作,因此控制器建议无法处理提供程序抛出的异常。 我如何处理提供商的异常?

Provider

@Component
@RequiredArgsConstructor
public class BearerTokenAuthenticationProvider implements AuthenticationProvider {

private final Wso2TokenVerificationClient client;

@Override
public Authentication authenticate( Authentication authentication ) {
    BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) authentication;
    Map<String, String> requestBody = new HashMap<>();
    requestBody.put( "token", token.getToken() );
    Wso2TokenValidationResponse tokenValidationResponse = client.introspectToken( requestBody );
    if( !Boolean.parseBoolean( tokenValidationResponse.getActive() ) ) {
        throw new AuthenticationException(
            "Token not valid", HttpStatus.UNAUTHORIZED
        );
    }
    DecodedJWT jwt = JWT.decode(token.getToken());
    UserDetails details = new UserDetails();
    details.setId( Long.parseLong(jwt.getClaim( OidcUserClaims.USER_ID ).asString()) );
    details.setEmail( jwt.getClaim( OidcUserClaims.EMAIL ).asString() );
    token.setDetails( details );
    return token;
}

@Override
public boolean supports( Class<?> aClass ) {
    return BearerTokenAuthenticationToken.class.equals( aClass );
}

安全配置

@Configuration
@RequiredArgsConstructor
public class CommonWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

private final BearerTokenAuthenticationProvider bearerTokenProvider;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().contentSecurityPolicy("script-src 'self'");
    http
            .csrf().disable()
            .authorizeRequests(auth -> auth
                    .antMatchers("/public/**").not().hasAuthority("ROLE_ANONYMOUS")
            )
        .and()
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}

@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
    auth.authenticationProvider( bearerTokenProvider );
}

}


您可以添加一个authenticationEntryPoint处理自定义异常。

@Configuration
@RequiredArgsConstructor
static class CommonWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

    private final BearerTokenAuthenticationProvider bearerTokenProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .headers()
                .contentSecurityPolicy("script-src 'self'");
        http
            .csrf().disable()
            .authorizeRequests(auth -> auth
                 .antMatchers("/public/**").not().hasAuthority("ROLE_ANONYMOUS")
            )
            .oauth2ResourceServer(c -> c.jwt()
                .and()
                .authenticationEntryPoint((request, response, authException) -> {
                    //handle CustomAuthenticationException
                    
                    }
                )
            );
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(bearerTokenProvider);
    }
}

public class CustomAuthenticationException extends AuthenticationException {
    HttpStatus status;
    
    public CustomAuthenticationException(String message, HttpStatus status) {
        super(message);
        this.status = status;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Security Authentication Provider异常处理 的相关文章

随机推荐