|
| 1 | +/* |
| 2 | + * Copyright 2020 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.security.oauth2.server.authorization.web; |
| 17 | + |
| 18 | +import org.junit.Before; |
| 19 | +import org.junit.BeforeClass; |
| 20 | +import org.junit.Rule; |
| 21 | +import org.junit.Test; |
| 22 | +import org.springframework.beans.factory.annotation.Autowired; |
| 23 | +import org.springframework.http.HttpHeaders; |
| 24 | +import org.springframework.security.config.annotation.web.builders.HttpSecurity; |
| 25 | +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; |
| 26 | +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; |
| 27 | +import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer; |
| 28 | +import org.springframework.security.config.test.SpringTestRule; |
| 29 | +import org.springframework.security.oauth2.core.AuthorizationGrantType; |
| 30 | +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType; |
| 31 | +import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; |
| 32 | +import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; |
| 33 | +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationAttributeNames; |
| 34 | +import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; |
| 35 | +import org.springframework.security.oauth2.server.authorization.TestOAuth2Authorizations; |
| 36 | +import org.springframework.security.oauth2.server.authorization.TokenType; |
| 37 | +import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; |
| 38 | +import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; |
| 39 | +import org.springframework.security.oauth2.server.authorization.client.TestRegisteredClients; |
| 40 | +import org.springframework.test.web.servlet.MockMvc; |
| 41 | +import org.springframework.test.web.servlet.MvcResult; |
| 42 | +import org.springframework.util.LinkedMultiValueMap; |
| 43 | +import org.springframework.util.MultiValueMap; |
| 44 | +import org.springframework.util.StringUtils; |
| 45 | + |
| 46 | +import java.net.URLEncoder; |
| 47 | +import java.nio.charset.StandardCharsets; |
| 48 | +import java.util.Base64; |
| 49 | + |
| 50 | +import static org.assertj.core.api.Assertions.assertThat; |
| 51 | +import static org.hamcrest.CoreMatchers.containsString; |
| 52 | +import static org.mockito.ArgumentMatchers.any; |
| 53 | +import static org.mockito.ArgumentMatchers.eq; |
| 54 | +import static org.mockito.Mockito.mock; |
| 55 | +import static org.mockito.Mockito.reset; |
| 56 | +import static org.mockito.Mockito.verify; |
| 57 | +import static org.mockito.Mockito.verifyNoInteractions; |
| 58 | +import static org.mockito.Mockito.when; |
| 59 | +import static org.springframework.security.config.Customizer.withDefaults; |
| 60 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; |
| 61 | +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; |
| 62 | +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; |
| 63 | +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; |
| 64 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; |
| 65 | +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
| 66 | + |
| 67 | +/** |
| 68 | + * Integration tests for the OAuth 2.0 Authorization Code Grant. |
| 69 | + * |
| 70 | + * @author Joe Grandja |
| 71 | + */ |
| 72 | +public class OAuth2AuthorizationCodeGrantTests { |
| 73 | + private static RegisteredClientRepository registeredClientRepository; |
| 74 | + private static OAuth2AuthorizationService authorizationService; |
| 75 | + |
| 76 | + @Rule |
| 77 | + public final SpringTestRule spring = new SpringTestRule(); |
| 78 | + |
| 79 | + @Autowired |
| 80 | + private MockMvc mvc; |
| 81 | + |
| 82 | + @BeforeClass |
| 83 | + public static void init() { |
| 84 | + registeredClientRepository = mock(RegisteredClientRepository.class); |
| 85 | + authorizationService = mock(OAuth2AuthorizationService.class); |
| 86 | + } |
| 87 | + |
| 88 | + @Before |
| 89 | + public void setup() { |
| 90 | + reset(registeredClientRepository); |
| 91 | + reset(authorizationService); |
| 92 | + } |
| 93 | + |
| 94 | + @Test |
| 95 | + public void requestWhenAuthorizationRequestNotAuthenticatedThenRedirectToLogin() throws Exception { |
| 96 | + this.spring.register(OAuth2AuthorizationServerConfiguration.class).autowire(); |
| 97 | + |
| 98 | + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); |
| 99 | + when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) |
| 100 | + .thenReturn(registeredClient); |
| 101 | + |
| 102 | + MvcResult mvcResult = this.mvc.perform(get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI) |
| 103 | + .params(getAuthorizationRequestParameters(registeredClient))) |
| 104 | + .andExpect(status().is3xxRedirection()) |
| 105 | + .andReturn(); |
| 106 | + assertThat(mvcResult.getResponse().getRedirectedUrl()).endsWith("/login"); |
| 107 | + |
| 108 | + verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId())); |
| 109 | + verifyNoInteractions(authorizationService); |
| 110 | + } |
| 111 | + |
| 112 | + @Test |
| 113 | + public void requestWhenAuthorizationRequestAuthenticatedThenRedirectToClient() throws Exception { |
| 114 | + this.spring.register(OAuth2AuthorizationServerConfiguration.class).autowire(); |
| 115 | + |
| 116 | + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); |
| 117 | + when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) |
| 118 | + .thenReturn(registeredClient); |
| 119 | + |
| 120 | + MvcResult mvcResult = this.mvc.perform(get(OAuth2AuthorizationEndpointFilter.DEFAULT_AUTHORIZATION_ENDPOINT_URI) |
| 121 | + .params(getAuthorizationRequestParameters(registeredClient)) |
| 122 | + .with(user("user"))) |
| 123 | + .andExpect(status().is3xxRedirection()) |
| 124 | + .andReturn(); |
| 125 | + assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://example.com\\?code=.{15,}&state=state"); |
| 126 | + |
| 127 | + verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId())); |
| 128 | + verify(authorizationService).save(any()); |
| 129 | + } |
| 130 | + |
| 131 | + @Test |
| 132 | + public void requestWhenTokenRequestValidThenResponseIncludesCacheHeaders() throws Exception { |
| 133 | + this.spring.register(OAuth2AuthorizationServerConfiguration.class).autowire(); |
| 134 | + |
| 135 | + RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); |
| 136 | + when(registeredClientRepository.findByClientId(eq(registeredClient.getClientId()))) |
| 137 | + .thenReturn(registeredClient); |
| 138 | + |
| 139 | + OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(registeredClient).build(); |
| 140 | + when(authorizationService.findByTokenAndTokenType( |
| 141 | + eq(authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE)), |
| 142 | + eq(TokenType.AUTHORIZATION_CODE))) |
| 143 | + .thenReturn(authorization); |
| 144 | + |
| 145 | + this.mvc.perform(post(OAuth2TokenEndpointFilter.DEFAULT_TOKEN_ENDPOINT_URI) |
| 146 | + .params(getTokenRequestParameters(registeredClient, authorization)) |
| 147 | + .header(HttpHeaders.AUTHORIZATION, "Basic " + encodeBasicAuth( |
| 148 | + registeredClient.getClientId(), registeredClient.getClientSecret())) |
| 149 | + .with(csrf())) |
| 150 | + .andExpect(status().isOk()) |
| 151 | + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, containsString("no-store"))) |
| 152 | + .andExpect(header().string(HttpHeaders.PRAGMA, containsString("no-cache"))); |
| 153 | + |
| 154 | + verify(registeredClientRepository).findByClientId(eq(registeredClient.getClientId())); |
| 155 | + verify(authorizationService).findByTokenAndTokenType( |
| 156 | + eq(authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE)), |
| 157 | + eq(TokenType.AUTHORIZATION_CODE)); |
| 158 | + verify(authorizationService).save(any()); |
| 159 | + } |
| 160 | + |
| 161 | + private static MultiValueMap<String, String> getAuthorizationRequestParameters(RegisteredClient registeredClient) { |
| 162 | + MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); |
| 163 | + parameters.set(OAuth2ParameterNames.RESPONSE_TYPE, OAuth2AuthorizationResponseType.CODE.getValue()); |
| 164 | + parameters.set(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); |
| 165 | + parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next()); |
| 166 | + parameters.set(OAuth2ParameterNames.SCOPE, |
| 167 | + StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); |
| 168 | + parameters.set(OAuth2ParameterNames.STATE, "state"); |
| 169 | + return parameters; |
| 170 | + } |
| 171 | + |
| 172 | + private static MultiValueMap<String, String> getTokenRequestParameters(RegisteredClient registeredClient, |
| 173 | + OAuth2Authorization authorization) { |
| 174 | + MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); |
| 175 | + parameters.set(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); |
| 176 | + parameters.set(OAuth2ParameterNames.CODE, authorization.getAttribute(OAuth2AuthorizationAttributeNames.CODE)); |
| 177 | + parameters.set(OAuth2ParameterNames.REDIRECT_URI, registeredClient.getRedirectUris().iterator().next()); |
| 178 | + return parameters; |
| 179 | + } |
| 180 | + |
| 181 | + private static String encodeBasicAuth(String clientId, String secret) throws Exception { |
| 182 | + clientId = URLEncoder.encode(clientId, StandardCharsets.UTF_8.name()); |
| 183 | + secret = URLEncoder.encode(secret, StandardCharsets.UTF_8.name()); |
| 184 | + String credentialsString = clientId + ":" + secret; |
| 185 | + byte[] encodedBytes = Base64.getEncoder().encode(credentialsString.getBytes(StandardCharsets.UTF_8)); |
| 186 | + return new String(encodedBytes, StandardCharsets.UTF_8); |
| 187 | + } |
| 188 | + |
| 189 | + @EnableWebSecurity |
| 190 | + static class OAuth2AuthorizationServerConfiguration extends WebSecurityConfigurerAdapter { |
| 191 | + private OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer |
| 192 | + = new OAuth2AuthorizationServerConfigurer<>(); |
| 193 | + |
| 194 | + // @formatter:off |
| 195 | + @Override |
| 196 | + protected void configure(HttpSecurity http) throws Exception { |
| 197 | + http |
| 198 | + .authorizeRequests(authorizeRequests -> |
| 199 | + authorizeRequests |
| 200 | + .anyRequest().authenticated() |
| 201 | + ) |
| 202 | + .formLogin(withDefaults()) |
| 203 | + .apply(this.authorizationServerConfigurer); |
| 204 | + |
| 205 | + configure(this.authorizationServerConfigurer); |
| 206 | + } |
| 207 | + // @formatter:on |
| 208 | + |
| 209 | + private void configure(OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer) { |
| 210 | + authorizationServerConfigurer |
| 211 | + .registeredClientRepository(registeredClientRepository) |
| 212 | + .authorizationService(authorizationService); |
| 213 | + } |
| 214 | + } |
| 215 | +} |
0 commit comments