Use different AuthenticationProvider depending on username and remote IP address

前端 未结 1 1286
旧巷少年郎
旧巷少年郎 2021-01-21 00:43

In a Spring Security 3.2 based application I need to authenticate users against two different providers, based on a certain pattern in their username AND their remote ip address

相关标签:
1条回答
  • 2021-01-21 01:02

    You could create a wrapper which does the check for the pattern/ip-address if it matches calls the delegate else return null.

    public class FilteringAuthenticationProvider implements AuthenticationProvider {
        private final AuthenticationProvider delegate;
    
        public FilteringAuthenticationProvider(AuthenticationProvider delegate) { this.delegate=delegate;}
    
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            Object details = authentication.getDetails();
            String username = authentication.getPrincipal().toString();
            String remoteAddress = null;
            if (details instanceof WebAuthenticationDetails) {
                remoteAddress = ((WebAuthenticationDetails) details).getRemoteAddress(); 
            }
    
            if (matches(remoteAddress, username)) {
                return delegate.authenticate(authentication);
            }
            return null
        }
    
        private boolean matches(String remoteAddress, String Username) {
            // your checking logic here
        }       
    }
    

    Something like this. Then configure it in your security configuration and let it wrap the ActiveDirectoryLdapAuthenticationProvider.

    <sec:authentication-manager>
        <sec:authentication-provider ref="filteringLdapProvider" />
        <sec:authentication-provider>
            <user-service ref="customUserDetailsService" />
        </sec:authentication-provider>
    </sec:authentication-manager>
    
    <bean id="filteringLdapProvider" class="FilteringAuthenticationProvider">
        <constructor-arg ref="ldapProvider" />
    </bean>
    
    <bean id="ldapProvider" class="ActiveDirectoryLdapAuthenticationProvider">
    ...
    </bean>
    

    Something like this.

    0 讨论(0)
提交回复
热议问题