【问题标题】:How to set custom 403 response in OAuth2 resource server?如何在 OAuth2 资源服务器中设置自定义 403 响应?
【发布时间】:2021-06-03 09:24:51
【问题描述】:

春季启动 2.4.3 如果用户没有操作权限,它会给出 403 响应,但没有任何响应正文。但是设置了标题WWW-Authenticate

WWW-Authenticate: Bearer error="insufficient_scope", error_description="The request requires higher privileges than provided by the access token."

我仍然希望有一些带有消息的响应正文。我怎样才能实现它?

    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .formLogin(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeRequests(authorize -> authorize
                        .mvcMatchers(HttpMethod.GET, "/app/**", "/admin/**").authenticated()
                        .mvcMatchers(HttpMethod.PUT, "/app/**", "/admin/**").authenticated()
                        .mvcMatchers(HttpMethod.POST, "/app/**", "/admin/**").authenticated()
                )
                .oauth2ResourceServer()
                .jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
    }

【问题讨论】:

    标签: spring-security spring-oauth2


    【解决方案1】:

    我遇到了同样的问题,找到了以下解决方案:

    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException e) throws IOException, ServletException {
            e.getCause().printStackTrace();
    
            response.setStatus(...);
            response.setContentType(...);
            response.getWriter().write("your custom error response");
        }
    }
    

    然后在您的安全配置中:

    http. 
      //...
        .oauth2ResourceServer()
        .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
    
    

    【讨论】:

    • 返回正常状态? :)
    • 已更新。在我的用例中,我返回了一个 GraphQL 错误,该错误旨在始终返回 200 Ok。
    猜你喜欢
    • 2021-02-13
    • 2020-08-02
    • 2016-07-14
    • 2018-05-17
    • 2017-12-10
    • 2021-12-18
    • 2019-02-27
    • 1970-01-01
    • 2016-01-18
    相关资源
    最近更新 更多