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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

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

Trending

  • The Rise of the Intelligent AI Agent: Revolutionizing Database Management With Agentic DBA
  • Scrum Smarter, Not Louder: AI Prompts Every Developer Should Steal
  • Continuous Quality Engineering: The Convergence of CI/CD, Chaos Testing, and AI-Powered Test Orchestration
  • Microservice Madness: Debunking Myths and Exposing Pitfalls
  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 
Sanjay Patel user avatar
Sanjay Patel
DZone Core CORE ·
Aug. 14, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
31.5K 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.

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.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: