2015-04-13 9 views
0

Я использую spring-security-oauth2 (1.0.5.RELEASE), и он отлично работает.Spring Security Oauth2 Настроить количество попыток

Я хотел бы настроить неудачные attmepts, чтобы я регистрировал количество попыток, и если он пересекает заданный номер, тогда я отключу пользователя на 30 минут.

Как я могу достичь этого? На каких классах я должен смотреть?

Моя конфигурация безопасности выглядит следующим образом:

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

     http://www.springframework.org/schema/beans/spring-beans-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/security/oauth2 
     http://www.springframework.org/schema/security/spring-security-oauth2-1.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-3.1.xsd"> 


<!-- 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="/api/**" 
     create-session="never" 
     use-expressions="true" 
     entry-point-ref="oauthAuthenticationEntryPoint" 
     access-decision-manager-ref="accessDecisionManager" 
     xmlns="http://www.springframework.org/schema/security"> 
    <anonymous enabled="false"/> 
    <intercept-url pattern="/api/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/> 
    <custom-filter ref="resourceServerFilter" before="PRE_AUTH_FILTER"/> 
    <access-denied-handler ref="oauthAccessDeniedHandler"/> 
</http> 

<!-- signup dont need access token --> 

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



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

<!-- 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> 
     <user-service id="userDetailsService"> 
      <user name="admin" password="password" authorities="ROLE_USER"/> 
     </user-service> 
    </authentication-provider> 
</authentication-manager> --> 

<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security"> 
     <authentication-provider> 
      <password-encoder ref="encoder" /> 
      <jdbc-user-service data-source-ref="dataSource" 
       users-by-username-query="SELECT USERNAME, PASSWORD, ENABLED FROM USERS WHERE USERNAME=?" 
       authorities-by-username-query="SELECT USERNAME, ROLE FROM USER_ROLES WHERE USERNAME=?" /> 
     </authentication-provider> 
</authentication-manager> 

<bean id="encoder" 
     class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"> 
     <constructor-arg name="strength" value="10" /> 
</bean> 


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

<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"/> 
    <!-- <property name="accessTokenValiditySeconds" value="10"/> --> 
    <property name="tokenEnhancer" ref="tokenEnhancer"/> 
</bean> 

<bean id="tokenEnhancer" class="com.mi.common.MyTokenEnhancer"/> 

<bean id="userApprovalHandler" 
     class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler"> 
    <property name="tokenServices" ref="tokenServices"/> 
</bean> 

<!-- Token management --> 
<oauth:authorization-server client-details-service-ref="clientDetails" token-services-ref="tokenServices" 
          user-approval-handler-ref="userApprovalHandler"> 
    <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="my-trusted-client" 
        authorized-grant-types="password,authorization_code,refresh_token,implicit,redirect" 
        authorities="ROLE_ADMIN, ROLE_USER, ROLE_CLIENT, ROLE_TRUSTED_CLIENT" 
        redirect-uri="/web" 
        scope="read,write,trust" 
        access-token-validity="3600" 
        refresh-token-validity="36000"/> 
</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> 

ответ

1

Обычно такая функциональность будет добавлена ​​к AuthenticationManager. Пример (от Cloud Foundry UAA)

@Override 
public Authentication authenticate(Authentication req) throws AuthenticationException { 

    ... 

    if (!accountLoginPolicy.isAllowed(user, req)) { 
    AuthenticationPolicyRejectionException e = new AuthenticationPolicyRejectionException("Login policy rejected authentication"); 
    publish(new AuthenticationFailureLockedEvent(req, e)); 
    throw e; 
    } 
    ... 
} 
+0

Спасибо. Но вы могли видеть мой файл конфигурации, у меня есть два аутентификатора, который я должен изменить? –

+1

Тот, который аутентифицирует пользователей, я думаю. Или тот, который вы хотите отклонить неудачные попытки в любом случае. Может быть, оба они? –

+0

Спасибо. Я пытался и обнаружил, что реализация AuthenticationProvider также обеспечивает решение этой проблемы. –

Смежные вопросы