URL-адрес токена не работает с весенней безопасностью oauth2

Я пытаюсь получить конфигурацию oauth2 для защиты моего веб-приложения и разрешить доступ к приложению только доверенным клиентам с предоставленными учетными данными пользователя.

Это то, что у меня есть до сих пор

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:oauth="http://www.springframework.org/schema/security/oauth2" xmlns:sec="http://www.springframework.org/schema/security"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">


    <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 request-matcher="regex" create-session="stateless" entry-point-ref="oauthAuthenticationEntryPoint"
      xmlns="http://www.springframework.org/schema/security">
        <!-- <anonymous enabled="false" /> -->
        <intercept-url pattern="/api/register/.*" access="ROLE_CLIENT" />
        <intercept-url pattern="/api/.*" access="ROLE_USER" />
        <access-denied-handler ref="oauthAccessDeniedHandler" />
        <expression-handler ref="oauthWebExpressionHandler" />
    </http>

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

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

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

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

   <bean id="myUserDetailsService" class="com.example.core.web.rest.auth.QeepUserDetailsService"/>

   <bean id="tokenStore" class="com.example.core.web.rest.auth.QeepTokenStore" />

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

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

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

   <oauth:client-details-service id="clientDetails">
       <oauth:client client-id="my-trusted-client-with-secret" authorized-grant-types="password,authorization_code,refresh_token,implicit"
                  secret="somesecret" authorities="ROLE_CLIENT, ROLE_TRUSTED_CLIENT" />
   </oauth:client-details-service>

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

   <sec:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
       <!--you could also wire in the expression handler up at the layer of the http filters. See https://jira.springsource.org/browse/SEC-1452 -->
   <sec:expression-handler ref="oauthExpressionHandler" />
   </sec:global-method-security>

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

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

Если я получаю доступ к /oauth/token с помощью curl, я получаю запрос на авторизацию клиента, который я получаю, используя настроенные учетные данные клиента. Но после этого /oauth/token возвращает только 404 - Not found. Я пробовал разные вещи в последние часы без каких-либо успехов.

Я извлек конфигурацию из образца sparklr/tonr oauth2 1.0.5, который я использовал, потому что мы все еще используем spring 3.2.

Тот же тест отлично работает в sparklr-Sample-webapp.

ИЗМЕНИТЬ

Фактический URL-адрес curl выглядит следующим образом:

curl -v -H "Authorization: Basic bXktdHJ1c3RlZC1jbGllbnQtd2l0aC1zZWNyZXQ6c29tZXNlY3JldA==" "http://localhost:8084/core/oauth/token"

Без заголовка авторизации я получаю 401 запрос на аутентификацию клиента в соответствии с настройками («мой доверенный клиент с секретом» и «somesecret»), но с добавленным заголовком авторизации я просто получаю 404 - Не найдено. Если я проверю то же самое с помощью sparklr-Sample, я получу сообщение об ошибке с запросом типа гранта после добавления заголовка Basic-Auth-Header, как указано выше, чего я и ожидал.

Я надеюсь, что это делает немного яснее.

Любые идеи, что не так с моей конфигурацией?


person HefferWolf    schedule 12.12.2014    source источник
comment
Я не понимаю. Как можно что-то скрутить, и это работает, а потом получить 404? Я думаю, нам нужно более подробное описание того, что вы сделали и почему это не удалось. Может быть, настоящая команда curl (если проблема была в этом)?   -  person Dave Syer    schedule 14.12.2014
comment
Как отображается ваш DispatcherServlet (web.xml)?   -  person Dave Syer    schedule 15.12.2014


Ответы (1)


DispatcherServlet был сопоставлен с неправильным URL-адресом, я сломал его, пытаясь исправить проблему, которая возникла у меня первой. Dispatcher-Servlet сопоставляется с core/api, а служба токенов сначала сопоставляется с core/api/oauth/token, которую я позже изменил на core/oauth/token, но я забыл изменить DispatcherServlet. Спасибо, Дэйв за подсказку!

person HefferWolf    schedule 15.12.2014