Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Spring Security 5 for Reactive Applications

$
0
0

1. Introduction

In this article, we’ll explore new features of the Spring Security 5 framework for securing reactive applications. This release is aligned with Spring 5 and Spring Boot 2.

In this article, we won’t go into details about the reactive applications themselves, which is a new feature of the Spring 5 framework. Be sure to check out the article Intro to Reactor Core for more details.

2. Maven Setup

We’ll use Spring Boot starters to bootstrap our project together with all required dependencies.

The basic setup requires a parent declaration, web starter, and security starter dependencies. We’ll also need the Spring Security test framework:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.M6</version>
    <relativePath/>
</parent>

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

At the time of this writing, the latest version of Spring Security 5 is in the release candidate state. The Spring Boot library, which supports it, is in the milestone state.

So we’ll need to provide the milestone repository for Maven setup:

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

We can check out the current version of Spring Boot security starter over at Maven Central.

3. Project Setup

3.1. Bootstrapping the Reactive Application

We won’t use the standard @SpringBootApplication configuration but instead, configure a Netty-based web server. Netty is an asynchronous NIO-based framework which is a good foundation for reactive applications.

The @EnableWebFlux annotation enables the standard Spring Web Reactive configuration for the application:

@ComponentScan(basePackages = {"com.baeldung.security"})
@EnableWebFlux
public class SpringSecurity5Application {

    public static void main(String[] args) {
        try (AnnotationConfigApplicationContext context 
         = new AnnotationConfigApplicationContext(
            SpringSecurity5Application.class)) {
 
            context.getBean(NettyContext.class).onClose().block();
        }
    }

Here, we create a new application context and wait for Netty to shut down by calling .onClose().block() chain on the Netty context.

After Netty is shut down, the context will be automatically closed using the try-with-resources block.

We’ll also need to create a Netty-based HTTP server, a handler for the HTTP requests, and the adapter between the server and the handler:

@Bean
public NettyContext nettyContext(ApplicationContext context) {
    HttpHandler handler = WebHttpHandlerBuilder
      .applicationContext(context).build();
    ReactorHttpHandlerAdapter adapter 
      = new ReactorHttpHandlerAdapter(handler);
    HttpServer httpServer = HttpServer.create("localhost", 8080);
    return httpServer.newHandler(adapter).block();
}

3.2. Spring Security Configuration Class

For our basic Spring Security configuration, we’ll create a configuration class – SecurityConfig.

To enable WebFlux support in Spring Security 5, we only need to specify the @EnableWebFluxSecurity annotation:

@EnableWebFluxSecurity
public class SecurityConfig {
    // ...
}

Now we can take advantage of the class ServerHttpSecurity to build our security configuration.

This class is a new feature of Spring 5. It’s similar to HttpSecurity builder, but it’s only enabled for WebFlux applications.

The ServerHttpSecurity is already preconfigured with some sane defaults, so we could skip this configuration completely. But for starters, we’ll provide the following minimal config:

@Bean
public SecurityWebFilterChain securitygWebFilterChain(
  ServerHttpSecurity http) {
    return http.authorizeExchange()
      .anyExchange().authenticated()
      .and().build();
}

Also, we’ll need a user details service. Spring Security provides us with a convenient mock user builder and an in-memory implementation of the user details service:

@Bean
public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder()
      .username("user")
      .password("password")
      .roles("USER")
      .build();
    return new MapReactiveUserDetailsService(user);
}

Since we’re in reactive land, the user details service should also be reactive. If we check out the ReactiveUserDetailsService interface, we’ll see that its findByUsername method actually returns a Mono publisher:

public interface ReactiveUserDetailsService {

    Mono<UserDetails> findByUsername(String username);
}

Now we can run our application and observe a regular HTTP basic authentication form.

4. Styled Login Form

A small but striking improvement in Spring Security 5 is a new styled login form which uses the Bootstrap 4 CSS framework. The stylesheets in the login form link to CDN, so we’ll only see the improvement when connected to the Internet.

To use the new login form, let’s add the corresponding formLogin() builder method to the ServerHttpSecurity builder:

public SecurityWebFilterChain securitygWebFilterChain(
  ServerHttpSecurity http) {
    return http.authorizeExchange()
      .anyExchange().authenticated()
      .and().formLogin()
      .and().build();
}

If we now open the main page of the application, we’ll see that it looks much better than the default form we’re used to since previous versions of Spring Security:

 

Note that this is not a production-ready form, but it’s a good bootstrap of our application.

If we now log in and then go to the http://localhost:8080/logout URL, we’ll see the logout confirmation form, which is also styled.

5. Reactive Controller Security

To see something behind the authentication form, let’s implement a simple reactive controller that greets the user:

@RestController
public class GreetController {

    @GetMapping("/")
    public Mono<String> greet(Mono<Principal> principal) {
        return principal
          .map(Principal::getName)
          .map(name -> String.format("Hello, %s", name));
    }

}

After logging in, we’ll see the greeting. Let’s add another reactive handler that would be accessible by admin only:

@GetMapping("/admin")
public Mono<String> greetAdmin(Mono<Principal> principal) {
    return principal
      .map(Principal::getName)
      .map(name -> String.format("Admin access: %s", name));
}

Now let’s create a second user with the role ADMIN: in our user details service:

UserDetails admin = User.withDefaultPasswordEncoder()
  .username("admin")
  .password("password")
  .roles("ADMIN")
  .build();

We can now add a matcher rule for the admin URL that requires the user to have the ROLE_ADMIN authority.

Note that we have to put matchers before the .anyExchange() chain call. This call applies to all other URLs which were not yet covered by other matchers:

return http.authorizeExchange()
  .pathMatchers("/admin").hasAuthority("ROLE_ADMIN")
  .anyExchange().authenticated()
  .and().formLogin()
  .and().build();

If we now log in with user or admin, we’ll see that they both observe initial greeting, as we’ve made it accessible for all authenticated users.

But only the admin user can go to the http://localhost:8080/admin URL and see her greeting.

6. Reactive Method Security

We’ve seen how we can secure the URLs, but what about methods?

To enable method-based security for reactive methods, we only need to add the @EnableReactiveMethodSecurity annotation to our SecurityConfig class:

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
    // ...
}

Now let’s create a reactive greeting service with the following content:

@Service
public class GreetService {

    public Mono<String> greet() {
        return Mono.just("Hello from service!");
    }
}

We can inject it into the controller, go to http://localhost:8080/greetService and see that it actually works:

@RestController
public class GreetController {

    private GreetService greetService

    @GetMapping("/greetService")
    public Mono<String> greetService() {
        return greetService.greet();
    }

    // standard constructors...
}

But if we now add the @PreAuthorize annotation on the service method with the ADMIN role, then the greet service URL won’t be accessible to a regular user:

@Service
public class GreetService {

@PreAuthorize("hasRole('ADMIN')")
public Mono<String> greet() {
    // ...
}

7. Mocking Users in Tests

Let’s check out how easy it is to test our reactive Spring application.

First, we’ll create a test with an injected application context:

@ContextConfiguration(classes = SpringSecurity5Application.class)
public class SecurityTest {

    @Autowired
    ApplicationContext context;

    // ...
}

Now we’ll set up a simple reactive web test client, which is a feature of the Spring 5 test framework:

@Before
public void setup() {
    this.rest = WebTestClient
      .bindToApplicationContext(this.context)
      .configureClient()
      .build();
}

This allows us to quickly check that the unauthorized user is redirected from the main page of our application to the login page:

@Test
public void whenNoCredentials_thenRedirectToLogin() {
    this.rest.get()
      .uri("/")
      .exchange()
      .expectStatus().is3xxRedirection();
}

If we now add the @MockWithUser annotation to a test method, we can provide an authenticated user for this method.

The login and password of this user would be user and password respectively, and the role is USER. This, of course, can all be configured with the @MockWithUser annotation parameters.

Now we can check that the authorized user sees the greeting:

@Test
@WithMockUser
public void whenHasCredentials_thenSeesGreeting() {
    this.rest.get()
      .uri("/")
      .exchange()
      .expectStatus().isOk()
      .expectBody(String.class).isEqualTo("Hello, user");
}

The @WithMockUser annotation is available since Spring Security 4. However, in Spring Security 5 it was also updated to cover reactive endpoints and methods.

8. Conclusion

In this tutorial, we’ve discovered new features of the upcoming Spring Security 5 release, especially in the reactive programming arena.

As always, the source code for the article is available over on GitHub.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>