spring-boot - Spring Security:oauth2Login 仅在某些路径上重定向
问题描述
我已将 Spring Security 配置为对我的网站进行身份验证,这样所有路径都会自动重定向到 OAuth2 授权 URL(使用.oauth2Login()
)。但是,我希望对 API(即/api/**
)的未经身份验证的请求返回401 Unauthorized
而不是被重定向。我不知道该怎么做。任何帮助将非常感激。
这是我当前的配置:
http
.authorizeRequests()
.antMatchers("/api/auth/oauth2/callback").permitAll()
.anyRequest().authenticated()
.oauth2Login()
.authorizationEndpoint()
.baseUri(this.oauth2AuthorizationRedirectBaseUri);
http.logout()
.logoutUrl("/auth/logout")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID");
解决方案
您可以为 /API/** 定义自定义身份验证入口点并将 t 添加到您的配置中:
@Component
public class CustomAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("developers");
super.afterPropertiesSet();
}
}
在您的 Http 安全配置中添加:
http.
...
.exceptionHandling()
.defaultAuthenticationEntryPointFor(
new CustomAuthenticationEntryPoint(),
new AntPathRequestMatcher("/api/**"))
推荐阅读
- scala - 如何在 Scala 中创建文件输入流以从 URL 下载视频?
- c++ - 'Microsoft::WRL::FtmBase' 类具有虚函数,但析构函数不是虚函数
- build - Xcode 9.4.1 无法构建模块并重新定义模块 - 无法构建
- spring-boot - 使用 spring 和 querydsl 排序
- java - 运行一次迭代后,循环移动到代码中的错误位置
- python - 使用 hover_line_alpha 时散景线“消失”
- r - 使用 enquo 时如何测试变量类型?
- python - TensorFlow 通过 input_fn 管道输入多个参数
- json - 在 Postgres 中查询 JSON 对象数组
- vba - 使用系统用户名授予权限