Java SpringSecurityOAuth2:在RESTWebService中获取用户名

Java SpringSecurityOAuth2:在RESTWebService中获取用户名,java,spring-security,jersey,spring-security-oauth2,Java,Spring Security,Jersey,Spring Security Oauth2,我创建了一个RESTful web服务来执行工作流上的操作。web服务由oauth2和我自己的授权服务器保护。 我想向工作流中添加有关谁对其执行操作的信息。我不知道该由谁来获取调用web服务的用户的用户名 对于web服务实现,我使用jersey(1.18.1),对于安全性,我使用spring-security-oauth2(2.0.2.RELEASE) 我正在使用一个数据库令牌存储,它包含一个表OAUTH\u ACCESS\u令牌(令牌\u ID、令牌、身份验证\u ID、用户名、客户端\u I

我创建了一个RESTful web服务来执行工作流上的操作。web服务由oauth2和我自己的授权服务器保护。 我想向工作流中添加有关谁对其执行操作的信息。我不知道该由谁来获取调用web服务的用户的用户名

对于web服务实现,我使用jersey(1.18.1),对于安全性,我使用spring-security-oauth2(2.0.2.RELEASE)

我正在使用一个数据库令牌存储,它包含一个表OAUTH\u ACCESS\u令牌(令牌\u ID、令牌、身份验证\u ID、用户名、客户端\u ID、身份验证、刷新\u令牌),看起来包含正确的信息。它有用户名和令牌,但令牌看起来像一个序列化的java对象,所以我自己无法查询它

网络服务:

@Component
@Path("/workflows")
public class WorkflowRestService {

    @POST
    @Path("/{id}/actions")
    @Produces(MediaType.APPLICATION_JSON)
    @Transactional
    public Response executeActions(@PathParam("id") String id, Map<String, Object> actionArgs) throws JAXBException, HealthDataException {

        //would like to have/get username here.

        Workflow workflow = workflowService.get(id);
        Action action = actionFactory.getAction(actionArgs);
        workflow.execute(action);
        Workflow update = workflowService.update(workflow);
        return Response.ok(update).build();
    }
}
@组件
@路径(“/workflows”)
公共类WorkflowRestService{
@职位
@路径(“/{id}/actions”)
@产生(MediaType.APPLICATION_JSON)
@交易的
公共响应执行(@PathParam(“id”)字符串id,Map actionArgs)抛出JAXBEException,HealthDataException{
//希望在此处输入/获取用户名。
工作流=workflowService.get(id);
Action Action=actionFactory.getAction(actionArgs);
工作流。执行(操作);
工作流更新=workflowService.update(工作流);
返回Response.ok(update.build();
}
}
Web服务安全配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/security/oauth2
        http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd">

    <context:property-placeholder location="classpath:main.properties"/>

    <!-- Protected resources -->
    <http authentication-manager-ref="" pattern="/workflows/**"
          create-session="never"
          entry-point-ref="oauthAuthenticationEntryPoint"
          access-decision-manager-ref="accessDecisionManager"
          xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false"/>
        <intercept-url pattern="/workflows/**"
                       access="ROLE_USER"/>
        <custom-filter ref="resourceServerFilter"
                       before="PRE_AUTH_FILTER"/>
        <access-denied-handler
                ref="oauthAccessDeniedHandler"/>
    </http>

    <bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="dstest"/>
    </bean>

    <bean id="oauthAccessDeniedHandler"
          class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

    <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"/>
            </list>
        </constructor-arg>
    </bean>

    <authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <jdbc-user-service data-source-ref="securityDataSource"/>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
          class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails"/>
    </bean>

    <!-- Token Store  -->
    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="securityDataSource" />
    </bean>

    <bean id="oAuth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg ref="clientDetails"/>
    </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"/>
        <!-- VIV -->
        <property name="accessTokenValiditySeconds" value="10"/>
    </bean>

    <oauth:resource-server id="resourceServerFilter"
                           resource-id="dstest"
                           token-services-ref="tokenServices"/>

    <!-- Client Definition -->
    <oauth:client-details-service id="clientDetails">

        <oauth:client client-id="healthdata-client"
                      authorized-grant-types="password,authorization_code,refresh_token,implicit,redirect"
                      authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
                      redirect-uri="/web"
                      scope="read,write,trust"
                      access-token-validity="300"
                      refresh-token-validity="6000"/>

    </oauth:client-details-service>


    <sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
        <sec:expression-handler ref="oauthExpressionHandler"/>
    </sec:global-method-security>
    <oauth:expression-handler id="oauthExpressionHandler"/>
    <oauth:web-expression-handler id="oauthWebExpressionHandler"/>
</beans>

授权服务器配置:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/security/oauth2
        http://www.springframework.org/schema/security/spring-security-oauth2-2.0.xsd">

    <context:property-placeholder location="classpath:main.properties"/>

    <!-- Definition of the Authentication Service -->
    <http pattern="/oauth/token" create-session="stateless" 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>

    <!-- Protected resources -->
    <http pattern="/users/**"
          create-session="never"
          entry-point-ref="oauthAuthenticationEntryPoint"
          access-decision-manager-ref="accessDecisionManager"
          xmlns="http://www.springframework.org/schema/security">
        <anonymous enabled="false"/>
        <intercept-url pattern="/users/**"
                       access="ROLE_USER"/>
        <custom-filter ref="resourceServerFilter"
                       before="PRE_AUTH_FILTER"/>
        <access-denied-handler
                ref="oauthAccessDeniedHandler"/>
    </http>

    <bean id="oauthAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="dstest"/>
    </bean>

    <bean id="clientAuthenticationEntryPoint"
          class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
        <property name="realmName" value="dstest/client"/>
        <property name="typeName" value="Basic"/>
    </bean>

    <bean id="oauthAccessDeniedHandler"
          class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler"/>

    <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"/>
            </list>
        </constructor-arg>
    </bean>

    <!-- Authentication in config file -->
    <authentication-manager id="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
        <authentication-provider user-service-ref="clientDetailsUserService"/>
    </authentication-manager>

    <authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
        <authentication-provider>
            <jdbc-user-service data-source-ref="securityDataSource"/>
        </authentication-provider>
    </authentication-manager>

    <bean id="clientDetailsUserService"
          class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
        <constructor-arg ref="clientDetails"/>
    </bean>

    <!-- Token Store  -->
    <bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.JdbcTokenStore">
        <constructor-arg ref="securityDataSource" />
    </bean>

    <bean id="oAuth2RequestFactory" class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory">
        <constructor-arg ref="clientDetails"/>
    </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"/>
        <!-- VIV -->
        <property name="accessTokenValiditySeconds" value="10"/>
    </bean>

    <bean id="userApprovalHandler"
          class="org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler">
        <property name="tokenStore" ref="tokenStore"/>
        <property name="requestFactory" ref="oAuth2RequestFactory"/>
    </bean>

    <!-- Token management -->
    <oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices"
                                user-approval-handler-ref="userApprovalHandler" token-endpoint-url="/oauth/token">
        <oauth:authorization-code/>
        <oauth:implicit/>
        <oauth:refresh-token/>
        <oauth:client-credentials/>
        <oauth:password/>
    </oauth:authorization-server>

    <oauth:resource-server id="resourceServerFilter"
                           resource-id="dstest"
                           token-services-ref="tokenServices"/>

    <!-- Client Definition -->
    <oauth:client-details-service id="clientDetails">

        <oauth:client client-id="healthdata-client"
                      authorized-grant-types="password,authorization_code,refresh_token,implicit,redirect"
                      authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT"
                      redirect-uri="/web"
                      scope="read,write,trust"
                      access-token-validity="300"
                      refresh-token-validity="6000"/>

    </oauth:client-details-service>


    <sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
        <sec:expression-handler ref="oauthExpressionHandler"/>
    </sec:global-method-security>
    <oauth:expression-handler id="oauthExpressionHandler"/>
    <oauth:web-expression-handler id="oauthWebExpressionHandler"/>
</beans>

由于您使用Spring Security进行身份验证,我希望您能够访问
SecurityContext
(通过常用的线程本地访问器):

或者通过
HttpServletRequest

Principal principal = request.getUserPrincipal();

(或者,如果您使用的是SpringMVC,只需在
@Controller
中添加
Principal
作为方法参数)。在任何一种情况下,由于您使用的是Spring OAuth筛选器,您还应该发现
主体/身份验证
OAuth2Authentication
的一个实例,用户详细信息以及客户端都在其中。

我确实可以访问SecurityContext,因此可以获取主体。
Principal principal = request.getUserPrincipal();