【问题标题】:Customize Spring Security ResourceServer response自定义 Spring Security ResourceServer 响应
【发布时间】:2017-04-27 22:22:12
【问题描述】:

我有一个 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 中找到允许我覆盖此默认异常处理行为的挂钩。任何帮助表示赞赏。

【问题讨论】:

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


    【解决方案1】:

    你可以覆盖EntryPoint中的commence方法

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException;
    

    【讨论】:

    • 好的,现在就这样做。但是,HttpServletResponse 似乎真的很有限。我可以在该响应上设置一个真正的 java 对象吗?说.. response.setBody(new MyComplexObject());然后让spring把这个东西序列化成xml或者json?
    • 恐怕没有,因为它还在过滤器中。
    • 感谢@chaoluo 提供的信息。但是,当然,这是一种修改 spring security bad token 输出的方法。如果这是完全不可配置的,那肯定是 spring 安全性的一个严重缺陷。
    • @Jeff 我已经考虑了一段时间,现在我几乎可以肯定它会使spring-securityspring-mvc 紧密耦合,所以我确定这就是它的原因不喜欢那样。但是也许您可以编写自己的 EntryPoint 实现,您可以在其中 @Autowire mvc 的消息转换器并按照它们在 spring-mvc 中的使用方式使用它。我一直在寻找这个,但仍然没有找到适合我所有需求的方法。
    猜你喜欢
    • 2015-07-03
    • 2018-06-26
    • 1970-01-01
    • 2016-09-04
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2018-01-13
    相关资源
    最近更新 更多