我的应用程序使用带有JWTToken的Spring Security Oauth2。
我正在尝试修改响应的正文,当它返回错误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());