我的应用程序使用 Spring Security Oauth2 和 JWTToken。
我试图在返回错误 401 时修改响应正文,这种情况在未经身份验证的用户尝试访问数据时发生:
{
"error": "invalid_token",
"error_description": "Cannot convert access token to JSON"
}
为此,我实现了自己的 WebResponseExceptionTranslator
并将其设置在我的身份验证入口点中,如下所示:
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint());
}
@Bean
public AuthenticationEntryPoint authenticationEntryPoint () {
OAuth2AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
authenticationEntryPoint.setExceptionTranslator(new CustomWebResponseExceptionTranslator());
return authenticationEntryPoint;
}
}
但是,它继续使用默认的WebResponseExceptionTranslator
。所以,我的问题是,我怎样才能强制他使用我的?
最佳答案
如果您使用了 WebResponseExceptionTranslator
,则应将其放入 AuthorizationServerEndpointsConfigurer
中,如下所示:
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
endpoints.tokenStore(tokenStore)
.accessTokenConverter(accessTokenConverter)
.tokenEnhancer(enhancerChain)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.exceptionTranslator(webResponseExceptionTranslator());
关于java - Spring Oauth2修改无效 token 异常的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45488109/