Search code examples
springspring-securityspring-java-configcustom-authentication

Letting Spring security pick implementation of class implementing custom authentication provider


We have a webapp which implements custom authentication via AuthenticationProvider. This works fine now. But we want to provide an option for customer to implement their own authentication class implementing AuthenticationProvider. So they will delete our jar from app and add their jar to classpath.

It appears in security xml we need to specify only class implementing AuthenticationProvider but can't tell spring to pick any class implementing interface AuthenticationProvider

Current XML and Class implementation

<authentication-manager alias="authenticationManager">
    <authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

<beans:bean id="customAuthenticationProvider" class="w.x.y.z.CustomAuthenticationProvider"></beans:bean



@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    //Implementation
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}

Is there anyway I can tell spring to pick any class implementing AuthenticationProvider?


Solution

  • Maybe you can do it by using type autowiring and factory method:

    1-The CustomAuthenticationProvider it will be injected by type autowiring defined only in the jar added by your client and the deleted jar(it must be exactly one instance of AuthenticationProvider).

    2-And then use a factory method to inject this provider into the authentication-manager.

    1-first step

    public class AuthenticationProviderFactory {
    
        @Autowired
        private AuthenticationProvider authProvider;
    
        public AuthenticationProvider getAuthenticationProvider() {
            return authProvider;
        }
    
    }
    

    2-second step

    <bean name="authenticationProviderFactory"
      class="w.x.y.z..AuthenticationProviderFactory"></bean>
    
    <bean name="authenticationProvider" factory-bean="authenticationProviderFactory"
    factory-method="getAuthenticationProvider">
    </bean>
    <authentication-manager alias="authenticationManager">
       <authentication-provider ref="authenticationProvider"/>
    </authentication-manager>
    

    !!!! The deleted jar and the new jar must have the same applicationContext.xml name(where the AuthenticationProvider is declared) to make the replace working.

    <import resource="applicationContextAuthProvider.xml"/>