我们有一个基于 Oauth2 的 REST 服务器(资源 + 授权),由 spring-security + spring web + jersey 用于我们的 REST 资源。大多数情况都很好,但是当使用错误凭据在用户名-密码流中点击 /oauth/token 时,我们不仅得到 400(按照规范是正确的),而且响应中的整个堆栈跟踪为 JSON . 我已经搜索、调试和摸索,但无法完全找到罪魁祸首。这可能是弹簧安全设置吗?还是弹簧网?还是使用 jersey 映射资源的 servlet?
示例响应(缩短):
$ curl -X POST -v --data "grant_type=password&username=admin&password=wrong_password&client_id=my_client" http://localhost:9090/oauth/token
* ...
* Connected to localhost (::1) port 9090 (#0)
* ...
> POST /oauth/token HTTP/1.1
> ...
> Accept: */*
> ...
> Content-Type: application/x-www-form-urlencoded
>
* ...
< HTTP/1.1 400 Bad Request
< ...
< Content-Type: application/json;charset=UTF-8
< ...
<
* ...
curl: (56) Recv failure: Connection reset by peer
{
"cause": null,
"stackTrace": [{
"methodName": "getOAuth2Authentication",
"fileName": "ResourceOwnerPasswordTokenGranter.java",
"lineNumber": 62,
"className": "org.springframework.security.oauth2.provider.passwo
rd.ResourceOwnerPasswordTokenGranter",
"nativeMethod": false
},
.... {"className": "java.lang.Thread",
"nativeMethod": false
}],
"additionalInformation": null,
"oauth2ErrorCode": "invalid_grant",
"httpErrorCode": 400,
"summary": "error=\"invalid_grant\", error_description=\"Bad credentials\"","message":"Badcredentials","localizedMessage":"Badcredentials"}
有任何想法吗?如果您需要更多信息,请告诉我 (web.xml/security.xml/application.xml/servlet.xml)
谢谢!
编辑: 使用带有错误凭据的客户端凭据流,它会给我一个 401 并且没有堆栈跟踪。只是当用户名/密码不匹配时抛出的 BadCredentials / InvalidGrant 异常会导致堆栈跟踪。
编辑 - 我们的配置中的一些片段
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>our.rest.package</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>org.springframework.web.servlet.FrameworkServlet.CONTEXT.appServlet</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
servlet-context.xml 只包含 freemarker 的东西,应该不重要 jersey-servlet 也不重要,因为它只映射 /rest/** 资源并且请求的资源是 /oauth/token。只剩下弹簧安全设置:
authentication-manager-ref="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request
parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter"
after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<http pattern="/rest/**" create-session="stateless"
<!-- ... -->
</http>
<http disable-url-rewriting="true"
xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/oauth/**" access="ROLE_USER" />
<intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<form-login authentication-failure-url="/login.jsp?authentication_error=true"
default-target-url="/index.jsp" login-page="/login.jsp"
login-processing-url="/login.do" />
<logout logout-success-url="/index.jsp" logout-url="/logout.do" />
<anonymous />
</http>
<oauth:resource-server id="resourceServerFilter"
resource-id="engine" token-services-ref="tokenServices" />
<oauth:authorization-server
client-details-service-ref="clientDetails" token-services-ref="tokenServices">
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
<oauth:client-details-service id="clientDetails">
<!-- several clients for client credentials flow... -->
<oauth:client client-id="username-password-client"
authorized-grant-types="password" authorities=""
access-token-validity="3600" />
</oauth:client-details-service>
<authentication-manager id="clientAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<authentication-provider user-service-ref="clientDetailsUserService" />
</authentication-manager>
<authentication-manager alias="theAuthenticationManager"
xmlns="http://www.springframework.org/schema/security">
<!-- authenticationManager is the bean name for our custom implementation
of the UserDetailsService -->
<authentication-provider user-service-ref="authenticationManager">
<password-encoder ref="encoder" />
</authentication-provider>
</authentication-manager>
<bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder">
</bean>
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="ourRealm" />
</bean>
<bean id="clientAuthenticationEntryPoint"
class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="ourRealm/client" />
<property name="typeName" value="Basic" />
</bean>
<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler">
</bean>
<sec:global-method-security
secured-annotations="enabled" pre-post-annotations="enabled">
<sec:expression-handler ref="expressionHandler" />
</sec:global-method-security>
<bean id="expressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<!-- our custom perission evaluator -->
<property name="permissionEvaluator" ref="permissionEvaluatorJpa" />
</bean>
<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="clientCredentialsTokenEndpointFilter"
class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
</bean>
<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased"
xmlns="http://www.springframework.org/schema/beans">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
<bean
class="org.springframework.security.web.access.expression.WebExpressionVoter" />
</list>
</constructor-arg>
</bean>
<bean id="tokenStore"
class="org.springframework.security.oauth2.provider.token.JdbcTokenStore">
<constructor-arg ref="ourDataSource" />
</bean>
<bean id="tokenServices"
class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>
<bean id="requestFactory" class="org.springframework.security.oauth2.provider.DefaultAuthorizationRequestFactory">
<constructor-arg name="clientDetailsService" ref="clientDetails" />
</bean>
<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />
好吧,对我来说似乎没有明显的地方可以在这里配置它。
堆栈跟踪表明,有一个未处理InvalidGrantException
的ResourceOwnerPasswordTokenGranter
. 因此,我尝试在 web.xml 中的 spring-security 过滤器上方的过滤器链中添加过滤器,捕获所有异常并处理它们。但是不起作用,因为 spring-security 过滤器似乎自己处理 InvalidGrantException,这意味着没有异常会冒泡到我周围的过滤器。
( TokenEndpoint
)@RequestMapping(value = "/oauth/token")
调用 ResourceOwnerPasswordTokenGranter 来验证用户名/密码:
@FrameworkEndpoint
@RequestMapping(value = "/oauth/token")
public class TokenEndpoint extends AbstractEndpoint {
@RequestMapping
public ResponseEntity<OAuth2AccessToken> getAccessToken(Principal principal,
@RequestParam("grant_type") String grantType, @RequestParam Map<String, String> parameters) {
// ...
// undhandled:
OAuth2AccessToken token = getTokenGranter().grant(grantType, authorizationRequest);
// ...
return getResponse(token);
}
出现了正确的异常:
public class ResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {
@Override
protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) {
// ...
try {
userAuth = authenticationManager.authenticate(userAuth);
}
catch (BadCredentialsException e) {
// If the username/password are wrong the spec says we should send 400/bad grant
throw new InvalidGrantException(e.getMessage());
}
}
}
但即使在端点回击时也从未处理过。然后过滤器链进行异常处理并添加堆栈跟踪。相反,端点应该在没有堆栈跟踪的情况下返回一个干净的 400,即处理该死的异常!
现在我能看到的唯一方法是覆盖 TokenEndpoint 并捕获异常。
有更好的想法吗?