Spring Security 5

Author: Shazin Sadakath


Spring Security 5 is released and it now supports Spring 5 which means it supports the reactive programming capabilities of Spring Web Flux. In this post I wanted to show how to configure a Spring Security 5 Application which runs on Spring Boot 2.

The configuration has changed a bit from previous WebSecurityConfigurerAdapter based configuration to something like the following;

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain springWebFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeExchange()
                .pathMatchers("/user").authenticated()
                .anyExchange().permitAll()
                .and()
                .build();
    }

    @Bean
    public UserDetailsRepository userDetailsRepository() {
        UserDetails userDetails = User.withUsername("shazin").password("sha123").roles("USER").build();
        return new MapUserDetailsRepository(userDetails);
    }
}

@EnableWebFluxSecurity annotation is responsible for enabling the Web Flux Security support in the Spring Boot Application.

The userDetailsRepository bean is responsible for the Authorization and loads the user credentials and springWebFilterChain bean is responsible for the Authentication where it can be customized to restrict access.

The following controller can be used to test the Reactive Authorization capabilities of the Spring Security 5.

@RestController
public class IndexController {

    @GetMapping("/greet")
    public Mono greet(Mono principal) {
        return principal.map(auth -> "Hello, "+auth.getName());
    }

    @GetMapping("/user")
    public Mono user(Mono principal) {
        return principal;
    }
}

The complete source code is available in github

References

  1. https://docs.spring.io/spring-security/site/docs/5.0.0.RELEASE/reference/htmlsingle/


Tags: SpringSecurity5 SpringBoot2 Reactive
Views: 918
Register for more exciting articles

Comments

Please login or register to post a comment.


There are currently no comments.