【发布时间】:2015-07-27 13:27:48
【问题描述】:
虽然这似乎是一件容易的事,但事实恰恰相反。我正在尝试自定义 OAuth2 客户端身份验证请求的错误处理。这样做的目的是从响应消息中删除异常堆栈跟踪/消息。
上下文
- vanilla Oauth2 Spring Security 实现
- Java Spring 配置
完成任务所采取的步骤
- 创建
OAuth2ExceptionRenderer的自定义实现 -
创建
OAuth2AuthenticationEntryPoint的@Bean实例@Bean public OAuth2AuthenticationEntryPoint clientAuthEntryPoint() { OAuth2AuthenticationEntryPoint clientEntryPoint = new OAuth2AuthenticationEntryPoint(); clientEntryPoint.setTypeName("Basic"); clientEntryPoint.setRealmName("my-realm/client"); clientEntryPoint.setExceptionRenderer(new CustomOAuth2ExceptionRenderer()); return clientEntryPoint; } -
创建拒绝访问处理程序
@Bean public OAuth2AccessDeniedHandler accessDeniedHandler() { OAuth2AccessDeniedHandler adh = new OAuth2AccessDeniedHandler(); adh.setExceptionRenderer(new CustomOAuth2ExceptionRenderer()); return adh; } -
使用
AuthorizationServerConfiguration中的这些专门实现增强AuthorizationServerSecurityConfigurer等@Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.authenticationEntryPoint(clientAuthEntryPoint()); oauthServer.accessDeniedHandler(accessDeniedHandler()); oauthServer.realm("my-realm"); } }
OAuth2 请求
我们使用 curl 来启动 OAuth2 请求。这是我们用来测试客户端身份验证的命令:
curl --insecure -H "Accept: application/json" -X POST -iu adfadsf:asdvadfgadf "https://localhost:8430/oauth/token?grant_type=password$username=john&pasword=johny"
观察到的行为
由于客户端身份验证是基本身份验证,Spring Security 将为该步骤分配一个BasicAuthenticationFilter。如果恰好在与此步骤相关的后端出现错误(例如 SQL 异常),Spring Security 将不会选择 OAuth2AuthenticationEntryPoint 并将回退到默认入口点 BasicAuthenticationEntryPoint。
日志
o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
o.s.s.w.a.www.BasicAuthenticationFilter : Authentication request for failed: org.springframework.security.authentication.InternalAuthenticationServiceException: show me the money
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@649f92da
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed```
【问题讨论】:
-
我也有同样的问题,你解决了吗?
-
我们的解决方案是确保该方法没有异常泄漏(在我们的例子中为
loadClientByClientId)。这不是优雅的,但它有效。我还在他们的问题跟踪器上提出了一个问题,它仍然是开放的。也可以随意表达你的观点。 github.com/spring-projects/spring-security-oauth/issues/483
标签: java oauth spring-security spring-security-oauth2