Spring Framework Tutorial
Software Setup and Configuration (STS/Eclipse/IntelliJ)
Core Spring
Spring Annotations
Spring Data
Spring JDBC
Spring Security
To add a username and password for authentication in Spring Security, you can use in-memory authentication, JDBC authentication, or other authentication methods. Here, I'll show you how to add a simple username and password using in-memory authentication and then provide a brief overview of JDBC authentication:
Using in-memory authentication, you can define a user directly in your security configuration:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("username") // specify the username .password(passwordEncoder().encode("password")) // specify the password .roles("USER"); // specify the role } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
In this example, I'm using the BCryptPasswordEncoder
to encode the password, which is recommended for security reasons.
For JDBC authentication, Spring Security provides a way to read user credentials directly from the database.
First, add the JDBC driver to your pom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency>
Assuming you have tables users
and authorities
in your database with schema as Spring Security expects, you can configure JDBC authentication as follows:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired DataSource dataSource; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .jdbcAuthentication() .dataSource(dataSource) .usersByUsernameQuery("select username, password, enabled from users where username = ?") .authoritiesByUsernameQuery("select username, authority from authorities where username = ?"); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
Note: The usersByUsernameQuery
and authoritiesByUsernameQuery
methods allow you to define custom queries if your schema is different from what Spring Security expects.
UserDetailsService
where you can provide custom logic for fetching user details.Spring Security add user with username and password:
UserDetailsService
and provide authentication details.@Service public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Fetch user details from your data source User user = // ... retrieve user details // Return a UserDetails object with username, password, and authorities return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), getAuthorities(user) ); } private List<GrantedAuthority> getAuthorities(User user) { // Retrieve user roles and map them to GrantedAuthorities // ... return authorities; } }
Configuring user credentials in Spring Security:
UserDetailsService
bean.@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // Other configurations... }
How to set up username and password authentication in Spring Security:
AuthenticationManagerBuilder
.@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}admin").roles("USER", "ADMIN"); }
Adding users to Spring Security with authentication details:
UserDetailsService
and returning authentication details.public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Fetch user details from your data source User user = // ... retrieve user details // Return UserDetails with authentication details return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.getAuthorities() ); } }
Customizing user authentication in Spring Security:
UserDetailsService
and configuring authentication mechanisms.@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()) .and() .authenticationProvider(customAuthenticationProvider()); } @Bean public DaoAuthenticationProvider customAuthenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } // Other configurations... }
Securing Spring application with username and password in Spring Security:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .antMatchers("/user/**").hasRole("USER") .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .and() .httpBasic(); }
Defining user credentials in Spring Security:
UserDetailsService
implementation.public class CustomUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // Fetch user details from your data source User user = // ... retrieve user details // Define user credentials (username, password, authorities) return new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(), user.getAuthorities() ); } }
Managing user authentication in Spring Security:
UserDetailsService
and related configurations.@Autowired private CustomUserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); }
Spring Security username and password authentication example:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}admin").roles("USER", "ADMIN"); }