Configuring Spring Security with the In-memory realm

In order to have the user's credentials defined In-memory, first we need to provide a custom Spring Security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user1")
.password(passwordEncoder().encode("secret1"))
.roles("USER");
}

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

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated();
http.httpBasic();
http.csrf().disable();
}
}

The SecurityConfig class extends WebSecurityConfigurerAdapter, which is a base class for creating the WebSecurityConfigurer instance, and it will allow us to perform the customization by overriding its methods. The first configure() method allows us to configure an authentication manager by passing AuthenticationManagerBuilder as a parameter. That will help us build an in-memory authentication, LDAP authentication, or a JDBC-based authentication. We are also providing a custom password encoder that is created by the passwordEncoder() method. With Spring Security 5, we need to set the password encoder, thus BCryptPasswordEncoder is used for demonstration purposes.  The second configure() method configures an instance of HttpSecurity by providing an HTTP authentication mechanism. The @EnableWebSecurity annotation is a marker annotation added onto the SecurityConfig configuration class to execute the customized configuration methods.

So, we will have user1 defined in our In-memory realm and we can send requests to our protected Temperature Microservice, as follows:

curl -u user1:secret1 http://localhost:8080/temperature

In the next section, we will integrate a database realm in order to store the credentials of the user in a persistence mechanism.

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

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