1
0
mirror of synced 2026-08-05 17:57:15 +00:00

Add OAuth2 Client HandlerMethodArgumentResolver

Fixes gh-4651
This commit is contained in:
Joe Grandja
2018-03-08 06:09:50 -05:00
parent 982fc360b2
commit 526e0fdd4f
16 changed files with 850 additions and 71 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2018 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.
@@ -73,7 +73,8 @@ import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({ WebSecurityConfiguration.class,
SpringWebMvcImportSelector.class })
SpringWebMvcImportSelector.class,
OAuth2ImportSelector.class })
@EnableGlobalAuthentication
@Configuration
public @interface EnableWebSecurity {
@@ -83,4 +84,4 @@ public @interface EnableWebSecurity {
* @return if true, enables debug support with Spring Security
*/
boolean debug() default false;
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2002-2018 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2ClientArgumentResolver;
import org.springframework.util.ClassUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* {@link Configuration} for OAuth 2.0 Client support.
*
* <p>
* This {@code Configuration} is conditionally imported by {@link OAuth2ImportSelector}
* when the {@code spring-security-oauth2-client} module is present on the classpath.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2ImportSelector
*/
@Import(OAuth2ClientConfiguration.OAuth2ClientWebMvcImportSelector.class)
final class OAuth2ClientConfiguration {
static class OAuth2ClientWebMvcImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
boolean webmvcPresent = ClassUtils.isPresent(
"org.springframework.web.servlet.DispatcherServlet", getClass().getClassLoader());
return webmvcPresent ?
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration.OAuth2ClientWebMvcSecurityConfiguration" } :
new String[] {};
}
}
@Configuration
static class OAuth2ClientWebMvcSecurityConfiguration implements WebMvcConfigurer {
@Autowired(required = false)
private ClientRegistrationRepository clientRegistrationRepository;
@Autowired(required = false)
private OAuth2AuthorizedClientService authorizedClientService;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
if (this.clientRegistrationRepository != null && this.authorizedClientService != null) {
OAuth2ClientArgumentResolver oauth2ClientArgumentResolver = new OAuth2ClientArgumentResolver(
this.clientRegistrationRepository, this.authorizedClientService);
argumentResolvers.add(oauth2ClientArgumentResolver);
}
}
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2002-2018 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
/**
* Used by {@link EnableWebSecurity} to conditionally import {@link OAuth2ClientConfiguration}
* when the {@code spring-security-oauth2-client} module is present on the classpath.
* @author Joe Grandja
* @since 5.1
* @see OAuth2ClientConfiguration
*/
final class OAuth2ImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
boolean oauth2ClientPresent = ClassUtils.isPresent(
"org.springframework.security.oauth2.client.registration.ClientRegistration", getClass().getClassLoader());
return oauth2ClientPresent ?
new String[] { "org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration" } :
new String[] {};
}
}
@@ -28,6 +28,7 @@ import org.springframework.security.oauth2.client.web.AuthorizationRequestReposi
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationCodeGrantFilter;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.util.Assert;
/**
@@ -277,6 +278,10 @@ public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>> exte
authorizationRequestFilter.setAuthorizationRequestRepository(
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository);
}
RequestCache requestCache = builder.getSharedObject(RequestCache.class);
if (requestCache != null) {
authorizationRequestFilter.setRequestCache(requestCache);
}
builder.addFilter(this.postProcess(authorizationRequestFilter));
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
@@ -52,6 +52,7 @@ import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
@@ -447,6 +448,10 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
authorizationRequestFilter.setAuthorizationRequestRepository(
this.authorizationEndpointConfig.authorizationRequestRepository);
}
RequestCache requestCache = http.getSharedObject(RequestCache.class);
if (requestCache != null) {
authorizationRequestFilter.setRequestCache(requestCache);
}
http.addFilter(this.postProcess(authorizationRequestFilter));
OAuth2LoginAuthenticationFilter authenticationFilter = this.getAuthenticationFilter();
@@ -0,0 +1,136 @@
/*
* Copyright 2002-2018 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configuration;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.annotation.OAuth2Client;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link OAuth2ClientConfiguration}.
*
* @author Joe Grandja
*/
public class OAuth2ClientConfigurationTests {
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
private MockMvc mockMvc;
@Test
public void requestWhenAuthorizedClientFoundThenOAuth2ClientArgumentsResolved() throws Exception {
String clientRegistrationId = "client1";
String principalName = "user1";
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(clientRegistrationId)
.clientId("client-id")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUriTemplate("{baseUrl}/client1")
.scope("scope1", "scope2")
.authorizationUri("https://provider.com/oauth2/auth")
.tokenUri("https://provider.com/oauth2/token")
.clientName("Client 1")
.build();
when(clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).thenReturn(clientRegistration);
OAuth2AuthorizedClientService authorizedClientService = mock(OAuth2AuthorizedClientService.class);
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
when(authorizedClientService.loadAuthorizedClient(clientRegistrationId, principalName)).thenReturn(authorizedClient);
OAuth2AccessToken accessToken = mock(OAuth2AccessToken.class);
when(authorizedClient.getAccessToken()).thenReturn(accessToken);
OAuth2ClientArgumentResolverConfig.CLIENT_REGISTRATION_REPOSITORY = clientRegistrationRepository;
OAuth2ClientArgumentResolverConfig.AUTHORIZED_CLIENT_SERVICE = authorizedClientService;
this.spring.register(OAuth2ClientArgumentResolverConfig.class).autowire();
this.mockMvc.perform(get("/access-token").with(user(principalName)))
.andExpect(status().isOk())
.andExpect(content().string("resolved"));
this.mockMvc.perform(get("/authorized-client").with(user(principalName)))
.andExpect(status().isOk())
.andExpect(content().string("resolved"));
this.mockMvc.perform(get("/client-registration").with(user(principalName)))
.andExpect(status().isOk())
.andExpect(content().string("resolved"));
}
@EnableWebMvc
@EnableWebSecurity
static class OAuth2ClientArgumentResolverConfig extends WebSecurityConfigurerAdapter {
static ClientRegistrationRepository CLIENT_REGISTRATION_REPOSITORY;
static OAuth2AuthorizedClientService AUTHORIZED_CLIENT_SERVICE;
@Override
protected void configure(HttpSecurity http) throws Exception {
}
@RestController
public class Controller {
@GetMapping("/access-token")
public String accessToken(@OAuth2Client("client1") OAuth2AccessToken accessToken) {
return accessToken != null ? "resolved" : "not-resolved";
}
@GetMapping("/authorized-client")
public String authorizedClient(@OAuth2Client("client1") OAuth2AuthorizedClient authorizedClient) {
return authorizedClient != null ? "resolved" : "not-resolved";
}
@GetMapping("/client-registration")
public String clientRegistration(@OAuth2Client("client1") ClientRegistration clientRegistration) {
return clientRegistration != null ? "resolved" : "not-resolved";
}
}
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return CLIENT_REGISTRATION_REPOSITORY;
}
@Bean
public OAuth2AuthorizedClientService authorizedClientService() {
return AUTHORIZED_CLIENT_SERVICE;
}
}
}
@@ -19,6 +19,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
@@ -29,6 +30,7 @@ import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.annotation.OAuth2Client;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
@@ -42,16 +44,21 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
@@ -69,6 +76,8 @@ public class OAuth2ClientConfigurerTests {
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private static RequestCache requestCache;
@Rule
public final SpringTestRule spring = new SpringTestRule();
@@ -101,6 +110,7 @@ public class OAuth2ClientConfigurerTests {
.build();
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
when(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class))).thenReturn(accessTokenResponse);
requestCache = mock(RequestCache.class);
}
@Test
@@ -151,7 +161,20 @@ public class OAuth2ClientConfigurerTests {
assertThat(authorizedClient).isNotNull();
}
@Test
public void configureWhenRequestCacheProvidedAndClientAuthorizationRequiredExceptionThrownThenRequestCacheUsed() throws Exception {
this.spring.register(OAuth2ClientConfig.class).autowire();
MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1")))
.andExpect(status().is3xxRedirection())
.andReturn();
assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?response_type=code&client_id=client-1&scope=user&state=.{15,}&redirect_uri=http://localhost/client-1");
verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@EnableWebSecurity
@EnableWebMvc
static class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
@@ -159,13 +182,32 @@ public class OAuth2ClientConfigurerTests {
.authorizeRequests()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(requestCache)
.and()
.oauth2()
.client()
.clientRegistrationRepository(clientRegistrationRepository)
.authorizedClientService(authorizedClientService)
.authorizationCodeGrant()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient);
}
@Bean
public ClientRegistrationRepository clientRegistrationRepository() {
return clientRegistrationRepository;
}
@Bean
public OAuth2AuthorizedClientService authorizedClientService() {
return authorizedClientService;
}
@RestController
public class ResourceController {
@GetMapping("/resource1")
public String resource1(@OAuth2Client("registration-1") OAuth2AuthorizedClient authorizedClient) {
return "resource1";
}
}
}
}