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