Enabling reactive security

The last part that we haven't yet covered is how complex it is to enable security in a reactive web application. Fortunately, the configuration of security in a modern WebFlux-based application requires the declaration of few beans. The following is a reference example of how we may do this:

@SpringBootConfiguration                                           // (1)
@EnableReactiveMethodSecurity // (1.1)
public class SecurityConfiguration { //

@Bean // (2)
public SecurityWebFilterChain securityWebFilterChain( //
ServerHttpSecurity http // (2.1)
) { //
return http // (2.2)
.formLogin() //
.and() //
.authorizeExchange() //
.anyExchange().authenticated() //
.and() //
.build(); // (2.3)
} //

@Bean // (3)
public ReactiveUserDetailsService userDetailsService() { //
UserDetails user = //
User.withUsername("user") // (3.1)
.withDefaultPasswordEncoder() //
.password("password") //
.roles("USER", "ADMIN") //
.build(); //
return new MapReactiveUserDetailsService(user); // (3.2)

} //
}

The preceding numbers in the code may be explained as follows:

  1. This is the declaration of the configuration class. Here, in order to enable a specific annotated MethodInterceptor, we have to add the @EnableReactiveMethodSecurity annotation, which imports the configurations required for that, as shown in (1.1).
  2. Here, we have the configuration of the SecurityWebFilterChain bean. In order to configure the required bean, Spring Security provides us with ServerHttpSecurity, which is a builder (shown in 2.3) with a fluent API (shown in 2.2).
  3. This is the configuration of the ReactiveUserDetailsService bean. In order to authenticate a user in the default Spring Security setup, we have to provide an implementation of ReactiveUserDetailsService. For demonstration purposes, we provide an in-memory implementation of the interface, as shown at point (3.2), and configure a test user (at 3.1) in order to log in to the system.

As we may notice in the preceding code, the overall configuration of Spring Security is similar to what we have seen previously. That means that migrating to such a configuration does not take much time.

Support for reactive in the new generation of Spring Security allows us to build a highly protected web application with minimal effort spent on the infrastructure's setup.

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

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