当前位置: 首页 > 知识库问答 >
问题:

spring-security oauth2 REST服务器的错误证书(400)错误响应中不需要的堆栈跟踪

沈冠宇
2023-03-14

我们有一个REST服务器(资源授权),它基于spring-security spring web jersey的Oauth2,用于我们的REST资源。大部分工作都很顺利,但是当使用错误的凭证在用户名-密码流中点击/oauth/token时,我们得到的不仅仅是400(按照规范应该是正确的),而是作为JSON的整个stacktrace。我四处搜寻、调试、摸索,但还是找不到罪魁祸首。这可能是Spring安全设置吗?还是春网?还是使用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并且没有堆栈跟踪。只是当用户名/密码不匹配时抛出的Bad凭据/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。只剩下spring-security设置:

    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" />

好吧,对我来说,似乎没有明显的地方可以在这里配置它。

stacktrace表明,ResourceOwnerPasswordTokenGranter引发了未处理的InvalidGrantException。因此,我尝试将过滤器添加到web中Spring Security过滤器上方的过滤器链中。xml,捕获所有异常并处理它们。但是,这不会起作用,因为Spring Security过滤器似乎可以自己处理InvalidGrantException,这意味着没有异常气泡出现在我周围的过滤器中。

TokenEndpoint@Request estMap(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());
        }
    }

}

但是从来没有处理过,甚至当它返回到endpoint时也没有。然后filterchain进行异常处理并添加stacktrace。相反,endpoint应该返回一个没有stacktrace的干净的400,即处理该死的异常!

现在,我能看到的唯一html" target="_blank">方法是覆盖TokenEndpoint并捕获异常。

有更好的主意吗?

共有1个答案

刘子实
2023-03-14

您可以为该特定异常编写异常映射程序,并对请求执行任何操作。每当从终结点方法引发定义的异常时,ExceptionMapper 都会处理响应。

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class MyExceptionMapper implements ExceptionMapper<InvalidGrantException>
{
    @Override
    public Response toResponse(InvalidGrantException exception)
    {
        return Response.status(Response.Status.BAD_REQUEST).build(); 
    }
}

编辑18.11.2013:

我猜您可以随时重写EntryPoint类(如StackOverflow问题中所示)。

自定义的OAuth2Exception渲染器(请参阅SO:自定义SpringSecurity OAuth2错误输出也可以工作。

 类似资料:
  • 我希望获得格式的JPA验证和服务器内部错误,而不是堆栈跟踪, 使用 当post没有属性时,我希望验证错误不为NULL。 当前回报: > 所需返回: POM web.xml

  • 我已经尝试运行下面的代码,从1周到现在。我已经重写了大约4-5次相同的代码,以防我错过了什么。尝试寻找解决方案,以及,但我无法检测到底是什么错误? 错误:找不到模块'webpack-cli/bin/config-yargs'需要堆栈: C:\用户\NFC\Desktop\reactapp\node_modules\webpack-dev-server\bin\webpack-dev-server.

  • 线程名称:Converse_Chat_No 1-1示例开始:2018-06-06 14:29:19 IST加载时间:1313连接时间:1104延迟:1313大小以字节为单位:1639发送字节:1982头大小以字节为单位:554正文大小以字节为单位:1085示例计数:1错误计数:1数据类型(“text”“bin”“”):文本响应代码:400响应消息:错误请求 响应标题:HTTP/1.1 400错误请

  • 在另一种情况下,经过去模糊处理后,我得到的不是正常的堆栈跟踪,而是如下所示: 是什么原因,有可能莫名其妙地从这得到一个正常的堆栈跟踪?

  • 我使用Apache Tomcat 8.5.8部署了一个静态Web应用程序 当我调用普通URL时,它工作正常。http://localhost/example/index.html 但是当我调用下面的URL时,它给我400个错误请求错误。http://localhost/example/index.html?host_info=Outlook|网页 我知道这是因为URL具有特殊字符(|)。但我无法配

  • 问题内容: 我试图从桌面应用程序连接到URL,但出现问题标题中指示的错误,但是当我尝试从servlet连接到同一URL时,一切正常。当我从浏览器加载URL时,一切正常。我在servlet中使用相同的代码。该代码在库中,当它不起作用时,我将代码拉到当前项目中的类中,但它不起作用。 网址https://graph.facebook.com/me。 代码片段。 我在这里有些困惑,是否存在某种不是普通桌面