自定义Spring Security ResourceServer响应

时间:2016-12-12 23:12:52

标签: spring spring-mvc spring-boot spring-security spring-security-oauth2

我有一个Spring安全配置,看起来像我下面的内容:

@Configuration
@EnableResourceServer
@EnableConfigurationProperties(OAuthSettings.class)
public class SecurityConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private OAuthSettings oAuthSettings;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        final JwtAccessTokenConverter jwtTokenEnhancer = new JwtAccessTokenConverter();
        jwtTokenEnhancer.setVerifierKey(oAuthSettings.getPublicKey());
        jwtTokenEnhancer.afterPropertiesSet();

        JwtTokenStore tokenStore = new JwtTokenStore(jwtTokenEnhancer);
        resources.tokenStore(tokenStore);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/**")
        .access(String.format("#oauth2.hasScope('%s')", oAuthSettings.getRequiredScope()));
    }
}

如果我发送了一个不良令牌,我会收到此回复:

{
  "error": "invalid_token",
  "error_description": "Encoded token is a refresh token"
}

我真的想自定义此回复。

示例,也许我想发回一个具有更多(或不同)属性的对象。例如,响应如:

{
  "error": "invalid_token",
  "errorDescription": "Encoded token is a refresh token",
  "aSuggestion": "some suggestion",
  "anotherProperty": "check this out!"
}

我无法在spring security中找到一个钩子,允许我覆盖这个默认的异常处理行为。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以覆盖commence

中的EntryPoint方法
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException;