Configuring Spring Security

Now, we will configure Spring Security authentication and authorization by creating a Spring Security configuration class as follows:

@EnableWebSecurity
public class SpringMvcSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
PasswordEncoder passwordEncoder;

@Override
protected void configure(AuthenticationManagerBuilder auth)
throws
Exception {
auth
.inMemoryAuthentication()
.passwordEncoder(passwordEncoder)
.withUser("user").password(passwordEncoder.encode("user@123"))
.roles("USER")
.and()
.withUser("admin").password(passwordEncoder.
encode("admin@123")
).roles("USER", "ADMIN");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/**").hasAnyRole("ADMIN","USER")
.and().formLogin()
.and().logout().logoutSuccessUrl("/login").permitAll()
.and()
.csrf().disable();
}
}

Let's understand the preceding configuration:

  • @EnableWebSecurity: It enables Spring Security's web security support, and also provides the Spring MVC integration.
  • WebSecurityConfigurerAdapter: It provides a set of methods that are used to enable specific web security configuration.
  • protected void configure(AuthenticationManagerBuilder auth): We have used in-memory authentication in this example. It can be used to connect to the database using auth.jdbcAuthentication(), or to a Lightweight Directory Access Protocol (LDAP) using auth.ldapAuthentication().
  • .passwordEncoder(passwordEncoder): We have used the password encoder BCryptPasswordEncoder.
  • .withUser("user").password(passwordEncoder.encode("user@123")): It sets the user ID and encoded password for authentication.
  • .roles("USER"): It assigns roles to the user.
  • protected void configure(HttpSecurity http): It is used to secure different URLs that need security.
  • .antMatchers("/login").permitAll(): It permits all of the users to access the login page.
  • .antMatchers("/admin/**").hasRole("ADMIN"): It permits access to the admin panel to the users who have the ADMIN role.
  • .antMatchers("/**").anyRequest().hasAnyRole("ADMIN", "USER"): It means that to make any request with "/", you must be logged in with the ADMIN or USER role.
  • .and().formLogin(): It will provide a default login page, with username and password fields.
  • .and().logout().logoutSuccessUrl("/login").permitAll(): It sets the logout success page when a user logs out.
  • .csrf().disable(): By default, the Cross Site Request Forgery (CSRF) flag is enabled. Here, we have disabled it from configuration.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset