DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  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.

Sanjay Patel user avatar by
Sanjay Patel
CORE ·
Aug. 14, 18 · Tutorial
Like (1)
Save
Tweet
Share
29.21K 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. A ReactiveUserDetailsServiceconnecting to our user DB

  2. A 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 @EnableWebFluxSecurity annotation 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 User domain class, which has a toUserDetails method that returns a UserDetails object. 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 toUserDetails method 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 SecurityWebFilterChain bean, 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.

Popular on DZone

  • A First Look at Neon
  • Kubernetes-Native Development With Quarkus and Eclipse JKube
  • Introduction to NoSQL Database
  • ClickHouse: A Blazingly Fast DBMS With Full SQL Join Support

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: