mirror of
https://github.com/spring-projects/spring-security.git
synced 2025-05-31 09:12:14 +00:00
Add OAuth2 Client HandlerMethodArgumentResolver
Fixes gh-4651
This commit is contained in:
parent
982fc360b2
commit
526e0fdd4f
@ -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");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with 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 })
|
@Target(value = { java.lang.annotation.ElementType.TYPE })
|
||||||
@Documented
|
@Documented
|
||||||
@Import({ WebSecurityConfiguration.class,
|
@Import({ WebSecurityConfiguration.class,
|
||||||
SpringWebMvcImportSelector.class })
|
SpringWebMvcImportSelector.class,
|
||||||
|
OAuth2ImportSelector.class })
|
||||||
@EnableGlobalAuthentication
|
@EnableGlobalAuthentication
|
||||||
@Configuration
|
@Configuration
|
||||||
public @interface EnableWebSecurity {
|
public @interface EnableWebSecurity {
|
||||||
@ -83,4 +84,4 @@ public @interface EnableWebSecurity {
|
|||||||
* @return if true, enables debug support with Spring Security
|
* @return if true, enables debug support with Spring Security
|
||||||
*/
|
*/
|
||||||
boolean debug() default false;
|
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.OAuth2AuthorizationCodeGrantFilter;
|
||||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
|
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
|
import org.springframework.security.web.savedrequest.RequestCache;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -277,6 +278,10 @@ public final class OAuth2ClientConfigurer<B extends HttpSecurityBuilder<B>> exte
|
|||||||
authorizationRequestFilter.setAuthorizationRequestRepository(
|
authorizationRequestFilter.setAuthorizationRequestRepository(
|
||||||
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository);
|
authorizationCodeGrantConfigurer.authorizationEndpointConfig.authorizationRequestRepository);
|
||||||
}
|
}
|
||||||
|
RequestCache requestCache = builder.getSharedObject(RequestCache.class);
|
||||||
|
if (requestCache != null) {
|
||||||
|
authorizationRequestFilter.setRequestCache(requestCache);
|
||||||
|
}
|
||||||
builder.addFilter(this.postProcess(authorizationRequestFilter));
|
builder.addFilter(this.postProcess(authorizationRequestFilter));
|
||||||
|
|
||||||
AuthenticationManager authenticationManager = builder.getSharedObject(AuthenticationManager.class);
|
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.oidc.user.OidcUser;
|
||||||
import org.springframework.security.oauth2.core.user.OAuth2User;
|
import org.springframework.security.oauth2.core.user.OAuth2User;
|
||||||
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;
|
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.AntPathRequestMatcher;
|
||||||
import org.springframework.security.web.util.matcher.RequestMatcher;
|
import org.springframework.security.web.util.matcher.RequestMatcher;
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
@ -447,6 +448,10 @@ public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> exten
|
|||||||
authorizationRequestFilter.setAuthorizationRequestRepository(
|
authorizationRequestFilter.setAuthorizationRequestRepository(
|
||||||
this.authorizationEndpointConfig.authorizationRequestRepository);
|
this.authorizationEndpointConfig.authorizationRequestRepository);
|
||||||
}
|
}
|
||||||
|
RequestCache requestCache = http.getSharedObject(RequestCache.class);
|
||||||
|
if (requestCache != null) {
|
||||||
|
authorizationRequestFilter.setRequestCache(requestCache);
|
||||||
|
}
|
||||||
http.addFilter(this.postProcess(authorizationRequestFilter));
|
http.addFilter(this.postProcess(authorizationRequestFilter));
|
||||||
|
|
||||||
OAuth2LoginAuthenticationFilter authenticationFilter = this.getAuthenticationFilter();
|
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.Rule;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.mock.web.MockHttpServletRequest;
|
import org.springframework.mock.web.MockHttpServletRequest;
|
||||||
import org.springframework.mock.web.MockHttpServletResponse;
|
import org.springframework.mock.web.MockHttpServletResponse;
|
||||||
import org.springframework.mock.web.MockHttpSession;
|
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.InMemoryOAuth2AuthorizedClientService;
|
||||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
||||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
|
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.OAuth2AccessTokenResponseClient;
|
||||||
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
|
||||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
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.OAuth2AccessTokenResponse;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
|
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.MockMvc;
|
||||||
import org.springframework.test.web.servlet.MvcResult;
|
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.HashMap;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.Mockito.mock;
|
import static org.mockito.Mockito.*;
|
||||||
import static org.mockito.Mockito.when;
|
|
||||||
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
|
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.request.MockMvcRequestBuilders.get;
|
||||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||||
@ -69,6 +76,8 @@ public class OAuth2ClientConfigurerTests {
|
|||||||
|
|
||||||
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
|
private static OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
|
||||||
|
|
||||||
|
private static RequestCache requestCache;
|
||||||
|
|
||||||
@Rule
|
@Rule
|
||||||
public final SpringTestRule spring = new SpringTestRule();
|
public final SpringTestRule spring = new SpringTestRule();
|
||||||
|
|
||||||
@ -101,6 +110,7 @@ public class OAuth2ClientConfigurerTests {
|
|||||||
.build();
|
.build();
|
||||||
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
|
||||||
when(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class))).thenReturn(accessTokenResponse);
|
when(accessTokenResponseClient.getTokenResponse(any(OAuth2AuthorizationCodeGrantRequest.class))).thenReturn(accessTokenResponse);
|
||||||
|
requestCache = mock(RequestCache.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -151,7 +161,20 @@ public class OAuth2ClientConfigurerTests {
|
|||||||
assertThat(authorizedClient).isNotNull();
|
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
|
@EnableWebSecurity
|
||||||
|
@EnableWebMvc
|
||||||
static class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {
|
static class OAuth2ClientConfig extends WebSecurityConfigurerAdapter {
|
||||||
@Override
|
@Override
|
||||||
protected void configure(HttpSecurity http) throws Exception {
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
@ -159,13 +182,32 @@ public class OAuth2ClientConfigurerTests {
|
|||||||
.authorizeRequests()
|
.authorizeRequests()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
.and()
|
.and()
|
||||||
|
.requestCache()
|
||||||
|
.requestCache(requestCache)
|
||||||
|
.and()
|
||||||
.oauth2()
|
.oauth2()
|
||||||
.client()
|
.client()
|
||||||
.clientRegistrationRepository(clientRegistrationRepository)
|
|
||||||
.authorizedClientService(authorizedClientService)
|
|
||||||
.authorizationCodeGrant()
|
.authorizationCodeGrant()
|
||||||
.tokenEndpoint()
|
.tokenEndpoint()
|
||||||
.accessTokenResponseClient(accessTokenResponseClient);
|
.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";
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -673,7 +673,7 @@ The following listing shows an example:
|
|||||||
[source,java]
|
[source,java]
|
||||||
----
|
----
|
||||||
@Controller
|
@Controller
|
||||||
public class MainController {
|
public class OAuth2LoginController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private ClientRegistrationRepository clientRegistrationRepository;
|
private ClientRegistrationRepository clientRegistrationRepository;
|
||||||
@ -953,7 +953,7 @@ The following listing shows an example:
|
|||||||
[source,java]
|
[source,java]
|
||||||
----
|
----
|
||||||
@Controller
|
@Controller
|
||||||
public class MainController {
|
public class OAuth2LoginController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private OAuth2AuthorizedClientService authorizedClientService;
|
private OAuth2AuthorizedClientService authorizedClientService;
|
||||||
|
@ -0,0 +1,85 @@
|
|||||||
|
/*
|
||||||
|
* 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.oauth2.client.annotation;
|
||||||
|
|
||||||
|
import org.springframework.core.annotation.AliasFor;
|
||||||
|
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
||||||
|
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||||
|
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2ClientArgumentResolver;
|
||||||
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
|
|
||||||
|
import java.lang.annotation.Documented;
|
||||||
|
import java.lang.annotation.ElementType;
|
||||||
|
import java.lang.annotation.Retention;
|
||||||
|
import java.lang.annotation.RetentionPolicy;
|
||||||
|
import java.lang.annotation.Target;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This annotation may be used to resolve a method parameter into an argument value
|
||||||
|
* for the following types: {@link ClientRegistration}, {@link OAuth2AuthorizedClient}
|
||||||
|
* and {@link OAuth2AccessToken}.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* For example:
|
||||||
|
* <pre>
|
||||||
|
* @Controller
|
||||||
|
* public class MyController {
|
||||||
|
* @GetMapping("/client-registration")
|
||||||
|
* public String clientRegistration(@OAuth2Client("login-client") ClientRegistration clientRegistration) {
|
||||||
|
* // do something with clientRegistration
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @GetMapping("/authorized-client")
|
||||||
|
* public String authorizedClient(@OAuth2Client("login-client") OAuth2AuthorizedClient authorizedClient) {
|
||||||
|
* // do something with authorizedClient
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @GetMapping("/access-token")
|
||||||
|
* public String accessToken(@OAuth2Client("login-client") OAuth2AccessToken accessToken) {
|
||||||
|
* // do something with accessToken
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 5.1
|
||||||
|
* @see OAuth2ClientArgumentResolver
|
||||||
|
*/
|
||||||
|
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
|
||||||
|
@Retention(RetentionPolicy.RUNTIME)
|
||||||
|
@Documented
|
||||||
|
public @interface OAuth2Client {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the client registration identifier.
|
||||||
|
*
|
||||||
|
* @return the client registration identifier
|
||||||
|
*/
|
||||||
|
@AliasFor("value")
|
||||||
|
String registrationId() default "";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The default attribute for this annotation.
|
||||||
|
* This is an alias for {@link #registrationId()}.
|
||||||
|
* For example, {@code @OAuth2Client("login-client")} is equivalent to
|
||||||
|
* {@code @OAuth2Client(registrationId="login-client")}.
|
||||||
|
*
|
||||||
|
* @return the client registration identifier
|
||||||
|
*/
|
||||||
|
@AliasFor("registrationId")
|
||||||
|
String value() default "";
|
||||||
|
|
||||||
|
}
|
@ -93,8 +93,8 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
|||||||
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
|
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
|
||||||
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository =
|
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository =
|
||||||
new HttpSessionOAuth2AuthorizationRequestRepository();
|
new HttpSessionOAuth2AuthorizationRequestRepository();
|
||||||
|
private RequestCache requestCache = new HttpSessionRequestCache();
|
||||||
private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
|
private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
|
||||||
private final RequestCache requestCache = new HttpSessionRequestCache();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided parameters.
|
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided parameters.
|
||||||
@ -131,6 +131,17 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
|||||||
this.authorizationRequestRepository = authorizationRequestRepository;
|
this.authorizationRequestRepository = authorizationRequestRepository;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the {@link RequestCache} used for storing the current request
|
||||||
|
* before redirecting the OAuth 2.0 Authorization Request.
|
||||||
|
*
|
||||||
|
* @param requestCache the cache used for storing the current request
|
||||||
|
*/
|
||||||
|
public final void setRequestCache(RequestCache requestCache) {
|
||||||
|
Assert.notNull(requestCache, "requestCache cannot be null");
|
||||||
|
this.requestCache = requestCache;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||||
throws ServletException, IOException {
|
throws ServletException, IOException {
|
||||||
@ -212,8 +223,9 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
|||||||
} else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) {
|
} else if (AuthorizationGrantType.IMPLICIT.equals(clientRegistration.getAuthorizationGrantType())) {
|
||||||
builder = OAuth2AuthorizationRequest.implicit();
|
builder = OAuth2AuthorizationRequest.implicit();
|
||||||
} else {
|
} else {
|
||||||
throw new IllegalArgumentException("Invalid Authorization Grant Type for Client Registration (" +
|
throw new IllegalArgumentException("Invalid Authorization Grant Type (" +
|
||||||
clientRegistration.getRegistrationId() + "): " + clientRegistration.getAuthorizationGrantType());
|
clientRegistration.getAuthorizationGrantType().getValue() +
|
||||||
|
") for Client Registration with Id: " + clientRegistration.getRegistrationId());
|
||||||
}
|
}
|
||||||
OAuth2AuthorizationRequest authorizationRequest = builder
|
OAuth2AuthorizationRequest authorizationRequest = builder
|
||||||
.clientId(clientRegistration.getClientId())
|
.clientId(clientRegistration.getClientId())
|
||||||
@ -235,10 +247,10 @@ public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilt
|
|||||||
private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response,
|
private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response,
|
||||||
Exception failed) throws IOException, ServletException {
|
Exception failed) throws IOException, ServletException {
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
if (logger.isErrorEnabled()) {
|
||||||
logger.debug("Authorization Request failed: " + failed.toString(), failed);
|
logger.error("Authorization Request failed: " + failed.toString(), failed);
|
||||||
}
|
}
|
||||||
response.sendError(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase());
|
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String expandRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
|
private String expandRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
|
||||||
|
@ -0,0 +1,144 @@
|
|||||||
|
/*
|
||||||
|
* 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.oauth2.client.web.method.annotation;
|
||||||
|
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.lang.NonNull;
|
||||||
|
import org.springframework.lang.Nullable;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
|
||||||
|
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.authentication.OAuth2AuthenticationToken;
|
||||||
|
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||||
|
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||||
|
import org.springframework.security.oauth2.core.OAuth2AccessToken;
|
||||||
|
import org.springframework.util.Assert;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
import org.springframework.web.bind.support.WebDataBinderFactory;
|
||||||
|
import org.springframework.web.context.request.NativeWebRequest;
|
||||||
|
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
|
||||||
|
import org.springframework.web.method.support.ModelAndViewContainer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An implementation of a {@link HandlerMethodArgumentResolver} that is capable
|
||||||
|
* of resolving a method parameter into an argument value for the following types:
|
||||||
|
* {@link ClientRegistration}, {@link OAuth2AuthorizedClient} and {@link OAuth2AccessToken}.
|
||||||
|
*
|
||||||
|
* <p>
|
||||||
|
* For example:
|
||||||
|
* <pre>
|
||||||
|
* @Controller
|
||||||
|
* public class MyController {
|
||||||
|
* @GetMapping("/client-registration")
|
||||||
|
* public String clientRegistration(@OAuth2Client("login-client") ClientRegistration clientRegistration) {
|
||||||
|
* // do something with clientRegistration
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @GetMapping("/authorized-client")
|
||||||
|
* public String authorizedClient(@OAuth2Client("login-client") OAuth2AuthorizedClient authorizedClient) {
|
||||||
|
* // do something with authorizedClient
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* @GetMapping("/access-token")
|
||||||
|
* public String accessToken(@OAuth2Client("login-client") OAuth2AccessToken accessToken) {
|
||||||
|
* // do something with accessToken
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
* @since 5.1
|
||||||
|
* @see OAuth2Client
|
||||||
|
*/
|
||||||
|
public final class OAuth2ClientArgumentResolver implements HandlerMethodArgumentResolver {
|
||||||
|
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||||
|
private final OAuth2AuthorizedClientService authorizedClientService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs an {@code OAuth2ClientArgumentResolver} using the provided parameters.
|
||||||
|
*
|
||||||
|
* @param clientRegistrationRepository the repository of client registrations
|
||||||
|
* @param authorizedClientService the authorized client service
|
||||||
|
*/
|
||||||
|
public OAuth2ClientArgumentResolver(ClientRegistrationRepository clientRegistrationRepository,
|
||||||
|
OAuth2AuthorizedClientService authorizedClientService) {
|
||||||
|
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
|
||||||
|
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
|
||||||
|
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||||
|
this.authorizedClientService = authorizedClientService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean supportsParameter(MethodParameter parameter) {
|
||||||
|
Class<?> parameterType = parameter.getParameterType();
|
||||||
|
return ((OAuth2AccessToken.class.isAssignableFrom(parameterType) ||
|
||||||
|
OAuth2AuthorizedClient.class.isAssignableFrom(parameterType) ||
|
||||||
|
ClientRegistration.class.isAssignableFrom(parameterType)) &&
|
||||||
|
(parameter.hasParameterAnnotation(OAuth2Client.class)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@NonNull
|
||||||
|
@Override
|
||||||
|
public Object resolveArgument(MethodParameter parameter,
|
||||||
|
@Nullable ModelAndViewContainer mavContainer,
|
||||||
|
NativeWebRequest webRequest,
|
||||||
|
@Nullable WebDataBinderFactory binderFactory) throws Exception {
|
||||||
|
|
||||||
|
OAuth2Client oauth2ClientAnnotation = parameter.getParameterAnnotation(OAuth2Client.class);
|
||||||
|
Authentication principal = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
|
||||||
|
String clientRegistrationId = null;
|
||||||
|
if (!StringUtils.isEmpty(oauth2ClientAnnotation.registrationId())) {
|
||||||
|
clientRegistrationId = oauth2ClientAnnotation.registrationId();
|
||||||
|
} else if (!StringUtils.isEmpty(oauth2ClientAnnotation.value())) {
|
||||||
|
clientRegistrationId = oauth2ClientAnnotation.value();
|
||||||
|
} else if (principal != null && OAuth2AuthenticationToken.class.isAssignableFrom(principal.getClass())) {
|
||||||
|
clientRegistrationId = ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId();
|
||||||
|
}
|
||||||
|
if (StringUtils.isEmpty(clientRegistrationId)) {
|
||||||
|
throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. " +
|
||||||
|
"It must be provided via @OAuth2Client(\"client1\") or @OAuth2Client(registrationId = \"client1\").");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ClientRegistration.class.isAssignableFrom(parameter.getParameterType())) {
|
||||||
|
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
|
||||||
|
if (clientRegistration == null) {
|
||||||
|
throw new IllegalArgumentException("Unable to find ClientRegistration with registration identifier \"" +
|
||||||
|
clientRegistrationId + "\".");
|
||||||
|
}
|
||||||
|
return clientRegistration;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (principal == null) {
|
||||||
|
// An Authentication is required given that an OAuth2AuthorizedClient is associated to a Principal
|
||||||
|
throw new IllegalStateException("Unable to resolve the Authorized Client with registration identifier \"" +
|
||||||
|
clientRegistrationId + "\". An \"authenticated\" or \"unauthenticated\" session is required. " +
|
||||||
|
"To allow for unauthenticated access, ensure HttpSecurity.anonymous() is configured.");
|
||||||
|
}
|
||||||
|
|
||||||
|
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService.loadAuthorizedClient(
|
||||||
|
clientRegistrationId, principal.getName());
|
||||||
|
if (authorizedClient == null) {
|
||||||
|
throw new ClientAuthorizationRequiredException(clientRegistrationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return OAuth2AccessToken.class.isAssignableFrom(parameter.getParameterType()) ?
|
||||||
|
authorizedClient.getAccessToken() : authorizedClient;
|
||||||
|
}
|
||||||
|
}
|
@ -28,15 +28,13 @@ import org.springframework.security.oauth2.client.registration.InMemoryClientReg
|
|||||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||||
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
|
||||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
import org.springframework.security.web.savedrequest.RequestCache;
|
||||||
|
|
||||||
import javax.servlet.FilterChain;
|
import javax.servlet.FilterChain;
|
||||||
import javax.servlet.ServletRequest;
|
import javax.servlet.ServletRequest;
|
||||||
import javax.servlet.ServletResponse;
|
import javax.servlet.ServletResponse;
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
import javax.servlet.http.HttpSession;
|
|
||||||
import java.util.Collections;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
@ -53,6 +51,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
private ClientRegistration registration3;
|
private ClientRegistration registration3;
|
||||||
private ClientRegistrationRepository clientRegistrationRepository;
|
private ClientRegistrationRepository clientRegistrationRepository;
|
||||||
private OAuth2AuthorizationRequestRedirectFilter filter;
|
private OAuth2AuthorizationRequestRedirectFilter filter;
|
||||||
|
private RequestCache requestCache;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setUp() {
|
public void setUp() {
|
||||||
@ -95,6 +94,8 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(
|
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(
|
||||||
this.registration1, this.registration2, this.registration3);
|
this.registration1, this.registration2, this.registration3);
|
||||||
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository);
|
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository);
|
||||||
|
this.requestCache = mock(RequestCache.class);
|
||||||
|
this.filter.setRequestCache(this.requestCache);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -115,6 +116,12 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
.isInstanceOf(IllegalArgumentException.class);
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
|
||||||
|
assertThatThrownBy(() -> this.filter.setRequestCache(null))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
|
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
|
||||||
String requestUri = "/path";
|
String requestUri = "/path";
|
||||||
@ -129,7 +136,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusBadRequest() throws Exception {
|
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError() throws Exception {
|
||||||
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI +
|
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI +
|
||||||
"/" + this.registration1.getRegistrationId() + "-invalid";
|
"/" + this.registration1.getRegistrationId() + "-invalid";
|
||||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
|
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
|
||||||
@ -141,8 +148,8 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
|
|
||||||
verifyZeroInteractions(filterChain);
|
verifyZeroInteractions(filterChain);
|
||||||
|
|
||||||
assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
|
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
|
||||||
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase());
|
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -320,16 +327,7 @@ public class OAuth2AuthorizationRequestRedirectFilterTests {
|
|||||||
|
|
||||||
assertThat(response.getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?response_type=code&client_id=client-1&scope=user&state=.{15,}&redirect_uri=http://localhost/authorize/oauth2/code/registration-1");
|
assertThat(response.getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?response_type=code&client_id=client-1&scope=user&state=.{15,}&redirect_uri=http://localhost/authorize/oauth2/code/registration-1");
|
||||||
|
|
||||||
HttpSession session = request.getSession(false);
|
verify(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
|
||||||
assertThat(session).isNotNull();
|
|
||||||
boolean requestSaved = false;
|
|
||||||
for (String attrName : Collections.list(session.getAttributeNames())) {
|
|
||||||
if (SavedRequest.class.isAssignableFrom(session.getAttribute(attrName).getClass())) {
|
|
||||||
requestSaved = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assertThat(requestSaved).isTrue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -0,0 +1,260 @@
|
|||||||
|
/*
|
||||||
|
* 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.oauth2.client.web.method.annotation;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.springframework.core.MethodParameter;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContext;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
|
||||||
|
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.authentication.OAuth2AuthenticationToken;
|
||||||
|
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.util.ReflectionUtils;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
|
||||||
|
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for {@link OAuth2ClientArgumentResolver}.
|
||||||
|
*
|
||||||
|
* @author Joe Grandja
|
||||||
|
*/
|
||||||
|
public class OAuth2ClientArgumentResolverTests {
|
||||||
|
private ClientRegistrationRepository clientRegistrationRepository;
|
||||||
|
private OAuth2AuthorizedClientService authorizedClientService;
|
||||||
|
private OAuth2ClientArgumentResolver argumentResolver;
|
||||||
|
private ClientRegistration clientRegistration;
|
||||||
|
private OAuth2AuthorizedClient authorizedClient;
|
||||||
|
private OAuth2AccessToken accessToken;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUp() {
|
||||||
|
this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
|
||||||
|
this.authorizedClientService = mock(OAuth2AuthorizedClientService.class);
|
||||||
|
this.argumentResolver = new OAuth2ClientArgumentResolver(
|
||||||
|
this.clientRegistrationRepository, this.authorizedClientService);
|
||||||
|
this.clientRegistration = ClientRegistration.withRegistrationId("client1")
|
||||||
|
.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(this.clientRegistrationRepository.findByRegistrationId(anyString())).thenReturn(this.clientRegistration);
|
||||||
|
this.authorizedClient = mock(OAuth2AuthorizedClient.class);
|
||||||
|
when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(this.authorizedClient);
|
||||||
|
this.accessToken = mock(OAuth2AccessToken.class);
|
||||||
|
when(this.authorizedClient.getAccessToken()).thenReturn(this.accessToken);
|
||||||
|
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||||
|
securityContext.setAuthentication(mock(Authentication.class));
|
||||||
|
SecurityContextHolder.setContext(securityContext);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
|
||||||
|
assertThatThrownBy(() -> new OAuth2ClientArgumentResolver(null, this.authorizedClientService))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
|
||||||
|
assertThatThrownBy(() -> new OAuth2ClientArgumentResolver(this.clientRegistrationRepository, null))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeOAuth2AccessTokenThenTrue() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeOAuth2AccessTokenWithoutAnnotationThenFalse() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessTokenWithoutAnnotation", OAuth2AccessToken.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeOAuth2AuthorizedClientThenTrue() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeOAuth2AuthorizedClientWithoutAnnotationThenFalse() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClientWithoutAnnotation", OAuth2AuthorizedClient.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeClientRegistrationThenTrue() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeClientRegistrationWithoutAnnotationThenFalse() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistrationWithoutAnnotation", ClientRegistration.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeUnsupportedThenFalse() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeUnsupported", String.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void supportsParameterWhenParameterTypeUnsupportedWithoutAnnotationThenFalse() {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeUnsupportedWithoutAnnotation", String.class);
|
||||||
|
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenRegistrationIdEmptyAndNotOAuth2AuthenticationThenThrowIllegalArgumentException() throws Exception {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AccessToken.class);
|
||||||
|
assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage("Unable to resolve the Client Registration Identifier. It must be provided via @OAuth2Client(\"client1\") or @OAuth2Client(registrationId = \"client1\").");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception {
|
||||||
|
OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class);
|
||||||
|
when(authentication.getAuthorizedClientRegistrationId()).thenReturn("client1");
|
||||||
|
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
|
||||||
|
securityContext.setAuthentication(authentication);
|
||||||
|
SecurityContextHolder.setContext(securityContext);
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AccessToken.class);
|
||||||
|
this.argumentResolver.resolveArgument(methodParameter, null, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenClientRegistrationFoundThenResolves() throws Exception {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class);
|
||||||
|
assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.clientRegistration);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() throws Exception {
|
||||||
|
when(this.clientRegistrationRepository.findByRegistrationId(anyString())).thenReturn(null);
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeClientRegistration", ClientRegistration.class);
|
||||||
|
assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessage("Unable to find ClientRegistration with registration identifier \"client1\".");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenParameterTypeOAuth2AuthorizedClientAndCurrentAuthenticationNullThenThrowIllegalStateException() throws Exception {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class);
|
||||||
|
assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
|
||||||
|
.isInstanceOf(IllegalStateException.class)
|
||||||
|
.hasMessage("Unable to resolve the Authorized Client with registration identifier \"client1\". " +
|
||||||
|
"An \"authenticated\" or \"unauthenticated\" session is required. " +
|
||||||
|
"To allow for unauthenticated access, ensure HttpSecurity.anonymous() is configured.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenOAuth2AuthorizedClientFoundThenResolves() throws Exception {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class);
|
||||||
|
assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() throws Exception {
|
||||||
|
when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(null);
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient", OAuth2AuthorizedClient.class);
|
||||||
|
assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
|
||||||
|
.isInstanceOf(ClientAuthorizationRequiredException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenOAuth2AccessTokenAndOAuth2AuthorizedClientFoundThenResolves() throws Exception {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class);
|
||||||
|
assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient.getAccessToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenOAuth2AccessTokenAndOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() throws Exception {
|
||||||
|
when(this.authorizedClientService.loadAuthorizedClient(anyString(), any())).thenReturn(null);
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessToken", OAuth2AccessToken.class);
|
||||||
|
assertThatThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
|
||||||
|
.isInstanceOf(ClientAuthorizationRequiredException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void resolveArgumentWhenOAuth2AccessTokenAndAnnotationRegistrationIdSetThenResolves() throws Exception {
|
||||||
|
MethodParameter methodParameter = this.getMethodParameter("paramTypeAccessTokenAnnotationRegistrationId", OAuth2AccessToken.class);
|
||||||
|
assertThat(this.argumentResolver.resolveArgument(methodParameter, null, null, null)).isSameAs(this.authorizedClient.getAccessToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
|
||||||
|
Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes);
|
||||||
|
return new MethodParameter(method, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static class TestController {
|
||||||
|
void paramTypeAccessToken(@OAuth2Client("client1") OAuth2AccessToken accessToken) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeAccessTokenWithoutAnnotation(OAuth2AccessToken accessToken) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeAuthorizedClient(@OAuth2Client("client1") OAuth2AuthorizedClient authorizedClient) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeAuthorizedClientWithoutAnnotation(OAuth2AuthorizedClient authorizedClient) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeClientRegistration(@OAuth2Client("client1") ClientRegistration clientRegistration) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeClientRegistrationWithoutAnnotation(ClientRegistration clientRegistration) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeUnsupported(@OAuth2Client("client1") String param) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeUnsupportedWithoutAnnotation(String param) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void registrationIdEmpty(@OAuth2Client OAuth2AccessToken accessToken) {
|
||||||
|
}
|
||||||
|
|
||||||
|
void paramTypeAccessTokenAnnotationRegistrationId(@OAuth2Client(registrationId = "client1") OAuth2AccessToken accessToken) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -15,12 +15,9 @@
|
|||||||
*/
|
*/
|
||||||
package sample.web;
|
package sample.web;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
|
|
||||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
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.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
@ -35,9 +32,7 @@ import java.util.List;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
*/
|
*/
|
||||||
@Controller
|
@Controller
|
||||||
public class MainController {
|
public class GitHubReposController {
|
||||||
@Autowired
|
|
||||||
private OAuth2AuthorizedClientService authorizedClientService;
|
|
||||||
|
|
||||||
@GetMapping("/")
|
@GetMapping("/")
|
||||||
public String index() {
|
public String index() {
|
||||||
@ -45,16 +40,7 @@ public class MainController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/repos")
|
@GetMapping("/repos")
|
||||||
public String gitHubRepos(Model model, Authentication authentication) {
|
public String gitHubRepos(Model model, @OAuth2Client("github") OAuth2AuthorizedClient authorizedClient) {
|
||||||
String registrationId = "github";
|
|
||||||
|
|
||||||
OAuth2AuthorizedClient authorizedClient =
|
|
||||||
this.authorizedClientService.loadAuthorizedClient(
|
|
||||||
registrationId, authentication.getName());
|
|
||||||
if (authorizedClient == null) {
|
|
||||||
throw new ClientAuthorizationRequiredException(registrationId);
|
|
||||||
}
|
|
||||||
|
|
||||||
String endpointUri = "https://api.github.com/user/repos";
|
String endpointUri = "https://api.github.com/user/repos";
|
||||||
List repos = WebClient.builder()
|
List repos = WebClient.builder()
|
||||||
.filter(oauth2Credentials(authorizedClient))
|
.filter(oauth2Credentials(authorizedClient))
|
@ -145,7 +145,7 @@ public class OAuth2LoginApplicationTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void requestAuthorizeClientWhenInvalidClientThenStatusBadRequest() throws Exception {
|
public void requestAuthorizeClientWhenInvalidClientThenStatusInternalServerError() throws Exception {
|
||||||
HtmlPage page = this.webClient.getPage("/");
|
HtmlPage page = this.webClient.getPage("/");
|
||||||
|
|
||||||
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
|
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId("google");
|
||||||
@ -161,7 +161,7 @@ public class OAuth2LoginApplicationTests {
|
|||||||
response = ex.getResponse();
|
response = ex.getResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value());
|
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2002-2017 the original author or authors.
|
* Copyright 2002-2018 the original author or authors.
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@ -15,15 +15,13 @@
|
|||||||
*/
|
*/
|
||||||
package sample.web;
|
package sample.web;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.http.HttpHeaders;
|
import org.springframework.http.HttpHeaders;
|
||||||
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
|
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.authentication.OAuth2AuthenticationToken;
|
|
||||||
import org.springframework.stereotype.Controller;
|
import org.springframework.stereotype.Controller;
|
||||||
import org.springframework.ui.Model;
|
import org.springframework.ui.Model;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.reactive.function.client.ClientRequest;
|
import org.springframework.web.reactive.function.client.ClientRequest;
|
||||||
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
|
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
|
||||||
import org.springframework.web.reactive.function.client.WebClient;
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
@ -36,22 +34,17 @@ import java.util.Map;
|
|||||||
* @author Joe Grandja
|
* @author Joe Grandja
|
||||||
*/
|
*/
|
||||||
@Controller
|
@Controller
|
||||||
public class MainController {
|
public class OAuth2LoginController {
|
||||||
|
|
||||||
@Autowired
|
@GetMapping("/")
|
||||||
private OAuth2AuthorizedClientService authorizedClientService;
|
public String index(Model model, @OAuth2Client OAuth2AuthorizedClient authorizedClient) {
|
||||||
|
model.addAttribute("userName", authorizedClient.getPrincipalName());
|
||||||
@RequestMapping("/")
|
|
||||||
public String index(Model model, OAuth2AuthenticationToken authentication) {
|
|
||||||
OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
|
|
||||||
model.addAttribute("userName", authentication.getName());
|
|
||||||
model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
|
model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
|
||||||
return "index";
|
return "index";
|
||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping("/userinfo")
|
@GetMapping("/userinfo")
|
||||||
public String userinfo(Model model, OAuth2AuthenticationToken authentication) {
|
public String userinfo(Model model, @OAuth2Client OAuth2AuthorizedClient authorizedClient) {
|
||||||
OAuth2AuthorizedClient authorizedClient = this.getAuthorizedClient(authentication);
|
|
||||||
Map userAttributes = Collections.emptyMap();
|
Map userAttributes = Collections.emptyMap();
|
||||||
String userInfoEndpointUri = authorizedClient.getClientRegistration()
|
String userInfoEndpointUri = authorizedClient.getClientRegistration()
|
||||||
.getProviderDetails().getUserInfoEndpoint().getUri();
|
.getProviderDetails().getUserInfoEndpoint().getUri();
|
||||||
@ -69,11 +62,6 @@ public class MainController {
|
|||||||
return "userinfo";
|
return "userinfo";
|
||||||
}
|
}
|
||||||
|
|
||||||
private OAuth2AuthorizedClient getAuthorizedClient(OAuth2AuthenticationToken authentication) {
|
|
||||||
return this.authorizedClientService.loadAuthorizedClient(
|
|
||||||
authentication.getAuthorizedClientRegistrationId(), authentication.getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
|
private ExchangeFilterFunction oauth2Credentials(OAuth2AuthorizedClient authorizedClient) {
|
||||||
return ExchangeFilterFunction.ofRequestProcessor(
|
return ExchangeFilterFunction.ofRequestProcessor(
|
||||||
clientRequest -> {
|
clientRequest -> {
|
Loading…
x
Reference in New Issue
Block a user