Search code examples
spring-securityspring-webfluxspring-security-oauth2

How can I return 401 for some URL when using spring security oAuth2 login


I'm trying to secure my application with Spring Security oAuth2. Is there a way to return 401 for some URL while other pages go to the login page if a user is not logged in.

For example, return login form for /ui/*, and return 401 for /api/*

I tried to use two SecurityWebFilterChain, but didn't success.


Solution

  • You can configure Spring Security to use a custom AuthenticationEntryPoint, something like:

    http
        // ... your configuration
        .exceptionHandling((ex) -> ex
            .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), new AntPathRequestMatcher("/ui/**"))
            .defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED), new AntPathRequestMatcher("/api/**"))
        );
    

    This way Spring Security will pick up the AuthenticationEntryPoint based on the RequestMatcher#matches method