VOOZH about

URL: https://dzone.com/articles/reactive-spring-security-for-webflux-rest-web-serv

⇱ Reactive Spring Security For WebFlux REST Web Services


Related

  1. DZone
  2. Coding
  3. Frameworks
  4. Reactive Spring Security For WebFlux REST Web Services

Reactive Spring Security For WebFlux REST Web Services

Let's take a dive into how to configure Spring Security for reactive and stateless WebFlux REST APIs. Click here to learn more.

By Aug. 14, 18 · Tutorial
Likes
Comment
Save
32.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this series of posts, we'll dive into how exactly to configure Spring Security for reactive and stateless WebFlux REST APIs. Specifically, we'll look at how to:

  1. Have Spring Security pick users from our user table, rather than its default in-memory user-store

  2. Support form-login to obtain a token, i.e. a user should be able to call POST /login with their username and password to receive a token

  3. Configure authorization at the request level, as well as method level

  4. Make the API stateless, i.e. not storing the Spring Context in the session

  5. Return a 401 Unauthorized response instead of redirecting to a login page when an unauthenticated user tries to access a restricted page or in the case of an authentication failure

  6. Configure custom token authentication (for stateless authentication using Authorization Bearer JWT/JWE tokens)

  7. Configure stuff like CSRF, CORS, log out, etc.

For code examples, we’ll refer to Spring Lemon. If you haven’t heard of Spring Lemon, you should give it a look. It’s a library encapsulating the sophisticated, non-functional code and configuration that’s needed when developing real-world RESTful web services using the Spring framework and Spring Boot.

So, let the adventure begin!

The Basics

Spring Security has documented a minimal version of configuration for WebFlux applications, which looks like the following:

@EnableWebFluxSecurity
public class HelloWebfluxSecurityConfig {

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

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


To summarize, we'll need to provide a couple of beans:

  1. ReactiveUserDetailsServiceconnecting to our user DB

  2. SecurityWebFilterChain for configuring access rules etc.

Spring Boot Autoconfiguration

Default beans similar to those above get auto-configured when using Spring Boot — as documented here. But, to meet our requirements, we, of course, need to replace those with ours.

Also, note that the @EnableWebFluxSecurityannotation isn't required in Spring Boot applications.

A Better ReactiveUserDetailsService

As you see above, we need to configure a ReactiveUserDetailsService so that Spring Security finds our users. A map-based, user details service is configured above, but in the real world, we'll need to code it to access our user store. For example, here is a minimal sample derived from Spring Lemon's user details service:

@Service
public class MyReactiveUserDetailsService implements ReactiveUserDetailsService {

 @Autowired
 private UserRepository userRepository;

 @Override
 public Mono<UserDetails> findByUsername(String username) {

 return userRepository.findByUsername(username).switchIfEmpty(Mono.defer(() -> {

 return Mono.error(new UsernameNotFoundException("User Not Found"));

 })).map(User::toUserDetails);
 }
}


The above code assumes that we have a Userdomain class, which has a toUserDetailsmethod that returns a UserDetailsobject. So, we'll need to define the User class and an implementation of UserDetails.

The User class could look something like this:

public class User {

 private String username;
 private String password;
 private Collection<String> roles;

 // Getters and setters

 public UserDetails toUserDetails() {

 // returns a UserDetails object
 }
}


The toUserDetailsmethod above should return an object that should have implemented UserDetails , which will look something like this:

public class MyUserDetails implements UserDetails {

 private String username;
 private String password;
 private Collection<String> roles;

 @Override
 public Collection<? extends GrantedAuthority> getAuthorities() {

 // return authorities derived from roles;
 }

 @Override
 public String getPassword() {

 return password;
 }

 @Override
 public String getUsername() {

 return username;
 }

 @Override
 public boolean isAccountNonExpired() {

 return true;
 }

 @Override
 public boolean isAccountNonLocked() {

 return true;
 }

 @Override
 public boolean isCredentialsNonExpired() {

 return true;
 }

 @Override
 public boolean isEnabled() {

 return true;
 }
}


Since this is similar to traditional Spring Security, we'll not discuss the details here.

The next step will be configuring our SecurityWebFilterChainbean, which we'll take up in the next post.

Spring Framework Spring Security REST Web Protocols Web Service Spring Boot

Published at DZone with permission of Sanjay Patel. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: