Skip to content

Add ServerRequestCache setter in OAuth2AuthorizationCodeGrantWebFilter #8587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,7 @@
* @author Rafiullah Hamedy
* @author Eddú Meléndez
* @author Joe Grandja
* @author Parikshit Dutta
* @since 5.0
*/
public class ServerHttpSecurity {
Expand Down Expand Up @@ -1511,10 +1512,17 @@ protected void configure(ServerHttpSecurity http) {
OAuth2AuthorizationCodeGrantWebFilter codeGrantWebFilter = new OAuth2AuthorizationCodeGrantWebFilter(
authenticationManager, authenticationConverter, authorizedClientRepository);
codeGrantWebFilter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
if (http.requestCache != null) {
codeGrantWebFilter.setRequestCache(http.requestCache.requestCache);
}

OAuth2AuthorizationRequestRedirectWebFilter oauthRedirectFilter = new OAuth2AuthorizationRequestRedirectWebFilter(
clientRegistrationRepository);
oauthRedirectFilter.setAuthorizationRequestRepository(getAuthorizationRequestRepository());
if (http.requestCache != null) {
oauthRedirectFilter.setRequestCache(http.requestCache.requestCache);
}

http.addFilterAt(codeGrantWebFilter, SecurityWebFiltersOrder.OAUTH2_AUTHORIZATION_CODE);
http.addFilterAt(oauthRedirectFilter, SecurityWebFiltersOrder.HTTP_BASIC);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,8 @@

package org.springframework.security.config.web.server;

import java.net.URI;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -48,6 +50,7 @@
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -62,6 +65,7 @@

/**
* @author Rob Winch
* @author Parikshit Dutta
* @since 5.1
*/
@RunWith(SpringRunner.class)
Expand Down Expand Up @@ -147,6 +151,8 @@ public void oauth2ClientWhenCustomObjectsThenUsed() {
ReactiveAuthenticationManager manager = config.manager;
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = config.authorizationRequestRepository;

ServerRequestCache requestCache = config.requestCache;

OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.redirectUri("/authorize/oauth2/code/registration-id")
.build();
Expand All @@ -163,6 +169,7 @@ public void oauth2ClientWhenCustomObjectsThenUsed() {
when(authorizationRequestRepository.loadAuthorizationRequest(any())).thenReturn(Mono.just(authorizationRequest));
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(requestCache.getRedirectUri(any())).thenReturn(Mono.just(URI.create("saved-request")));

this.client.get()
.uri(uriBuilder ->
Expand All @@ -175,6 +182,7 @@ public void oauth2ClientWhenCustomObjectsThenUsed() {

verify(converter).convert(any());
verify(manager).authenticate(any());
verify(requestCache).getRedirectUri(any());
}

@EnableWebFlux
Expand All @@ -197,13 +205,17 @@ static class OAuth2ClientCustomConfig {

ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(ServerAuthorizationRequestRepository.class);

ServerRequestCache requestCache = mock(ServerRequestCache.class);

@Bean
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
http
.oauth2Client()
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository);
.authorizationRequestRepository(this.authorizationRequestRepository)
.and()
.requestCache(c -> c.requestCache(this.requestCache));
return http.build();
}
}
Expand All @@ -218,6 +230,8 @@ public void oauth2ClientWhenCustomObjectsInLambdaThenUsed() {
ReactiveAuthenticationManager manager = config.manager;
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = config.authorizationRequestRepository;

ServerRequestCache requestCache = config.requestCache;

OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.redirectUri("/authorize/oauth2/code/registration-id")
.build();
Expand All @@ -234,6 +248,7 @@ public void oauth2ClientWhenCustomObjectsInLambdaThenUsed() {
when(authorizationRequestRepository.loadAuthorizationRequest(any())).thenReturn(Mono.just(authorizationRequest));
when(converter.convert(any())).thenReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
when(manager.authenticate(any())).thenReturn(Mono.just(result));
when(requestCache.getRedirectUri(any())).thenReturn(Mono.just(URI.create("saved-request")));

this.client.get()
.uri(uriBuilder ->
Expand All @@ -246,6 +261,7 @@ public void oauth2ClientWhenCustomObjectsInLambdaThenUsed() {

verify(converter).convert(any());
verify(manager).authenticate(any());
verify(requestCache).getRedirectUri(any());
}

@Configuration
Expand All @@ -256,6 +272,8 @@ static class OAuth2ClientInLambdaCustomConfig {

ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(ServerAuthorizationRequestRepository.class);

ServerRequestCache requestCache = mock(ServerRequestCache.class);

@Bean
public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
http
Expand All @@ -264,6 +282,8 @@ public SecurityWebFilterChain springSecurityFilter(ServerHttpSecurity http) {
.authenticationConverter(this.authenticationConverter)
.authenticationManager(this.manager)
.authorizationRequestRepository(this.authorizationRequestRepository)
.and()
.requestCache(c -> c.requestCache(this.requestCache))
);
return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
Expand Down Expand Up @@ -80,6 +81,7 @@
*
* @author Rob Winch
* @author Joe Grandja
* @author Parikshit Dutta
* @since 5.1
* @see OAuth2AuthorizationCodeAuthenticationToken
* @see org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeReactiveAuthenticationManager
Expand All @@ -101,6 +103,8 @@ public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository =
new WebSessionOAuth2ServerAuthorizationRequestRepository();

private ServerRequestCache requestCache;

private ServerAuthenticationSuccessHandler authenticationSuccessHandler;

private ServerAuthenticationConverter authenticationConverter;
Expand Down Expand Up @@ -169,6 +173,23 @@ private void updateDefaultAuthenticationConverter() {
}
}

/**
* Sets the {@link ServerRequestCache} used for loading a previously saved request (if available)
* and replaying it after completing the processing of the OAuth 2.0 Authorization Response.
*
* @since 5.4
* @param requestCache the cache used for loading a previously saved request (if available)
*/
public final void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
updateDefaultAuthenticationSuccessHandler();
}

private void updateDefaultAuthenticationSuccessHandler() {
((RedirectServerAuthenticationSuccessHandler) this.authenticationSuccessHandler).setRequestCache(this.requestCache);
}

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return this.requiresAuthenticationMatcher.matches(exchange)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
Expand All @@ -31,25 +32,31 @@
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.handler.DefaultWebFilterChain;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request;

/**
* @author Rob Winch
* @author Parikshit Dutta
* @since 5.1
*/
@RunWith(MockitoJUnitRunner.class)
Expand Down Expand Up @@ -99,6 +106,12 @@ public void constructorWhenAuthorizedClientRepositoryNullThenIllegalArgumentExce
.isInstanceOf(IllegalArgumentException.class);
}

@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatCode(() -> this.filter.setRequestCache(null))
.isInstanceOf(IllegalArgumentException.class);
}

@Test
public void filterWhenNotMatchThenAuthenticationManagerNotCalled() {
MockServerWebExchange exchange = MockServerWebExchange
Expand Down Expand Up @@ -233,6 +246,40 @@ public void filterWhenAuthorizationRequestRedirectUriParametersNotMatchThenNotPr
verifyNoInteractions(this.authenticationManager);
}

@Test
public void filterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
when(this.clientRegistrationRepository.findByRegistrationId(any()))
.thenReturn(Mono.just(clientRegistration));
when(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any()))
.thenReturn(Mono.empty());
when(this.authenticationManager.authenticate(any()))
.thenReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));

MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
OAuth2AuthorizationRequest oauth2AuthorizationRequest =
createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
when(this.authorizationRequestRepository.loadAuthorizationRequest(any()))
.thenReturn(Mono.just(oauth2AuthorizationRequest));
when(this.authorizationRequestRepository.removeAuthorizationRequest(any()))
.thenReturn(Mono.just(oauth2AuthorizationRequest));

MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
DefaultWebFilterChain chain = new DefaultWebFilterChain(
e -> e.getResponse().setComplete(), Collections.emptyList());

ServerRequestCache requestCache = mock(ServerRequestCache.class);
when(requestCache.getRedirectUri(any(ServerWebExchange.class))).thenReturn(Mono.just(URI.create("/saved-request")));

this.filter.setRequestCache(requestCache);

this.filter.filter(exchange, chain).block();

verify(requestCache).getRedirectUri(exchange);
assertThat(exchange.getResponse().getHeaders().getLocation().toString()).isEqualTo("/saved-request");
}

private static OAuth2AuthorizationRequest createOAuth2AuthorizationRequest(
MockServerHttpRequest authorizationRequest, ClientRegistration registration) {
Map<String, Object> attributes = new HashMap<>();
Expand Down