我正在编写一个带有 Spring Security 的 Spring Boot 应用程序,它有一个 REST API 和一个 Web 界面。当用户未通过身份验证时,REST API 应仅返回 function setCsvToDownload(csv_file_path) {
var temp_download_link = document.createElement("a");
temp_download_link.download = csv_file_path;
temp_download_link.href = csv_file_path;
temp_download_link.click();
}
,而 Web 界面应重定向到登录页面。使用以下配置,这适用于以下情况:
如果请求包含授权标头但没有 401 Unauthorized
令牌,我无法做到的是具有相同的行为。在这种情况下,请求总是被重定向到登录页面,无论是 API 请求还是“网络”请求。到目前为止,我发现的唯一防止这种情况的方法是将 bearer
设置为 true,但这样就不会再将请求重定向到登录页面...
还有其他配置可以尝试吗?谢谢!
bearer-only
答案 0 :(得分:5)
Spring Security 的 BearerTokenAuthenticationFilter
(以及相应的 BearerTokenAuthenticationEntryPoint
)在有不记名令牌时被触发。
如果你想在其他时间调用BearerTokenAuthenticationEntryPoint
,你可以用全局异常处理程序注册它:
http
.exceptionHandling((exceptions) -> exceptions
.authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
);
这将告诉 Spring Security 将 BearerTokenAuthenticationEntryPoint
用于任何 AuthenticationException
。
或者,如果您支持多种身份验证机制(例如表单登录),那么您可以指定一个 RequestMatcher
:
http
.exceptionHandling((exceptions) -> exceptions
.defaultAuthenticationEntryPointFor(
new BearerTokenAuthenticationEntryPoint(),
(request) -> request.getHeader("Authorization") != null
)
);
也就是说,通过使用没有 Keycloak 包装器的 Spring Security,您可能会取得更大的成功。这样做的原因是 Spring Security 现在附带 its own bearer token support。