I'm learning about Spring Security in a Spring Boot app and I have a very simple example. And I see that if I comment the configure(AuthenticationManagerBuilder auth) there is no difference. If I use it or not I have the same output, and I need to login with the hardcoded credentials.
#Configuration
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// private final MyUserDetailsService myUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
// #Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(myUserDetailsService);
// }
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
MyUserDetailsService class:
#Service
public class MyUserDetailsService implements UserDetailsService {
private static final String USERNAME = "john";
private static final String PASSWORD = "$2a$10$fDDUFA8rHAraWnHAERMAv.4ReqKIi7mz8wrl7.Fpjcl1uEb6sIHGu";
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
if (!userName.equals(USERNAME)) {
throw new UsernameNotFoundException(userName);
}
return new User(USERNAME, PASSWORD, new ArrayList<>());
}
}
RestController:
#RestController
public class HelloController {
#GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
I want to know if implementing the UserDetailsService interface is equivalent with overriding the configure(AuthenticationManagerBuilder auth). Thank you!
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
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which can be overridden to customize the process of finding the user. In order to provide our own user service, we will need to implement the UserDetailsService interface.
loadUserByUsername(String username) returns the UserDetails which is part of org.springframework.security.core.userdetails which consists of getUsername(), getPassword(), getAuthorities() methods which is used further for spring security.
We can also customize the org.springframework.security.core.userdetails.User (here used as new User(USERNAME, PASSWORD, new ArrayList<>())) by implemeting the UserDetails interface.
Here, I am sharing the ideal way to use the UserDetailsService service
#Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
#Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login)
.map(user -> createSpringSecurityUser(login, user))
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
}
when loadUserByUsername is invoked?
As described above, It is typically called by DaoAuthenticationProvide instance in order to authenticate a user. For example, when a username and password is submitted, a UserdetailsService is called to find the password for that user to see if it is correct. It will also typically provide some other information about the user, such as the authorities and any custom fields you may want to access for a logged in user (email, for instance)
In-Memory Authentication
Here you have used the static values for username and password which can be ideally configured using the In-Memory Authentication as follow.
Spring Security’s InMemoryUserDetailsManager implements UserDetailsService to provide support for username/password based authentication that is retrieved in memory. InMemoryUserDetailsManager provides management of UserDetails by implementing the UserDetailsManager interface. UserDetails based authentication is used by Spring Security when it is configured to accept a username/password for authentication.
#Bean
public UserDetailsService users() {
UserDetails user = User.builder()
.username("user")
.password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
.roles("USER")
.build();
UserDetails admin = User.builder()
.username("admin")
.password("{bcrypt}$2a$10$GRLdNijSQMUvl/au9ofL.eDwmoohzzS7.rmNSJZ.0FxO/BTk76klW")
.roles("USER", "ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
configure(AuthenticationManagerBuilder auth)
This method uses AuthenticationManagerBuilder which internally use SecurityBuilder to create an AuthenticationManager. Allows for easily building in memory authentication, LDAP authentication, JDBC based authentication, adding UserDetailsService, and adding
AuthenticationProvider.
How Spring Security add/configure AuthenticationManagerBuilder?
UserDetailsService interface is equivalent with overriding the
configure(AuthenticationManagerBuilder auth)
No
No, it's not same.
User details service provided in the application as bean is registered with global authentication manager (details) and is fallback for all the local authentication manager.
Depending on application set up can have multiple local authentication managers. Each local authentication manager will use the default user details service configured with configure(AuthenticationManagerBuilder auth).
When should I override the configure(AuthenticationManagerBuilder
auth) from Spring Security in a Spring Boot app?
You should override if you have different authorization/authentication requirements and would you like to plugin your own authentication provider to satisfy the requirement or add any built in provider like ldap and in memory providers. You can also do it directly using http security bean shown below.
All the authentication providers are added to Provider Manager and are tried until one is found.
By default without providing anything ( i.e. without user details service or without overriding authentication manager ) you would have the default global authentication manager with auto configured user details manager ( i.e user password InMemoryUserDetailsManager implementation as configured in UserDetailsServiceAutoConfiguration auto configuration ).
So when you provide user details service application bean the auto configuration backs off and now your global authentication manager now is configured with the provided bean.
More details here
Here is the good explanation how it all comes together.
I would also like to expand little bit more on spring security authentication manager in general which is very easy to overlook.
As I previously noted there is global authentication manager and local authentication managers. There is special care to be taken when configuring each if needed.
This is explained in the java doc for the global authentication manager annotation.
The EnableGlobalAuthentication annotation signals that the annotated
class can be used to configure a global instance of
AuthenticationManagerBuilder.
For example:
#Configuration
#EnableGlobalAuthentication
public class MyGlobalAuthenticationConfiguration {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER")
.and().withUser("admin").password("password").roles("USER", "ADMIN");}}
Annotations that are annotated with EnableGlobalAuthentication also signal that the annotated class can be
used to configure a global instance of AuthenticationManagerBuilder.
For example:
#Configuration
#EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER")
.and().withUser("admin").password("password").roles("USER", "ADMIN");
}
// Possibly overridden methods ... }
The following annotations are annotated with EnableGlobalAuthentication
EnableWebSecurity EnableWebMvcSecurity EnableGlobalMethodSecurity
Configuring AuthenticationManagerBuilder in a class without the
EnableGlobalAuthentication annotation has unpredictable results.
EnableGlobalAuthentication imports configuration AuthenticationConfiguration responsible for setting up the default configuration for global authentication manager.
AuthenticationConfiguration configures two key pieces to make the authentication manager - user details and authentication provider.
User details is configured using InitializeUserDetailsBeanManagerConfigurer and authentication provider is configured using InitializeAuthenticationProviderBeanManagerConfigurer. Both of required beans are looked up in application context - that is how your user detail service is registered with global authentication manager.
GlobalMethodSecurityConfiguration and WebSecurityConfigurerAdapter are consumers of global authentication managers.
WebSecurityConfigurerAdapter can be used to create and configure local authentication manager (add new authentication providers) and also typically used to have different authentication/authorization requirements in application like mvc vs rest and public vs admin endpoints.
With spring security alone #EnableWebSecurity triggers the above flow as part of spring security filter chain set up. With spring boot the same flow is triggered by spring security auto configuration.
In spring security 5.4 version you can define http security as beans without needing to extend WebSecurityConfigurerAdapter class. Spring boot will have support for this in 2.4.0 release. More details here
#Bean
SecurityFilterChain configure(HttpSecurity http) throws Exception
{
http
.authenticationProvider(custom authentication provider)
.userDetailsService( custom user details service)
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
}
You are using the #Service annotation which creates the bean of the UserDetailsService at the time of the component scan. There is no need to specify it again in the AuthenticationManagerBuilder.
If you don't use the #Service annotation, then you can configure it manually in the WebSecurityConfigurerAdapter by over-riding the AuthenticationManagerBuilder.
To switch off the default web application security configuration completely you can add a bean with #EnableWebSecurity as explained in the spring boot documentation (section 4.10.1. MVC Security),
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(MyAuthenticationProvider);
}
}
The #EnableWebSecurity is a marker annotation. It allows Spring to find (it's a #Configuration and, therefore, #Component) and automatically apply the class to the global WebSecurity
To switch off the default web application security configuration completely you can add a bean with #EnableWebSecurity (this does not disable the authentication manager configuration or Actuator’s security). To customize it you normally use external properties and beans of type WebSecurityConfigurerAdapter (e.g. to add form-based login).
...
If you add #EnableWebSecurity and also disable Actuator security, you will get the default form-based login for the entire application unless you add a custom WebSecurityConfigurerAdapter.
...
If you define a #Configuration with #EnableWebSecurity anywhere in your application it will switch off the default webapp security settings in Spring Boot (but leave the Actuator’s security enabled). To tweak the defaults try setting properties in security.* (see SecurityProperties for details of available settings) and SECURITY section of Common application properties.
No, implementing the UserDetailsService interface is not equivalent to overriding the configure(AuthenticationManagerBuilder auth).
If you override UserDetailsSeervice and verify the username and password by override loadUserByUsername(), in your case it is static values(I would recommend for static users use inMemoryAuthentication).
You need to Autowired UserDetailsService
#Autowired
UserDetailsService userDetailsService;
And
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
this will tell your authenticationManager to use userDetailsService which is been implemented for authentication.
I want to know if implementing the UserDetailsService interface is equivalent with overriding the configure(AuthenticationManagerBuilder auth).
No, they are not comparable.
UserDetailsService is 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. *
and
AuthenticationManagerBuilder allows for easily building in memory authentication, JDBC based authentication, adding UserDetailsService, and adding AuthenticationProvider's.
So it is evident that when you use UserDetailsService, it means you are using DaoAuthenticationProvider for fetching user details from your underlying database.
NOTE: AuthenticationProvider is an abstraction for fetching user information from different sources/repositories and validates if the retrieved information is similar to the one provided by users.
Let's see an example, the configuration looks like this:
#Autowired
YourUserDetailServiceImpl userDetailsService;
.....
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
...
#Bean
public DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); //a provider
provider.setUserDetailsService(userDetailsService); //user details service
provider.setPasswordEncoder(encoder()); //you can add password encoders too
return provider;
}
And YourUserDetailServiceImpl has to override loadUserByUsername() to fetch used details.
#Override
public UserDetails loadUserByUsername(String email) {
final Account acc = accRepository.findByEmail(email);
if (acc == null)
throw new UsernameNotFoundException("Account not found");
//this can be a custom Object of your choice that `extends User`
return new UserPrincipal(
acc.getEmail(),
acc.getPassword(),
acc.isEnabled(),
true, true, true,
acc.getEpsRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
.collect(Collectors.toList()));
}
When configuring Spring Security :
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
//#Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
when running, with or without #Autowired, it works.
where AuthenticationManagerBuilder come from if it's not Autowired ?
There is no "injection" going on there. 'configure' is just a method that takes a AuthenticationManagerBuilder object.
Your SecurityConfig object implements WebSecurityConfigurerAdapter, and is a Spring Bean because of the annotations on it. You also enable security behavior via an annotation. All of this will cause Spring to be looking for beans of type WebSecurityConfigurerAdapter to serve a purpose in the set up of security. It finds your bean because it is one of these objects.
Spring knows what this type of bean is supposed to do, so it just calls the appropriate methods on that bean.
Because you have overloaded one of the methods of WebSecurityConfigurerAdapter, your version of that method will be called.
#Autowired is only for member variables that reference beans.
It is injected automatically in the method by the caller. Anyway #Autowiring has no role to play in a method argument.
I am new to JPA and Spring Boot.
http://www.baeldung.com/spring-security-registration-password-encoding-bcrypt
I'm looking to encode the password -- where would I place this bean -- do I just define it in my application.properties or in the pom.xml
Also you can define in your #Configuration beans, but is recommend to define password encoder in your ##EnableWebSecurity beans, it is automatically add #Configuration annotation for you and you can config more security related things.
#EnableWebSecurity
public class YourWebConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
}
I am relatively new to Spring in general but have read through the Apress Spring Rest text and gotten the examples running in Eclipse without problem.
Something that puzzles me in the examples is how objects appear to be automatically injected.
For example in chapter 8 security there is a QuickPollUserDetailsService class which implements the spring UserDetailsService class.
The text says the following:
"The SecurityConfig class declares a userDetailsService property, which gets injected with a QuickPollUserDetailsService instance at runtime."
#Configuration
#EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Inject
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService) .passwordEncoder(new BCryptPasswordEncoder());
}}
Nowhere in any file does it specify QuickPollUserDetailsService is to be set.
Is Spring being smart here and noticing that QuickPollUserDetailsService is the only implementer of UserDetailsService and therefore assuming that it must be injected?
If that is the case what if I had 2 or more implementer's of UserDetailsService
By default, Spring Boot will recursively scan the packages and available implementation will be automatically injected. If there is more than one implementation available, startup will fail.
I try to translate the following websecurity configuration written in Java to a plain-yml configuration.
#Order(Ordered.HIGHEST_PRECEDENCE)
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/register/**").permitAll()
.anyRequest().authenticated().and().csrf().disable()
.httpBasic();
}
#Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
This is the security relevant part of my application.yml:
security:
require_ssl: true
basic:
enabled: true
enable_csrf: false
ignored:
- /register/**
When I use the yml-version the endpoints are not accessible without authentication, but also valid users are not permitted to access the site. I think it's because I am using a custom userDetailsService which is not recognised.
How can I define the same behaviour of the registerAuthentication-method part with the yml-version? Is there a security.userDetailsServiceClass property or something similar?
On application properties reference there is nothing related to UserDetailsService, so must be not supported,also it's a advanced condiguration which can be done by normal configuration. Boot provides via properties only simple configuration to get start quickly, like httpBasic, you can combine both, but note your
ignored:
- /register/**
are clashing with Java Config's matchers