Reputation: 971
I use Spring Security's OAuth2 client auth with code grant type to do anonymous authentication.
The built-in OAuth2AuthorizationCodeGrantFilter
does a redirect after a successful auth of an anonymous principal.
It redirects to a URL obtained either via a request stored in a RequestCache
, or uses the default url (oauth2/code/{registrationId}
) stripped from query params.
The OAuth2AuthorizationCodeGrantFilter
's code in question:
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);
I can leverage the request cache to store a request for the redirection. But the RequestCache
's interface doesn't let me specify arbitrary URL for the redirection, only use an existing (immutable) HttpServletRequest.
I need to do a redirect to a specific URL based on some business logic. How can I force an arbitrary redirect URL?
Upvotes: 0
Views: 539
Reputation: 971
I have solved this by not specifying the redirect URL at all. Instead, I leveraged the authorization URL that the OAuth2AuthorizationCodeGrantFilter
uses by default.
I registered two RequestMappings in a RestController at the path /authorize/oauth2/code/{providerId}
, one with params = "!error"
and a second with params = "error"
. Since the OAuth filters do nothing with the redirect request (since it is stripped from oauth params), these two mappings can be used as a Success and Failure authorization handlers.
On the other hand, I've opened an issue in spring-security for supporting injectable RequestCache
, that would enable proper proper redirection mechanism. The issue seems to be worked on right now, but contains two other possible workarounds.
Upvotes: 2