2016-05-06 2 views
4

i,Весной OAuth2, почему мой ресурс все еще незащищен, хотя я отмечен его на моем сервере ресурсов?

Я использую Spring 3.2.11.RELEASE с пружиной-security-oauth2 v 2.0.7.RELEASE. Я хочу настроить сервер ресурсов таким образом, что если клиент правильно передает свой идентификатор и секрет с типом гранта client_credentials, он может использовать полученный токен для данных POST для URL-адреса. Тем не менее, я не могу понять, как защитить этот URL (я могу отправлять POST на этот URL-адрес, даже если токен неверен). Ниже, как я пытаюсь настроить мой сервер ресурс

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

<bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> 
    <constructor-arg value="/writeUrl" /> 
</bean> 

<oauth:client-details-service id="clientDetails"> 
    <oauth:client client-id="my-client-with-secret" 
     authorized-grant-types="client_credentials" authorities="ROLE_CLIENT" 
     scope="read,write" secret="secret" /> 
</oauth:client-details-service> 

Но, как я уже сказал, размещая данные в «/ writeUrl» или нет у меня действительный маркер успешно, и я хочу, чтобы заблокировать этот URL , Как мне это сделать? Моя полная конфигурация контекста приложения OAuth2 ниже ...

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

<!-- The OAuth2 protected resources are separated out into their own block 
    so we can deal with authorization and error handling separately. This isn't 
    mandatory, but it makes it easier to control the behaviour. --> 
<http pattern="/oauth/(users|clients)/.*" request-matcher="regex" 
    create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint" 
    use-expressions="true" xmlns="http://www.springframework.org/schema/security"> 
    <anonymous enabled="false" /> 
    <intercept-url pattern="/oauth/users/([^/].*?)/tokens/.*" 
     access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')" 
     method="DELETE" /> 
    <intercept-url pattern="/oauth/users/.*" 
     access="#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')" 
     method="GET" /> 
    <intercept-url pattern="/oauth/clients/.*" 
     access="#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')" 
     method="GET" /> 
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER" /> 
    <access-denied-handler ref="oauthAccessDeniedHandler" /> 
    <expression-handler ref="oauthWebExpressionHandler" /> 
</http> 

<!-- The OAuth2 protected resources are separated out into their own block 
    so we can deal with authorization and error handling separately. This isn't 
    mandatory, but it makes it easier to control the behaviour. --> 
<http pattern="/me/**" 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="/me" access="ROLE_USER,SCOPE_READ" /> 
    <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="sparklr2" /> 
</bean> 

<bean id="clientAuthenticationEntryPoint" 
    class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint"> 
    <property name="realmName" value="sparklr2/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-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> 
     <user-service id="userDetailsService"> 
      <user name="marissa" password="koala" authorities="ROLE_USER" /> 
      <user name="paul" password="emu" authorities="ROLE_USER" /> 
     </user-service> 
    </authentication-provider> 
</authentication-manager> 

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

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

<bean id="tokenServices" 
    class="org.springframework.security.oauth2.provider.token.DefaultTokenServices"> 
    <property name="tokenStore" ref="tokenStore" /> 
    <property name="tokenEnhancer" ref="tokenEnhancer" /> 
    <property name="supportRefreshToken" value="true" /> 
    <property name="clientDetailsService" ref="clientDetails" /> 
</bean> 

<bean id="tokenEnhancer" 
    class="org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter" /> 

<bean id="requestFactory" 
    class="org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory"> 
    <constructor-arg name="clientDetailsService" ref="clientDetails" /> 
</bean> 

<bean id="approvalStore" 
    class="org.springframework.security.oauth2.provider.approval.TokenApprovalStore"> 
    <property name="tokenStore" ref="tokenStore" /> 
</bean> 

<oauth:authorization-server 
    client-details-service-ref="clientDetails" token-services-ref="tokenServices"> 
    <oauth:authorization-code /> 
    <oauth:implicit /> 
    <oauth:refresh-token /> 
    <oauth:client-credentials /> 
    <oauth:password /> 
</oauth:authorization-server> 

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

<bean id="entry" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> 
    <constructor-arg value="/writeUrl" /> 
</bean> 

<oauth:client-details-service id="clientDetails"> 
    <oauth:client client-id="my-client-with-secret" 
     authorized-grant-types="client_credentials" authorities="ROLE_CLIENT" 
     scope="read,write" secret="secret" /> 
</oauth:client-details-service> 

<mvc:default-servlet-handler /> 

<oauth:expression-handler id="oauthExpressionHandler" /> 

<oauth:web-expression-handler id="oauthWebExpressionHandler" /> 
+0

Не могли бы вы загрузить полный исходный код в github или где-нибудь еще? – CrawlingKid

+0

К сожалению, нет. Однако вся конфигурация OAuth находится в XML выше - нет других частей моего projjct, которые относятся к OAuth. Мой вопрос в основном заключается в том, как вы берете URL-адрес и защищаете taht как часть сервера ресурсов, используя конфигурацию XML. – Dave

ответ

2

Там должно быть intercept-url в конфигурации конечных ресурсов с доступом только для уполномоченных пользователей (я предполагаю, что ваш URL может соответствовать следующему шаблону)

<security:http pattern="/writeUrl/**" 
        create-session="never" 
        entry-point-ref="oauthAuthenticationEntryPoint" 
        access-decision-manager-ref="accessDecisionManager"> 
    <security:anonymous enabled="false" /> 
    <security:intercept-url pattern="/**" 
          access="IS_AUTHENTICATED_FULLY"/> 

    <security:custom-filter ref="resourceServerFilter" 
          before="PRE_AUTH_FILTER" /> 
    <security:access-denied-handler ref="oauthAccessDeniedHandler" /> 
    </security:http> 
+0

Когда у вас есть «IS_AUTHENTICATED_FULLY», это taht в контексте безопасности SPring или Spring OAuth2 (может быть, они такие же)? Я использую тип типа «client_credentials», но когда мой клиент отправляет свой идентификатор и секрет, я не уверен, что это делает их «IS_AUTHENTICATED_FULLY». – Dave

+0

Ну, в этом случае я имел в виду это в контексте OAuth2. [Также] (http://stackoverflow.com/a/30953295) isAuthenticated() должно быть в порядке и сделать их аутентифицированными. –