Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security - Switch between Authentication Providers at Runtime (local database OR remote LDAP)

im currently working of a Spring MVC web application and we have been using authtication via a local database with an impl of the AbstractUserDetailsAuthenticationProvider class provided by spring security.

However, to secure the app further, we decided to allow users to authenticate via LDAP/AD server. This would not be a requirement and users can choose to enable this in the configurations in the portal itself.

Wondering how would one actually go around implementing this. Have found the AbstractLdapAuthenticationProvider. However, just to add this additional authentication provider to the authentication manager would not suffice as weather or not it should be there should be determined at runtime by a flag in the database.

Would really appreciate any help in this area.

Thanks for reading:)

like image 281
jia chen Avatar asked Jul 14 '26 19:07

jia chen


2 Answers

There are probably multiple ways to do this, but a simple approach would be to have two authentication providers to the authentication manager, authentication provider for local database first, LDAP authentication provider second.

To skip LDAP check at runtime, throw AccountStatusException (a subclass thereof, since abstract) from your local database provider. This makes the authentication manager skip further providers, in your case LDAP.

If you want the other way around for a user, set the password to blank or a random value in local database.

like image 50
holmis83 Avatar answered Jul 17 '26 16:07

holmis83


Have two authentication providers, one for local database and one for LDAP. The Spring authentication manager will invoke the public boolean supports(Class authentication) method in each of the providers to see if the provider supports the Authentication class provided. So the supports(Class authentication) method is a perfect place for you to write your own custom logic to enable/disable a particular authentication provider.

like image 26
Chao Avatar answered Jul 17 '26 16:07

Chao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!