我如何返回401的一些URL时,使用春季安全oAuth2登录



我正在尝试使用Spring Security oAuth2保护我的应用程序。如果用户没有登录,是否有一种方法可以为某些URL返回401,而其他页面则转到登录页面。

例如,/ui/*返回登录表单,/api/*返回401

我尝试使用两个SecurityWebFilterChain,但没有成功。

我的spring安全版本有些不同,代码如下:

http.exceptionHandling().authenticationEntryPoint(new DelegatingServerAuthenticationEntryPoint(
new DelegatingServerAuthenticationEntryPoint.DelegateEntry(
ServerWebExchangeMatchers.pathMatchers("/ui/**"),
new RedirectServerAuthenticationEntryPoint("/login")
),
new DelegatingServerAuthenticationEntryPoint.DelegateEntry(
ServerWebExchangeMatchers.pathMatchers("/api/**"),
new HttpStatusServerEntryPoint(HttpStatus.UNAUTHORIZED)
))
);

您可以配置Spring Security使用自定义AuthenticationEntryPoint,如下所示:

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

这样,Spring Security将基于RequestMatcher#matches方法拾取AuthenticationEntryPoint

最新更新