Spring Security when to use WebSecurityConfigurerAdapter and UserDetailsService - spring

can someone explain me when to use WebSecurityConfigurerAdapter and when UserDetailsService. I just started learning spring security, noticed that extending both interfaces you can create security implementation. But which one I should use if I want to create security for web project connection from angular based site and user data saved in Database.

The components you are talking about have very different responsibilities and therefore the question do I use one or the other? does not really make sense. Take a look at the JavaDocs of those components to learn the difference.
UserDetailsService
Core interface which loads user-specific data. It is used throughout the framework as a user DAO and is the strategy
used by the DaoAuthenticationProvider. The interface requires only one read-only method, which simplifies
support for new data-access strategies.
WebSecurityConfigurerAdapter
Provides a convenient base class for creating a WebSecurityConfigurer instance. The implementation allows customization by overriding methods.
For example you could have security configuration class which extends WebSecurityConfigurerAdapter and uses custom UserDetailsService to load user information like so:
#Configuration
#EnableWebMvcSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());
authenticationProvider.setUserDetailsService(userService);
return authenticationProvider;
}
// ...
}
The core components of Spring Security and their responsibilities are also nicely described in the reference guide.

Related

Reason for #EnableWebSecurity in the configuration class

I just read answer from the another question What is the use of #EnableWebSecurity in Spring?, but i couldn't understand why we need to add #EnableWebSecurity annotation at all.
Even I remove the #EnableWebSecurity from the configuration, my application still works.
Let's assume that we are going to implement either JWT based (rest api) or simply login based mvc application. For the following configuration what i am missing?
#Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new MyCustomUserDetailsService();
}
#Bean
public PasswsordEncoder passwsordEncoder() {
return new BrcyptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// for the jwt authentication add jwt filter etc ..
// for the login based, override default login page, error page etc..
}
}
If you are not using spring-boot but just a pure spring project , you definitely need to add #EnableWebSecurity in order to enable spring-security.
But if you are using spring-boot 2.0 +, you do not need to add it by yourself because the spring-boot auto configuration will automatically do it for you if you forget to do so. Under the cover , it is done by the WebSecurityEnablerConfiguration which its javadoc also states this behaviour as follows:
If there is a bean of type WebSecurityConfigurerAdapter, this adds the
#EnableWebSecurity annotation. This will
make sure that the annotation is present with default security
auto-configuration and also if the user adds custom security and
forgets to add the annotation.

How to define a custom UserDetailsService with WebSecurityConfigurerAdapter?

I'm a bit lost at how WebSecurityConfigurerAdapter should be correctly extended to properly use a custom UserDetailsService and expose it as a bean.
I mean, there are:
userDetailsService(): Javadoc says:
Allows modifying and accessing the UserDetailsService from
userDetailsServiceBean() without interacting with the
ApplicationContext. Developers should override this method when
changing the instance of userDetailsServiceBean().
userDetailsServiceBean(): Javadoc says:
Override this method to expose a UserDetailsService created from
configure(AuthenticationManagerBuilder) as a bean. [...] To change
the instance returned, developers should change
userDetailsService() instead
configure(AuthenticationManagerBuilder): Javadoc says:
[...] The authenticationManagerBean() method can be used to expose
the resulting AuthenticationManager as a Bean. The
userDetailsServiceBean() can be used to expose the last populated
UserDetailsService that is created with the
AuthenticationManagerBuilder as a Bean. The UserDetailsService
will also automatically be populated on
HttpSecurity#getSharedObject(Class) for use with other
SecurityContextConfigurer (i.e. RememberMeConfigurer)"
If I just read this, I understand that:
configure(AuthenticationManagerBuilder) configures an AuthenticationManager, which can be exposed by overriding authenticationManagerBean() to be marked with #Bean; to build this AuthenticationManager, configure(AuthenticationManagerBuilder) builds and wires a UserDetailsService
overriding userDetailsServiceBean() (to mark with #Bean) allows to expose the UserDetailsService built and wired by the previous method
if I want configure(AuthenticationManagerBuilder) to use my own implementation of UserDetailsService, I must override userDetailsService() to return it; it will be then exposed by overriding userDetailsServiceBean()
So I ended up with this:
#Override
protected void configure(final AuthenticationManagerBuilder auth)
throws Exception {
final MyUserDetailsService userDetailsService = userDetailsService();
auth.userDetailsService(userDetailsService);
// all the other configuration has been omitted
}
#Override
protected MyUserDetailsService userDetailsService() {
return new MyUserDetailsService();
}
#Bean
#Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
However, this is what puzzles me and what I see:
the default implementation of configure(final AuthenticationManagerBuilder auth) substantially does nothing (just sets disableLocalConfigureAuthenticationBldr to true) and in particular it does not call userDetailsService(); it's my overriding that does it, so it's me that I'm injecting my custom UserDetailsService implementation through the use of userDetailsService(); in other words, if I don't override userDetailsService() and create the custom UserDetailsService instance in configure(final AuthenticationManagerBuilder auth) directly, I get the same result
probably related to the above: the default implementation of userDetailsService() is exactly identical to that of userDetailsServiceBean()... I would have expected the latter to delegate sooner or later to the former, but if the former default implementation is actually the same... I really get lost and I wonder why two distinct methods are provided
I would expect that, with the above, my custom MyUserDetailsService implementation is exposed in the application context, but if I try to inject a MyUserDetailsService instance somewhere else, Springs complains that there's no such instance in my application context; indeed, the bean returned by userDetailsServiceBean() is always some kind of delegating wrapper; if I inject a generic UserDetailsService instance and try to use it, I get an IllegalStateException saying that "UserDetailsService is required" (the delegation mechanism in org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.UserDetailsServiceDelegator.loadUserByUsername(String) fails to retrieve a proper default UserDetailsService...)
by debugging I see that userDetailsService() is invoked twice (hence creating two DISTINCT instances of MyUserDetailsService), once by the above implementation of configure(final AuthenticationManagerBuilder auth), and once by org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.createSharedObjects()...
So, the above is clearly incorrect (authentication works because the right UserDetailsService is injected into the AuthenticationManager, but it fails to expose the UserDetailsService in the application context) and I may probably overcome all these problems by simply marking a MyUserDetailsService bean with #Service or by writing yet another #Bean method in my WebSecurityConfigurerAdapter extension that returns an instance of my custom UserDetailsService, hence bypassing both userDetailsService() and userDetailsServiceBean()... But I'm not sure this is the best way to achieve the desired result (those two methods should have been put there for some reason...)
I really think WebSecurityConfigurerAdapter is overly complicated in how it handles this...
The way to configure custom UserDetailsService depends on the number ofUserDetailsServices and kind of UserDetailsService.
Also remember there are different ways to expose a bean in Spring: #Configuration with factory method (#Bean), #ComponentScan with #Component, XML etc.
One global UserDetailsService
If you want to use one global custom UserDetailsService you only have to expose it, see Spring Security Reference:
10.10.7. UserDetailsService
UserDetailsService is used by DaoAuthenticationProvider for retrieving a username, password, and other attributes for authenticating with a username and password. Spring Security provides in-memory and JDBC implementations of UserDetailsService.
You can define custom authentication by exposing a custom UserDetailsService as a bean. For example, the following will customize authentication assuming that CustomUserDetailsService implements UserDetailsService:
This is only used if the AuthenticationManagerBuilder has not been populated and no AuthenticationProviderBean is defined.
Example 66. Custom UserDetailsService Bean
#Bean
CustomUserDetailsService customUserDetailsService() {
return new CustomUserDetailsService();
}
The default implementations of userDetailsService() and userDetailsServiceBean() return the global UserDetailsService. There is no need to override these methods.
Different UserDetailsServices
If you want to use different UserDetailsServices for different WebSecurityConfigurerAdapters you could override WebSecurityConfigurerAdapter#configure:
Used by the default implementation of authenticationManager() to attempt to obtain an AuthenticationManager. If overridden, the AuthenticationManagerBuilder should be used to specify the AuthenticationManager.
and add it with AuthenticationManagerBuilder#userDetailsService:
Add authentication based upon the custom UserDetailsService that is passed in. It then returns a DaoAuthenticationConfigurer to allow customization of the authentication.
The default implementations of userDetailsService() and userDetailsServiceBean() return the UserDetailsService of the AuthenticationManagerBuilder.
If you want to inject the UserDetailsService to another component, you could override userDetailsServiceBean(). If you expose more than one UserDetailsService you have to use different bean names.
Built-in UserDetailsService
There are some built-in UserDetailsServices created by AuthenticationManagerBuilder, which are not exposed.
If you need such an UserDetailsService in another component, you have to override
userDetailsServiceBean(), see WebSecurityConfigurerAdapter#configure:
For example, the following configuration could be used to register in memory authentication that exposes an in memory UserDetailsService:
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth
// enable in memory based authentication with a user named
// "user" and "admin"
.inMemoryAuthentication().withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
// Expose the UserDetailsService as a Bean
#Bean
#Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
If you expose more than one UserDetailsService you have to use different bean names.

How to configure UserDetailsChecker for preAuthenticationChecks and postAuthenticationChecks in Spring Boot

I'm searching for a 'best practice' solution for configuring a UserDetailsChecker for preAuthenticationChecks and/or postAuthenticationChecks in Spring Boot (see AbstractUserDetailsAuthenticationProvider and DaoAuthenticationProvider).
Is it absolute necessary to create a custom DaoAuthenticationProvider?
No way to customize it via WebSecurityConfigurerAdapter or AuthenticationManagerBuilder?
Answering my own question: I've searched the spring boot sources (v1.5.13.RELEASE and v2.0.2.RELEASE) with grep - no results.
At least in this versions you have to create a custom DaoAuthenticationProvider if you want to make use of additional pre- or post authentication checks.
Edit: The phrase "you have to create a custom DaoAuthenticationProvider" is a bit misleading. In a recent project I've done it in the following way:
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig {
#Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth,
MyUserAccountService myUserAccountService,
PasswordEncoder passwordEncoder,
MessageSourceAccessor messageSourceAccessor
) throws Exception {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
daoAuthenticationProvider.setUserDetailsService(myUserAccountService);
daoAuthenticationProvider.setPostAuthenticationChecks(new UserAccountChecker(messageSourceAccessor));
auth.authenticationProvider(daoAuthenticationProvider);
auth.userDetailsService(myUserAccountService).passwordEncoder(passwordEncoder);
}
[...]
}
Here UserAccountChecker implements UserDetailsChecker is a class where the (post) authentication tests take place (also see the class DefaultPostAuthenticationChecks in AbstractUserDetailsAuthenticationProvider).

How can I do relational database-based HTTP Session Persistence in Spring 4?

I need to be able to store the HTTP Session in a relational database in order to do stateless load balancing of my front-end users across multiple front-end servers. How can I achieve this in Spring 4?
I see how one can do this with Redis, however there does not appear to be documentation on how to do this with a relational database e.g. Postgres.
With Spring Session (it transparently will override HttpSessions from Java EE) you can just take SessionRepository interface and implement it with your custom ex. JdbcSessionRepository. It is kind of easy to do. When you have your implementation, then just add manually (you don't need #EnableRedisHttpSession annotation) created filter to filter chain, like bellow:
#Configuration
#EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
//other stuff...
#Autowired
private SessionRepository<ExpiringSession> sessionRepository;
private HttpSessionStrategy httpSessionStrategy = new CookieHttpSessionStrategy(); // or HeaderHttpSessionStrategy
#Bean
public SessionRepository<ExpiringSession> sessionRepository() {
return new JdbcSessionRepository();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
SessionRepositoryFilter<ExpiringSession> sessionRepositoryFilter = new SessionRepositoryFilter<>(sessionRepository);
sessionRepositoryFilter.setHttpSessionStrategy(httpSessionStrategy);
http
.addFilterBefore(sessionRepositoryFilter, ChannelProcessingFilter.class);
}
}
Here you have how SessionRepository interface looks like. It has only 4 methods to implement. For how to create Session object, you can look in MapSessionRepository and MapSession implementation (or RedisOperationsSessionRepository and RedisSession).
public interface SessionRepository<S extends Session> {
S createSession();
void save(S session);
S getSession(String id);
void delete(String id);
}
Example solution https://github.com/Mati20041/spring-session-jpa-repository
Now spring boot supports by 'spring-session-jdbc'. You can save session into db with less code. For more example you can look at https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-jdbc.html#httpsession-jdbc-boot-sample
Just slap Spring Session on it, and you're done. Adding a Redis client bean and annotating a configuration class with #EnableRedisHttpSession is all you need.

Custom WebSecurityConfigurerAdapter

I have this problem implementing a custom login authentication using SpringBoot and SpringBoot-Security. I made a Bitbucket repository as reference for this thread (within CustomSecuringWeb branch). Before anything else, most of the comments here follows the Securing a Web Application tutorial.
The thing is, I was curious as how could the authentication data is now from the database instead of just memory data (which is very common in production line applications).
Throughout the process I made two attempts (though both attempts are located on the same branch - my bad for that).
Created a custom UserDetailsService implementation
Created a custom AbstractUserDetailsAuthentictionProvider implementation
I don't know where the problem lies, but upon checking the console log both returns that the persistence(even the repository) DI on each custom class where null.
The question is how could I make both attempts working. And (possibly) which one of the two attempts is better than the other.
First of all the two approaches are used for different purpose and not interchangeable.
Case 1:
UserDetailsService is used purely as DAO to locate user information by your authentication and based on that info authenticate user, no authentication should be done within UserDetailsService, just data access.
Specifications clearly mention that. This is what you are looking for.
Case2:
AuthentictionProvider on the other hand is used for providing custom method of authentication, for example if you want to custom authenticate on fields other than login and password you may do that by implementing AuthentictionProvider and supplying this object to your AuthenticationManagerBuilder. I do not think this is what you want to do in you project. You are just looking to implement your authentication based on users stored in database using login and password which is default way.
In above Case 1 where you implemented just UserDetailsService, instance of AuthentictionProvider was created for you in AuthenticationManager by the container and it was DaoAuthenticationProvider since you supplied UserDetailsService which is nothing else but DAO in your system that is used to retrive user for authentication.
Now to your implementation,
in your configuration instead of :
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(new AdminSecurityService());
auth.authenticationProvider(new AdminSecurityAuthenticationProvider());
}
do something like this
#Autowired
private CustomUserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
and your CustomUserDetailsService has to implement org.springframework.security.core.userdetails.UserDetailsService
#Service
public class CustomUserDetailsService implements UserDetailsService {
private final AdminRepository userRepository;
#Autowired
public CustomUserDetailsService(AdminRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Admin user = userRepository.findByLogin(username);
if (user == null) {
throw new UsernameNotFoundException(String.format("User %s does not exist!", username));
}
return new UserRepositoryUserDetails(user);
}
private final static class UserRepositoryUserDetails extends Admin implements UserDetails {
private static final long serialVersionUID = 1L;
private UserRepositoryUserDetails(User user) {
super(user);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_USER");
}
#Override
public String getUsername() {
return getLogin();//inherited from user
}
#Override
public boolean isAccountNonExpired() {
return true;//not for production just to show concept
}
#Override
public boolean isAccountNonLocked() {
return true;//not for production just to show concept
}
#Override
public boolean isCredentialsNonExpired() {
return true;//not for production just to show concept
}
#Override
public boolean isEnabled() {
return true;//not for production just to show concept
}
//getPassword() is already implemented in User.class
}
}
of course implementation is up to you but you have to be able to provide user password, and rest of the methods in that interface based on the retrieved user (Admin.class in your case). Hope it helps. I did not run this example so if I made some typos go ahead and ask if something does not work. I would also get rid of that 'AuthentictionProvider' from your project if you don't need it.
Here you got documentation:http://docs.spring.io/spring-security/site/docs/4.0.0.RC1/reference/htmlsingle/#tech-userdetailsservice
After comments:
You can set PasswordEncoder in your configure method without too much hassle just do:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
#Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
You can do that because you get access to AbstractDaoAuthenticationConfigurer returned from auth.userDetailsService(userDetailsService) and it allows you to configure DaoAuthenticationProvider, which is your provider of choice when you choose to use UserDetailsService.
You are right PasswordEncoder is set in AuthenticationProvider but you do not have to
implement AuthenticationProvider just use convineince object that is returned from auth.userDetailsService(userDetailsService) and set your encoder on that object which will pass it to AuthenticationPriovider in your case DaoAuthenticationProvider that was already created for you.
Just like roadrunner mentioned in the comment you very rarely need to implement your own AuthenticationProvider usually most of authentication configuration adjustments can be done with the use of AbstractDaoAuthenticationConfigurer which as mentioned above is returned from auth.userDetailsService(userDetailsService).
"And if I ever wanted to add a password encryption. And if I ever wanted to do other authentication (like checking if the user is locked, active, user is still logged-in, etc. [excluding password hashing]) will use the AuthenticationProvider."
No this is done for you as part of standard authentication mechanism
http://docs.spring.io/autorepo/docs/spring-security/3.2.0.RELEASE/apidocs/org/springframework/security/core/userdetails/UserDetails.html
If you look at the interface UserDetails you will see that if any of the above methods returns false authentication will fail.
Implementing AuthenticationProvider is really needed in very nonstandard cases. All standard stuff is pretty much covered by the framework .
In a JDBC way http://www.mkyong.com/spring-security/spring-security-form-login-using-database/ basically, you have to specify the query to retrieve users.
Firstly I would encourage you to read about String Security Core Services.
A key one in this situation is AuthenticationManager that is responsible for deciding if the user is authenticated or not. This is what you configure with AuthenticationManagerBuilder. It's primary implementation in Spring is ProviderManager that allows to define multiple authentication mechanisms in a single applications. The most common use case is that there is one, but it is still handled by this class. Each of those multiple authentication mechanisms is represented by a different AuthenticationProvider. ProviderManager takes a list of AunthenticationProviders an iterates through them to see if any of them can authenticate the user.
What you are interested in is DaoAuthenticationProvider. As the name suggests, it allows to use a Data Access Object to authenticate the user. It uses a standard interface for such DAO - a UserDetailsService. There is a default implementation available in Spring Security, but usually this is the bit you will want to implement yourself. All the rest is provided.
Also, the configuration bit you need is totally independent from Spring Boot. This is how you'd do it in XML:
<sec:authentication-manager >
<sec:authentication-provider user-service-ref="myUserDetailsService" />
</sec:authentication-manager>
And in Java it will be:
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService myUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService);
}
}
As per UserDetails implementation, usually the one provided by Spring Security is enough. But you can also implement your own if need be.
Usually you will also want a PasswordEncoder. A good one, like BCryptPasswordEncoder:
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private PasswordEncoder passwordEncoder;
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
}
Notice that it's a #Bean, so that you can #Autowire it in your UserRepository to encode user passwords as you save them in the database.

Resources