Using Spring Security for authentication and authorization

Spring Security is widely used to enable authentication and authorization, using many different mechanisms such as form-based logic, header-based login (Basic), and so on. In this application, we will be protecting the User Registration microservice. Consider the following code:

<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
...
</dependencies>

The preceding entries will import all the dependencies related to Spring Security. Now, let's look at the configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/users/reset-password/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/users**").hasRole("USER").and().formLogin().permitAll();
}
}

In the configure(WebSecurity web) method, it configures the ignore "/users/reset-password" from Spring Security. In the configure(HttpSecurity http) method, it configures a formLogin() method and protects the "/users" URL to have the role USER to access it. @EnableWebSecurity will enable all the other configurations required for Spring Security. Also, it creates ScryptPasswordEncoder as the passwordEncoder bean so that it will be used to encode passwords.

..................Content has been hidden....................

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