Spring security oauth2服务器 - 拦截未经授权的拒绝访问

时间:2017-11-14 08:54:43

标签: spring oauth-2.0 cloud spring-cloud spring-security-oauth2

我想拦截来自spring cloud oauth2授权服务器的访问拒绝响应:

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

我希望拦截异常并执行一些自定义重定向或显示自定义页面。

有关如何做到这一点的任何提示?

提前致谢。

1 个答案:

答案 0 :(得分:0)

最后通过扩展 ResourceServerConfigurerAdapter 并使用以下附加代码覆盖 configure(http)方法解决了这个问题:

...
http.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint());
...

@Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() {

        return (request, response, authException) -> {
            LOGGER.info("\n!!!!!!!! unauthorized: {} !!!!!!!!!!!!", authException.getMessage());
            String uri = request.getContextPath() + "/login";
            if(loadBalancerClient!=null && loadBalancerClient.choose("API-GATEWAY") != null) {
                uri = loadBalancerClient.choose("API-GATEWAY").getUri().toString();
            }
            response.sendRedirect(uri);
        };
    }