Search code examples
guiceshiro

shiro & guice - How to inject AuthenticationStrategy?


I'm using Shiro and guice. Shiro has two active realms.

The default shiro AuthenticationStrategy is "AtLeastOneSuccessfulStrategy". The basic idea of this strategy is fine but the problem is that it ignore reams exceptions. this mean that if Realm1 throws IncorrectCredentialsException there is no way to know it as it is wrapped by AuthenticationException with message that non of the realms support the token.

How do I replace the strategy with FirstSuccessfulStrategy ?

currently this is what i have in the ShiroWebModule:

   @Override
    protected void configureShiroWeb() {
       Multibinder<Realm> multibinder = Multibinder.newSetBinder(binder(), Realm.class);
        multibinder.addBinding().to(RealmA.class);
        multibinder.addBinding().to(RealmB.class);
        bind( HashedCredentialsMatcher.class );
        bind( CredentialsMatcher.class ).to( HashedCredentialsMatcher.class );
        bindConstant().annotatedWith( Names.named( "shiro.hashAlgorithmName" ) ).to( Md5Hash.ALGORITHM_NAME );
        addFilterChain( "/login.jsp", AUTHC_REST );
    }

    @Override
    protected void bindSessionManager( AnnotatedBindingBuilder<SessionManager> bind ) {
        bind.to( ServletContainerSessionManager.class );
    }

Solution

  • solved by adding

       bind(Authenticator.class).toInstance(new ModularRealmAuthenticator());
       bind(AuthenticationStrategy.class).to(FirstSuccessfulStrategy.class);
    

    to the configureShiroWeb() method.