在通过 Spring 安全 OAuth2 客户端成功进行匿名身份验证后重定向到特定的 URL

Redirect to a specific URL after successful anonymous auth via Spring Security OAuth2 client

我使用 Spring Security 的 OAuth2 客户端身份验证和代码授权类型来进行匿名身份验证。

内置 OAuth2AuthorizationCodeGrantFilter 在匿名主体成功验证后执行重定向。 它重定向到通过存储在 RequestCache 中的请求获得的 URL,或使用从查询参数中剥离的默认 url (oauth2/code/{registrationId})。

OAuth2AuthorizationCodeGrantFilter 的相关代码:

String redirectUrl = authorizationResponse.getRedirectUri();
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest != null) {
    redirectUrl = savedRequest.getRedirectUrl();
    this.requestCache.removeRequest(request, response);
}
this.redirectStrategy.sendRedirect(request, response, redirectUrl);

我可以利用请求缓存来存储重定向请求。但是 RequestCache 的接口不允许我为重定向指定任意 URL,只能使用现有的(不可变的)HttpServletRequest。

我需要根据某些业务逻辑重定向到特定 URL。我如何强制执行任意重定向 URL?

我根本不指定重定向 URL 就解决了这个问题。相反,我利用了 OAuth2AuthorizationCodeGrantFilter 默认使用的授权 URL。

我在路径 /authorize/oauth2/code/{providerId} 的 RestController 中注册了两个 RequestMappings,一个使用 params = "!error",第二个使用 params = "error"。由于 OAuth 过滤器对重定向请求不做任何事情(因为它从 oauth 参数中剥离),这两个映射可以用作成功和失败授权处理程序。

另一方面,我在 spring-security 中打开了一个 issue 以支持可注入 RequestCache,这将启用正确的重定向机制。该问题目前似乎已得到解决,但包含另外两个可能的解决方法。