repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/DelegatingOAuth2TokenValidator.java | /*
* Copyright 2002-2022 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
*
* https://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.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.util.Assert;
/**
* A composite validator
*
* @param <T> the type of {@link OAuth2Token} this validator validates
* @author Josh Cummings
* @since 5.1
*/
public final class DelegatingOAuth2TokenValidator<T extends OAuth2Token> implements OAuth2TokenValidator<T> {
private final Collection<OAuth2TokenValidator<T>> tokenValidators;
/**
* Constructs a {@code DelegatingOAuth2TokenValidator} using the provided validators.
* @param tokenValidators the {@link Collection} of {@link OAuth2TokenValidator}s to
* use
*/
public DelegatingOAuth2TokenValidator(Collection<OAuth2TokenValidator<T>> tokenValidators) {
Assert.notNull(tokenValidators, "tokenValidators cannot be null");
this.tokenValidators = new ArrayList<>(tokenValidators);
}
/**
* Constructs a {@code DelegatingOAuth2TokenValidator} using the provided validators.
* @param tokenValidators the collection of {@link OAuth2TokenValidator}s to use
*/
@SafeVarargs
public DelegatingOAuth2TokenValidator(OAuth2TokenValidator<T>... tokenValidators) {
this(Arrays.asList(tokenValidators));
}
@Override
public OAuth2TokenValidatorResult validate(T token) {
Collection<OAuth2Error> errors = new ArrayList<>();
for (OAuth2TokenValidator<T> validator : this.tokenValidators) {
errors.addAll(validator.validate(token).getErrors());
}
return OAuth2TokenValidatorResult.failure(errors);
}
}
| 2,170 | 32.4 | 109 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2ErrorCodes.java | /*
* Copyright 2002-2022 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
*
* https://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.core;
/**
* Standard error codes defined by the OAuth 2.0 Authorization Framework.
*
* @author Joe Grandja
* @since 5.0
*/
public final class OAuth2ErrorCodes {
/**
* {@code invalid_request} - The request is missing a required parameter, includes an
* invalid parameter value, includes a parameter more than once, or is otherwise
* malformed.
*/
public static final String INVALID_REQUEST = "invalid_request";
/**
* {@code unauthorized_client} - The client is not authorized to request an
* authorization code or access token using this method.
*/
public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
/**
* {@code access_denied} - The resource owner or authorization server denied the
* request.
*/
public static final String ACCESS_DENIED = "access_denied";
/**
* {@code unsupported_response_type} - The authorization server does not support
* obtaining an authorization code or access token using this method.
*/
public static final String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
/**
* {@code invalid_scope} - The requested scope is invalid, unknown, malformed or
* exceeds the scope granted by the resource owner.
*/
public static final String INVALID_SCOPE = "invalid_scope";
/**
* {@code insufficient_scope} - The request requires higher privileges than provided
* by the access token. The resource server SHOULD respond with the HTTP 403
* (Forbidden) status code and MAY include the "scope" attribute with the scope
* necessary to access the protected resource.
*
* @see <a href="https://tools.ietf.org/html/rfc6750#section-3.1">RFC-6750 - Section
* 3.1 - Error Codes</a>
*/
public static final String INSUFFICIENT_SCOPE = "insufficient_scope";
/**
* {@code invalid_token} - The access token provided is expired, revoked, malformed,
* or invalid for other reasons. The resource SHOULD respond with the HTTP 401
* (Unauthorized) status code. The client MAY request a new access token and retry the
* protected resource request.
*
* @see <a href="https://tools.ietf.org/html/rfc6750#section-3.1">RFC-6750 - Section
* 3.1 - Error Codes</a>
*/
public static final String INVALID_TOKEN = "invalid_token";
/**
* {@code server_error} - The authorization server encountered an unexpected condition
* that prevented it from fulfilling the request. (This error code is needed because a
* 500 Internal Server Error HTTP status code cannot be returned to the client via a
* HTTP redirect.)
*/
public static final String SERVER_ERROR = "server_error";
/**
* {@code temporarily_unavailable} - The authorization server is currently unable to
* handle the request due to a temporary overloading or maintenance of the server.
* (This error code is needed because a 503 Service Unavailable HTTP status code
* cannot be returned to the client via an HTTP redirect.)
*/
public static final String TEMPORARILY_UNAVAILABLE = "temporarily_unavailable";
/**
* {@code invalid_client} - Client authentication failed (e.g., unknown client, no
* client authentication included, or unsupported authentication method). The
* authorization server MAY return a HTTP 401 (Unauthorized) status code to indicate
* which HTTP authentication schemes are supported. If the client attempted to
* authenticate via the "Authorization" request header field, the
* authorization server MUST respond with a HTTP 401 (Unauthorized) status code and
* include the "WWW-Authenticate" response header field matching the
* authentication scheme used by the client.
*/
public static final String INVALID_CLIENT = "invalid_client";
/**
* {@code invalid_grant} - The provided authorization grant (e.g., authorization code,
* resource owner credentials) or refresh token is invalid, expired, revoked, does not
* match the redirection URI used in the authorization request, or was issued to
* another client.
*/
public static final String INVALID_GRANT = "invalid_grant";
/**
* {@code unsupported_grant_type} - The authorization grant type is not supported by
* the authorization server.
*/
public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
/**
* {@code unsupported_token_type} - The authorization server does not support the
* revocation of the presented token type.
*
* @since 5.5
* @see <a href="https://tools.ietf.org/html/rfc7009#section-2.2.1">RFC-7009 - Section
* 2.2.1 - Error Response</a>
*/
public static final String UNSUPPORTED_TOKEN_TYPE = "unsupported_token_type";
/**
* {@code invalid_redirect_uri} - The value of one or more redirection URIs is
* invalid.
*
* @since 5.6
* @see <a href="https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2">RFC-7591
* - Section 3.2.2 - Client Registration Error Response</a>
*/
public static final String INVALID_REDIRECT_URI = "invalid_redirect_uri";
private OAuth2ErrorCodes() {
}
}
| 5,643 | 37.657534 | 87 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/ClaimAccessor.java | /*
* Copyright 2002-2022 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
*
* https://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.core;
import java.net.URL;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.util.Assert;
/**
* An "accessor" for a set of claims that may be used for assertions.
*
* @author Joe Grandja
* @since 5.0
*/
public interface ClaimAccessor {
/**
* Returns a set of claims that may be used for assertions.
* @return a {@code Map} of claims
*/
Map<String, Object> getClaims();
/**
* Returns the claim value as a {@code T} type. The claim value is expected to be of
* type {@code T}.
* @param claim the name of the claim
* @param <T> the type of the claim value
* @return the claim value
* @since 5.2
*/
@SuppressWarnings("unchecked")
default <T> T getClaim(String claim) {
return !hasClaim(claim) ? null : (T) getClaims().get(claim);
}
/**
* Returns {@code true} if the claim exists in {@link #getClaims()}, otherwise
* {@code false}.
* @param claim the name of the claim
* @return {@code true} if the claim exists, otherwise {@code false}
* @since 5.5
*/
default boolean hasClaim(String claim) {
Assert.notNull(claim, "claim cannot be null");
return getClaims().containsKey(claim);
}
/**
* Returns the claim value as a {@code String} or {@code null} if it does not exist or
* is equal to {@code null}.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist or is equal to
* {@code null}
*/
default String getClaimAsString(String claim) {
return !hasClaim(claim) ? null
: ClaimConversionService.getSharedInstance().convert(getClaims().get(claim), String.class);
}
/**
* Returns the claim value as a {@code Boolean} or {@code null} if the claim does not
* exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code Boolean}
* @throws NullPointerException if the claim value is {@code null}
*/
default Boolean getClaimAsBoolean(String claim) {
if (!hasClaim(claim)) {
return null;
}
Object claimValue = getClaims().get(claim);
Boolean convertedValue = ClaimConversionService.getSharedInstance().convert(claimValue, Boolean.class);
Assert.notNull(convertedValue,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Boolean.");
return convertedValue;
}
/**
* Returns the claim value as an {@code Instant} or {@code null} if it does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist
*/
default Instant getClaimAsInstant(String claim) {
if (!hasClaim(claim)) {
return null;
}
Object claimValue = getClaims().get(claim);
Instant convertedValue = ClaimConversionService.getSharedInstance().convert(claimValue, Instant.class);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Instant.");
return convertedValue;
}
/**
* Returns the claim value as an {@code URL} or {@code null} if it does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if it does not exist
*/
default URL getClaimAsURL(String claim) {
if (!hasClaim(claim)) {
return null;
}
Object claimValue = getClaims().get(claim);
URL convertedValue = ClaimConversionService.getSharedInstance().convert(claimValue, URL.class);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to URL.");
return convertedValue;
}
/**
* Returns the claim value as a {@code Map<String, Object>} or {@code null} if the
* claim does not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code List}
* @throws NullPointerException if the claim value is {@code null}
*/
@SuppressWarnings("unchecked")
default Map<String, Object> getClaimAsMap(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.map(Map.class, TypeDescriptor.valueOf(String.class),
TypeDescriptor.valueOf(Object.class));
Object claimValue = getClaims().get(claim);
Map<String, Object> convertedValue = (Map<String, Object>) ClaimConversionService.getSharedInstance()
.convert(claimValue, sourceDescriptor, targetDescriptor);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to Map.");
return convertedValue;
}
/**
* Returns the claim value as a {@code List<String>} or {@code null} if the claim does
* not exist.
* @param claim the name of the claim
* @return the claim value or {@code null} if the claim does not exist
* @throws IllegalArgumentException if the claim value cannot be converted to a
* {@code List}
* @throws NullPointerException if the claim value is {@code null}
*/
@SuppressWarnings("unchecked")
default List<String> getClaimAsStringList(String claim) {
if (!hasClaim(claim)) {
return null;
}
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
final TypeDescriptor targetDescriptor = TypeDescriptor.collection(List.class,
TypeDescriptor.valueOf(String.class));
Object claimValue = getClaims().get(claim);
List<String> convertedValue = (List<String>) ClaimConversionService.getSharedInstance().convert(claimValue,
sourceDescriptor, targetDescriptor);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert claim '" + claim + "' of type '" + claimValue.getClass() + "' to List.");
return convertedValue;
}
}
| 6,729 | 35.978022 | 109 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/OAuth2TokenIntrospectionClaimAccessor.java | /*
* Copyright 2002-2021 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
*
* https://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.core;
import java.net.URL;
import java.time.Instant;
import java.util.List;
import org.springframework.lang.Nullable;
/**
* A {@link ClaimAccessor} for the "claims" that may be contained in the
* Introspection Response.
*
* @author David Kovac
* @since 5.6
* @see ClaimAccessor
* @see OAuth2TokenIntrospectionClaimNames
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7662#section-2.2">Introspection Response</a>
*/
public interface OAuth2TokenIntrospectionClaimAccessor extends ClaimAccessor {
/**
* Returns the indicator {@code (active)} whether or not the token is currently active
* @return the indicator whether or not the token is currently active
*/
default boolean isActive() {
return Boolean.TRUE.equals(getClaimAsBoolean(OAuth2TokenIntrospectionClaimNames.ACTIVE));
}
/**
* Returns a human-readable identifier {@code (username)} for the resource owner that
* authorized the token
* @return a human-readable identifier for the resource owner that authorized the
* token
*/
@Nullable
default String getUsername() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.USERNAME);
}
/**
* Returns the client identifier {@code (client_id)} for the token
* @return the client identifier for the token
*/
@Nullable
default String getClientId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.CLIENT_ID);
}
/**
* Returns the scopes {@code (scope)} associated with the token
* @return the scopes associated with the token
*/
@Nullable
default List<String> getScopes() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.SCOPE);
}
/**
* Returns the type of the token {@code (token_type)}, for example {@code bearer}.
* @return the type of the token, for example {@code bearer}.
*/
@Nullable
default String getTokenType() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.TOKEN_TYPE);
}
/**
* Returns a timestamp {@code (exp)} indicating when the token expires
* @return a timestamp indicating when the token expires
*/
@Nullable
default Instant getExpiresAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.EXP);
}
/**
* Returns a timestamp {@code (iat)} indicating when the token was issued
* @return a timestamp indicating when the token was issued
*/
@Nullable
default Instant getIssuedAt() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.IAT);
}
/**
* Returns a timestamp {@code (nbf)} indicating when the token is not to be used
* before
* @return a timestamp indicating when the token is not to be used before
*/
@Nullable
default Instant getNotBefore() {
return getClaimAsInstant(OAuth2TokenIntrospectionClaimNames.NBF);
}
/**
* Returns usually a machine-readable identifier {@code (sub)} of the resource owner
* who authorized the token
* @return usually a machine-readable identifier of the resource owner who authorized
* the token
*/
@Nullable
default String getSubject() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.SUB);
}
/**
* Returns the intended audience {@code (aud)} for the token
* @return the intended audience for the token
*/
@Nullable
default List<String> getAudience() {
return getClaimAsStringList(OAuth2TokenIntrospectionClaimNames.AUD);
}
/**
* Returns the issuer {@code (iss)} of the token
* @return the issuer of the token
*/
@Nullable
default URL getIssuer() {
return getClaimAsURL(OAuth2TokenIntrospectionClaimNames.ISS);
}
/**
* Returns the identifier {@code (jti)} for the token
* @return the identifier for the token
*/
@Nullable
default String getId() {
return getClaimAsString(OAuth2TokenIntrospectionClaimNames.JTI);
}
}
| 4,421 | 28.284768 | 91 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2BodyExtractors.java | /*
* 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
*
* https://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.core.web.reactive.function;
import reactor.core.publisher.Mono;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.web.reactive.function.BodyExtractor;
/**
* Static factory methods for OAuth2 {@link BodyExtractor} implementations.
*
* @author Rob Winch
* @since 5.1
*/
public abstract class OAuth2BodyExtractors {
/**
* Extractor to decode an {@link OAuth2AccessTokenResponse}
* @return a BodyExtractor for {@link OAuth2AccessTokenResponse}
*/
public static BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> oauth2AccessTokenResponse() {
return new OAuth2AccessTokenResponseBodyExtractor();
}
private OAuth2BodyExtractors() {
}
}
| 1,462 | 31.511111 | 117 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/web/reactive/function/OAuth2AccessTokenResponseBodyExtractor.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.core.web.reactive.function;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import com.nimbusds.oauth2.sdk.AccessTokenResponse;
import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.TokenErrorResponse;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import net.minidev.json.JSONObject;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.BodyExtractors;
/**
* Provides a way to create an {@link OAuth2AccessTokenResponse} from a
* {@link ReactiveHttpInputMessage}
*
* @author Rob Winch
* @since 5.1
*/
class OAuth2AccessTokenResponseBodyExtractor
implements BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
OAuth2AccessTokenResponseBodyExtractor() {
}
@Override
public Mono<OAuth2AccessTokenResponse> extract(ReactiveHttpInputMessage inputMessage, Context context) {
BodyExtractor<Mono<Map<String, Object>>, ReactiveHttpInputMessage> delegate = BodyExtractors
.toMono(STRING_OBJECT_MAP);
return delegate.extract(inputMessage, context)
.onErrorMap((ex) -> new OAuth2AuthorizationException(
invalidTokenResponse("An error occurred parsing the Access Token response: " + ex.getMessage()),
ex))
.switchIfEmpty(Mono.error(() -> new OAuth2AuthorizationException(
invalidTokenResponse("Empty OAuth 2.0 Access Token Response"))))
.map(OAuth2AccessTokenResponseBodyExtractor::parse)
.flatMap(OAuth2AccessTokenResponseBodyExtractor::oauth2AccessTokenResponse)
.map(OAuth2AccessTokenResponseBodyExtractor::oauth2AccessTokenResponse);
}
private static TokenResponse parse(Map<String, Object> json) {
try {
return TokenResponse.parse(new JSONObject(json));
}
catch (ParseException ex) {
OAuth2Error oauth2Error = invalidTokenResponse(
"An error occurred parsing the Access Token response: " + ex.getMessage());
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
private static OAuth2Error invalidTokenResponse(String message) {
return new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, message, null);
}
private static Mono<AccessTokenResponse> oauth2AccessTokenResponse(TokenResponse tokenResponse) {
if (tokenResponse.indicatesSuccess()) {
return Mono.just(tokenResponse).cast(AccessTokenResponse.class);
}
TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
ErrorObject errorObject = tokenErrorResponse.getErrorObject();
OAuth2Error oauth2Error = getOAuth2Error(errorObject);
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
private static OAuth2Error getOAuth2Error(ErrorObject errorObject) {
if (errorObject == null) {
return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR);
}
String code = (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR;
String description = errorObject.getDescription();
String uri = (errorObject.getURI() != null) ? errorObject.getURI().toString() : null;
return new OAuth2Error(code, description, uri);
}
private static OAuth2AccessTokenResponse oauth2AccessTokenResponse(AccessTokenResponse accessTokenResponse) {
AccessToken accessToken = accessTokenResponse.getTokens().getAccessToken();
OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessToken.getType().getValue())) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
long expiresIn = accessToken.getLifetime();
Set<String> scopes = (accessToken.getScope() != null)
? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet();
String refreshToken = null;
if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
}
Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken.getValue())
.tokenType(accessTokenType)
.expiresIn(expiresIn)
.scopes(scopes)
.refreshToken(refreshToken)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
}
| 5,835 | 41.289855 | 145 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/user/package-info.java | /*
* Copyright 2002-2017 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
*
* https://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.
*/
/**
* Provides a model for an OAuth 2.0 representation of a user {@code Principal}.
*/
package org.springframework.security.oauth2.core.user;
| 767 | 35.571429 | 80 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/user/DefaultOAuth2User.java | /*
* Copyright 2002-2021 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
*
* https://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.core.user;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.util.Assert;
/**
* The default implementation of an {@link OAuth2User}.
*
* <p>
* User attribute names are <b>not</b> standardized between providers and therefore it is
* required to supply the <i>key</i> for the user's "name" attribute to one of
* the constructors. The <i>key</i> will be used for accessing the "name" of the
* {@code Principal} (user) via {@link #getAttributes()} and returning it from
* {@link #getName()}.
*
* @author Joe Grandja
* @author Eddú Meléndez
* @since 5.0
* @see OAuth2User
*/
public class DefaultOAuth2User implements OAuth2User, Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Set<GrantedAuthority> authorities;
private final Map<String, Object> attributes;
private final String nameAttributeKey;
/**
* Constructs a {@code DefaultOAuth2User} using the provided parameters.
* @param authorities the authorities granted to the user
* @param attributes the attributes about the user
* @param nameAttributeKey the key used to access the user's "name" from
* {@link #getAttributes()}
*/
public DefaultOAuth2User(Collection<? extends GrantedAuthority> authorities, Map<String, Object> attributes,
String nameAttributeKey) {
Assert.notEmpty(attributes, "attributes cannot be empty");
Assert.hasText(nameAttributeKey, "nameAttributeKey cannot be empty");
if (!attributes.containsKey(nameAttributeKey)) {
throw new IllegalArgumentException("Missing attribute '" + nameAttributeKey + "' in attributes");
}
this.authorities = (authorities != null)
? Collections.unmodifiableSet(new LinkedHashSet<>(this.sortAuthorities(authorities)))
: Collections.unmodifiableSet(new LinkedHashSet<>(AuthorityUtils.NO_AUTHORITIES));
this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes));
this.nameAttributeKey = nameAttributeKey;
}
@Override
public String getName() {
return this.getAttribute(this.nameAttributeKey).toString();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public Map<String, Object> getAttributes() {
return this.attributes;
}
private Set<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities) {
SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<>(
Comparator.comparing(GrantedAuthority::getAuthority));
sortedAuthorities.addAll(authorities);
return sortedAuthorities;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
DefaultOAuth2User that = (DefaultOAuth2User) obj;
if (!this.getName().equals(that.getName())) {
return false;
}
if (!this.getAuthorities().equals(that.getAuthorities())) {
return false;
}
return this.getAttributes().equals(that.getAttributes());
}
@Override
public int hashCode() {
int result = this.getName().hashCode();
result = 31 * result + this.getAuthorities().hashCode();
result = 31 * result + this.getAttributes().hashCode();
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Name: [");
sb.append(this.getName());
sb.append("], Granted Authorities: [");
sb.append(getAuthorities());
sb.append("], User Attributes: [");
sb.append(getAttributes());
sb.append("]");
return sb.toString();
}
}
| 4,686 | 31.776224 | 109 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/user/OAuth2User.java | /*
* Copyright 2002-2019 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
*
* https://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.core.user;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
/**
* A representation of a user {@code Principal} that is registered with an OAuth 2.0
* Provider.
*
* <p>
* An OAuth 2.0 user is composed of one or more attributes, for example, first name,
* middle name, last name, email, phone number, address, etc. Each user attribute has a
* "name" and "value" and is keyed by the "name" in
* {@link #getAttributes()}.
*
* <p>
* <b>NOTE:</b> Attribute names are <b>not</b> standardized between providers and
* therefore will vary. Please consult the provider's API documentation for the set of
* supported user attribute names.
*
* <p>
* Implementation instances of this interface represent an
* {@link OAuth2AuthenticatedPrincipal} which is associated to an {@link Authentication}
* object and may be accessed via {@link Authentication#getPrincipal()}.
*
* @author Joe Grandja
* @author Eddú Meléndez
* @since 5.0
* @see DefaultOAuth2User
* @see OAuth2AuthenticatedPrincipal
*/
public interface OAuth2User extends OAuth2AuthenticatedPrincipal {
}
| 1,858 | 35.45098 | 88 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/user/OAuth2UserAuthority.java | /*
* Copyright 2002-2022 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
*
* https://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.core.user;
import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* A {@link GrantedAuthority} that may be associated to an {@link OAuth2User}.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2User
*/
public class OAuth2UserAuthority implements GrantedAuthority {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final String authority;
private final Map<String, Object> attributes;
/**
* Constructs a {@code OAuth2UserAuthority} using the provided parameters and defaults
* {@link #getAuthority()} to {@code OAUTH2_USER}.
* @param attributes the attributes about the user
*/
public OAuth2UserAuthority(Map<String, Object> attributes) {
this("OAUTH2_USER", attributes);
}
/**
* Constructs a {@code OAuth2UserAuthority} using the provided parameters.
* @param authority the authority granted to the user
* @param attributes the attributes about the user
*/
public OAuth2UserAuthority(String authority, Map<String, Object> attributes) {
Assert.hasText(authority, "authority cannot be empty");
Assert.notEmpty(attributes, "attributes cannot be empty");
this.authority = authority;
this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(attributes));
}
@Override
public String getAuthority() {
return this.authority;
}
/**
* Returns the attributes about the user.
* @return a {@code Map} of attributes about the user
*/
public Map<String, Object> getAttributes() {
return this.attributes;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OAuth2UserAuthority that = (OAuth2UserAuthority) obj;
if (!this.getAuthority().equals(that.getAuthority())) {
return false;
}
Map<String, Object> thatAttributes = that.getAttributes();
if (getAttributes().size() != thatAttributes.size()) {
return false;
}
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
String key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
if (value == null) {
if (!(thatAttributes.get(key) == null && thatAttributes.containsKey(key))) {
return false;
}
}
else {
Object thatValue = convertURLIfNecessary(thatAttributes.get(key));
if (!value.equals(thatValue)) {
return false;
}
}
}
return true;
}
@Override
public int hashCode() {
int result = this.getAuthority().hashCode();
result = 31 * result;
for (Map.Entry<String, Object> e : getAttributes().entrySet()) {
Object key = e.getKey();
Object value = convertURLIfNecessary(e.getValue());
result += Objects.hashCode(key) ^ Objects.hashCode(value);
}
return result;
}
@Override
public String toString() {
return this.getAuthority();
}
/**
* @return {@code URL} converted to a string since {@code URL} shouldn't be used for
* equality/hashCode. For other instances the value is returned as is.
*/
private static Object convertURLIfNecessary(Object value) {
return (value instanceof URL) ? ((URL) value).toExternalForm() : value;
}
}
| 4,054 | 28.384058 | 91 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ClaimTypeConverter.java | /*
* Copyright 2002-2021 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
*
* https://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.core.converter;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* A {@link Converter} that provides type conversion for claim values.
*
* @author Joe Grandja
* @since 5.2
* @see Converter
*/
public final class ClaimTypeConverter implements Converter<Map<String, Object>, Map<String, Object>> {
private final Map<String, Converter<Object, ?>> claimTypeConverters;
/**
* Constructs a {@code ClaimTypeConverter} using the provided parameters.
* @param claimTypeConverters a {@link Map} of {@link Converter}(s) keyed by claim
* name
*/
public ClaimTypeConverter(Map<String, Converter<Object, ?>> claimTypeConverters) {
Assert.notEmpty(claimTypeConverters, "claimTypeConverters cannot be empty");
Assert.noNullElements(claimTypeConverters.values().toArray(), "Converter(s) cannot be null");
this.claimTypeConverters = Collections.unmodifiableMap(new LinkedHashMap<>(claimTypeConverters));
}
@Override
public Map<String, Object> convert(Map<String, Object> claims) {
if (CollectionUtils.isEmpty(claims)) {
return claims;
}
Map<String, Object> result = new HashMap<>(claims);
this.claimTypeConverters.forEach((claimName, typeConverter) -> {
if (claims.containsKey(claimName)) {
Object claim = claims.get(claimName);
Object mappedClaim = typeConverter.convert(claim);
if (mappedClaim != null) {
result.put(claimName, mappedClaim);
}
}
});
return result;
}
}
| 2,309 | 32.478261 | 102 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToListStringConverter.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.util.ClassUtils;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToListStringConverter implements ConditionalGenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
Set<ConvertiblePair> convertibleTypes = new LinkedHashSet<>();
convertibleTypes.add(new ConvertiblePair(Object.class, List.class));
convertibleTypes.add(new ConvertiblePair(Object.class, Collection.class));
return convertibleTypes;
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getElementTypeDescriptor() == null
|| targetType.getElementTypeDescriptor().getType().equals(String.class) || sourceType == null
|| ClassUtils.isAssignable(sourceType.getType(), targetType.getElementTypeDescriptor().getType())) {
return true;
}
return false;
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (source instanceof Collection) {
Collection<String> results = new ArrayList<>();
for (Object object : ((Collection<?>) source)) {
if (object != null) {
results.add(object.toString());
}
}
return results;
}
return Collections.singletonList(source.toString());
}
}
| 2,298 | 30.930556 | 104 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToInstantConverter.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToInstantConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, Instant.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (source instanceof Instant) {
return source;
}
if (source instanceof Date) {
return ((Date) source).toInstant();
}
if (source instanceof Number) {
return Instant.ofEpochSecond(((Number) source).longValue());
}
try {
return Instant.ofEpochSecond(Long.parseLong(source.toString()));
}
catch (Exception ex) {
// Ignore
}
try {
return Instant.parse(source.toString());
}
catch (Exception ex) {
// Ignore
}
return null;
}
}
| 1,798 | 25.455882 | 93 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToURLConverter.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToURLConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, URL.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (source instanceof URL) {
return source;
}
try {
return new URI(source.toString()).toURL();
}
catch (Exception ex) {
// Ignore
}
return null;
}
}
| 1,482 | 25.482143 | 93 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ClaimConversionService.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.security.oauth2.core.ClaimAccessor;
/**
* A {@link ConversionService} configured with converters that provide type conversion for
* claim values.
*
* @author Joe Grandja
* @since 5.2
* @see GenericConversionService
* @see ClaimAccessor
*/
public final class ClaimConversionService extends GenericConversionService {
private static volatile ClaimConversionService sharedInstance;
private ClaimConversionService() {
addConverters(this);
}
/**
* Returns a shared instance of {@code ClaimConversionService}.
* @return a shared instance of {@code ClaimConversionService}
*/
public static ClaimConversionService getSharedInstance() {
ClaimConversionService sharedInstance = ClaimConversionService.sharedInstance;
if (sharedInstance == null) {
synchronized (ClaimConversionService.class) {
sharedInstance = ClaimConversionService.sharedInstance;
if (sharedInstance == null) {
sharedInstance = new ClaimConversionService();
ClaimConversionService.sharedInstance = sharedInstance;
}
}
}
return sharedInstance;
}
/**
* Adds the converters that provide type conversion for claim values to the provided
* {@link ConverterRegistry}.
* @param converterRegistry the registry of converters to add to
*/
public static void addConverters(ConverterRegistry converterRegistry) {
converterRegistry.addConverter(new ObjectToStringConverter());
converterRegistry.addConverter(new ObjectToBooleanConverter());
converterRegistry.addConverter(new ObjectToInstantConverter());
converterRegistry.addConverter(new ObjectToURLConverter());
converterRegistry.addConverter(new ObjectToListStringConverter());
converterRegistry.addConverter(new ObjectToMapStringObjectConverter());
}
}
| 2,653 | 34.864865 | 90 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToMapStringObjectConverter.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToMapStringObjectConverter implements ConditionalGenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, Map.class));
}
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getElementTypeDescriptor() == null
|| targetType.getMapKeyTypeDescriptor().getType().equals(String.class)) {
return true;
}
return false;
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (!(source instanceof Map)) {
return null;
}
Map<?, ?> sourceMap = (Map<?, ?>) source;
Map<String, Object> result = new HashMap<>();
sourceMap.forEach((k, v) -> result.put(k.toString(), v));
return result;
}
}
| 1,838 | 28.66129 | 93 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToStringConverter.java | /*
* Copyright 2002-2019 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
*
* https://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.core.converter;
import java.util.Collections;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToStringConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, String.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
return (source != null) ? source.toString() : null;
}
}
| 1,288 | 29.690476 | 93 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/converter/ObjectToBooleanConverter.java | /*
* Copyright 2002-2021 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
*
* https://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.core.converter;
import java.util.Collections;
import java.util.Set;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
/**
* @author Joe Grandja
* @since 5.2
*/
final class ObjectToBooleanConverter implements GenericConverter {
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Object.class, Boolean.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {
return null;
}
if (source instanceof Boolean) {
return source;
}
if (source instanceof String) {
return Boolean.valueOf((String) source);
}
return null;
}
}
| 1,434 | 27.137255 | 93 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/package-info.java | /*
* Copyright 2002-2017 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
*
* https://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.
*/
/**
* Core classes and interfaces providing support for OpenID Connect Core 1.0.
*/
package org.springframework.security.oauth2.core.oidc;
| 764 | 35.428571 | 77 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/StandardClaimNames.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc;
/**
* The names of the "Standard Claims" defined by the OpenID Connect Core 1.0
* specification that can be returned either in the UserInfo Response or the ID Token.
*
* @author Joe Grandja
* @since 5.0
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse">UserInfo
* Response</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
*/
public final class StandardClaimNames {
/**
* {@code sub} - the Subject identifier
*/
public static final String SUB = "sub";
/**
* {@code name} - the user's full name
*/
public static final String NAME = "name";
/**
* {@code given_name} - the user's given name(s) or first name(s)
*/
public static final String GIVEN_NAME = "given_name";
/**
* {@code family_name} - the user's surname(s) or last name(s)
*/
public static final String FAMILY_NAME = "family_name";
/**
* {@code middle_name} - the user's middle name(s)
*/
public static final String MIDDLE_NAME = "middle_name";
/**
* {@code nickname} - the user's nick name that may or may not be the same as the
* {@code given_name}
*/
public static final String NICKNAME = "nickname";
/**
* {@code preferred_username} - the preferred username that the user wishes to be
* referred to
*/
public static final String PREFERRED_USERNAME = "preferred_username";
/**
* {@code profile} - the URL of the user's profile page
*/
public static final String PROFILE = "profile";
/**
* {@code picture} - the URL of the user's profile picture
*/
public static final String PICTURE = "picture";
/**
* {@code website} - the URL of the user's web page or blog
*/
public static final String WEBSITE = "website";
/**
* {@code email} - the user's preferred e-mail address
*/
public static final String EMAIL = "email";
/**
* {@code email_verified} - {@code true} if the user's e-mail address has been
* verified, otherwise {@code false}
*/
public static final String EMAIL_VERIFIED = "email_verified";
/**
* {@code gender} - the user's gender
*/
public static final String GENDER = "gender";
/**
* {@code birthdate} - the user's birth date
*/
public static final String BIRTHDATE = "birthdate";
/**
* {@code zoneinfo} - the user's time zone
*/
public static final String ZONEINFO = "zoneinfo";
/**
* {@code locale} - the user's locale
*/
public static final String LOCALE = "locale";
/**
* {@code phone_number} - the user's preferred phone number
*/
public static final String PHONE_NUMBER = "phone_number";
/**
* {@code phone_number_verified} - {@code true} if the user's phone number has been
* verified, otherwise {@code false}
*/
public static final String PHONE_NUMBER_VERIFIED = "phone_number_verified";
/**
* {@code address} - the user's preferred postal address
*/
public static final String ADDRESS = "address";
/**
* {@code updated_at} - the time the user's information was last updated
*/
public static final String UPDATED_AT = "updated_at";
private StandardClaimNames() {
}
}
| 3,950 | 26.4375 | 86 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcIdToken.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AbstractOAuth2Token} representing an OpenID Connect Core
* 1.0 ID Token.
*
* <p>
* The {@code OidcIdToken} is a security token that contains "claims" about the
* authentication of an End-User by an Authorization Server.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractOAuth2Token
* @see IdTokenClaimAccessor
* @see StandardClaimAccessor
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
*/
public class OidcIdToken extends AbstractOAuth2Token implements IdTokenClaimAccessor {
private final Map<String, Object> claims;
/**
* Constructs a {@code OidcIdToken} using the provided parameters.
* @param tokenValue the ID Token value
* @param issuedAt the time at which the ID Token was issued {@code (iat)}
* @param expiresAt the expiration time {@code (exp)} on or after which the ID Token
* MUST NOT be accepted
* @param claims the claims about the authentication of the End-User
*/
public OidcIdToken(String tokenValue, Instant issuedAt, Instant expiresAt, Map<String, Object> claims) {
super(tokenValue, issuedAt, expiresAt);
Assert.notEmpty(claims, "claims cannot be empty");
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
}
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
/**
* Create a {@link Builder} based on the given token value
* @param tokenValue the token value to use
* @return the {@link Builder} for further configuration
* @since 5.3
*/
public static Builder withTokenValue(String tokenValue) {
return new Builder(tokenValue);
}
/**
* A builder for {@link OidcIdToken}s
*
* @author Josh Cummings
* @since 5.3
*/
public static final class Builder {
private String tokenValue;
private final Map<String, Object> claims = new LinkedHashMap<>();
private Builder(String tokenValue) {
this.tokenValue = tokenValue;
}
/**
* Use this token value in the resulting {@link OidcIdToken}
* @param tokenValue The token value to use
* @return the {@link Builder} for further configurations
*/
public Builder tokenValue(String tokenValue) {
this.tokenValue = tokenValue;
return this;
}
/**
* Use this claim in the resulting {@link OidcIdToken}
* @param name The claim name
* @param value The claim value
* @return the {@link Builder} for further configurations
*/
public Builder claim(String name, Object value) {
this.claims.put(name, value);
return this;
}
/**
* Provides access to every {@link #claim(String, Object)} declared so far with
* the possibility to add, replace, or remove.
* @param claimsConsumer the consumer
* @return the {@link Builder} for further configurations
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Use this access token hash in the resulting {@link OidcIdToken}
* @param accessTokenHash The access token hash to use
* @return the {@link Builder} for further configurations
*/
public Builder accessTokenHash(String accessTokenHash) {
return claim(IdTokenClaimNames.AT_HASH, accessTokenHash);
}
/**
* Use this audience in the resulting {@link OidcIdToken}
* @param audience The audience(s) to use
* @return the {@link Builder} for further configurations
*/
public Builder audience(Collection<String> audience) {
return claim(IdTokenClaimNames.AUD, audience);
}
/**
* Use this authentication {@link Instant} in the resulting {@link OidcIdToken}
* @param authenticatedAt The authentication {@link Instant} to use
* @return the {@link Builder} for further configurations
*/
public Builder authTime(Instant authenticatedAt) {
return claim(IdTokenClaimNames.AUTH_TIME, authenticatedAt);
}
/**
* Use this authentication context class reference in the resulting
* {@link OidcIdToken}
* @param authenticationContextClass The authentication context class reference to
* use
* @return the {@link Builder} for further configurations
*/
public Builder authenticationContextClass(String authenticationContextClass) {
return claim(IdTokenClaimNames.ACR, authenticationContextClass);
}
/**
* Use these authentication methods in the resulting {@link OidcIdToken}
* @param authenticationMethods The authentication methods to use
* @return the {@link Builder} for further configurations
*/
public Builder authenticationMethods(List<String> authenticationMethods) {
return claim(IdTokenClaimNames.AMR, authenticationMethods);
}
/**
* Use this authorization code hash in the resulting {@link OidcIdToken}
* @param authorizationCodeHash The authorization code hash to use
* @return the {@link Builder} for further configurations
*/
public Builder authorizationCodeHash(String authorizationCodeHash) {
return claim(IdTokenClaimNames.C_HASH, authorizationCodeHash);
}
/**
* Use this authorized party in the resulting {@link OidcIdToken}
* @param authorizedParty The authorized party to use
* @return the {@link Builder} for further configurations
*/
public Builder authorizedParty(String authorizedParty) {
return claim(IdTokenClaimNames.AZP, authorizedParty);
}
/**
* Use this expiration in the resulting {@link OidcIdToken}
* @param expiresAt The expiration to use
* @return the {@link Builder} for further configurations
*/
public Builder expiresAt(Instant expiresAt) {
return this.claim(IdTokenClaimNames.EXP, expiresAt);
}
/**
* Use this issued-at timestamp in the resulting {@link OidcIdToken}
* @param issuedAt The issued-at timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder issuedAt(Instant issuedAt) {
return this.claim(IdTokenClaimNames.IAT, issuedAt);
}
/**
* Use this issuer in the resulting {@link OidcIdToken}
* @param issuer The issuer to use
* @return the {@link Builder} for further configurations
*/
public Builder issuer(String issuer) {
return this.claim(IdTokenClaimNames.ISS, issuer);
}
/**
* Use this nonce in the resulting {@link OidcIdToken}
* @param nonce The nonce to use
* @return the {@link Builder} for further configurations
*/
public Builder nonce(String nonce) {
return this.claim(IdTokenClaimNames.NONCE, nonce);
}
/**
* Use this subject in the resulting {@link OidcIdToken}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(IdTokenClaimNames.SUB, subject);
}
/**
* Build the {@link OidcIdToken}
* @return The constructed {@link OidcIdToken}
*/
public OidcIdToken build() {
Instant iat = toInstant(this.claims.get(IdTokenClaimNames.IAT));
Instant exp = toInstant(this.claims.get(IdTokenClaimNames.EXP));
return new OidcIdToken(this.tokenValue, iat, exp, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
}
| 8,395 | 31.292308 | 105 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/DefaultAddressStandardClaim.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc;
import java.util.Map;
/**
* The default implementation of an {@link AddressStandardClaim Address Claim}.
*
* @author Joe Grandja
* @since 5.0
* @see AddressStandardClaim
*/
public final class DefaultAddressStandardClaim implements AddressStandardClaim {
private String formatted;
private String streetAddress;
private String locality;
private String region;
private String postalCode;
private String country;
private DefaultAddressStandardClaim() {
}
@Override
public String getFormatted() {
return this.formatted;
}
@Override
public String getStreetAddress() {
return this.streetAddress;
}
@Override
public String getLocality() {
return this.locality;
}
@Override
public String getRegion() {
return this.region;
}
@Override
public String getPostalCode() {
return this.postalCode;
}
@Override
public String getCountry() {
return this.country;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || !AddressStandardClaim.class.isAssignableFrom(obj.getClass())) {
return false;
}
AddressStandardClaim other = (AddressStandardClaim) obj;
if ((this.getFormatted() != null) ? !this.getFormatted().equals(other.getFormatted())
: other.getFormatted() != null) {
return false;
}
if ((this.getStreetAddress() != null) ? !this.getStreetAddress().equals(other.getStreetAddress())
: other.getStreetAddress() != null) {
return false;
}
if ((this.getLocality() != null) ? !this.getLocality().equals(other.getLocality())
: other.getLocality() != null) {
return false;
}
if ((this.getRegion() != null) ? !this.getRegion().equals(other.getRegion()) : other.getRegion() != null) {
return false;
}
if ((this.getPostalCode() != null) ? !this.getPostalCode().equals(other.getPostalCode())
: other.getPostalCode() != null) {
return false;
}
return (this.getCountry() != null) ? this.getCountry().equals(other.getCountry()) : other.getCountry() == null;
}
@Override
public int hashCode() {
int result = (this.getFormatted() != null) ? this.getFormatted().hashCode() : 0;
result = 31 * result + ((this.getStreetAddress() != null) ? this.getStreetAddress().hashCode() : 0);
result = 31 * result + ((this.getLocality() != null) ? this.getLocality().hashCode() : 0);
result = 31 * result + ((this.getRegion() != null) ? this.getRegion().hashCode() : 0);
result = 31 * result + ((this.getPostalCode() != null) ? this.getPostalCode().hashCode() : 0);
result = 31 * result + ((this.getCountry() != null) ? this.getCountry().hashCode() : 0);
return result;
}
/**
* A builder for {@link DefaultAddressStandardClaim}.
*/
public static class Builder {
private static final String FORMATTED_FIELD_NAME = "formatted";
private static final String STREET_ADDRESS_FIELD_NAME = "street_address";
private static final String LOCALITY_FIELD_NAME = "locality";
private static final String REGION_FIELD_NAME = "region";
private static final String POSTAL_CODE_FIELD_NAME = "postal_code";
private static final String COUNTRY_FIELD_NAME = "country";
private String formatted;
private String streetAddress;
private String locality;
private String region;
private String postalCode;
private String country;
/**
* Default constructor.
*/
public Builder() {
}
/**
* Constructs and initializes the address attributes using the provided
* {@code addressFields}.
* @param addressFields the fields used to initialize the address attributes
*/
public Builder(Map<String, Object> addressFields) {
this.formatted((String) addressFields.get(FORMATTED_FIELD_NAME));
this.streetAddress((String) addressFields.get(STREET_ADDRESS_FIELD_NAME));
this.locality((String) addressFields.get(LOCALITY_FIELD_NAME));
this.region((String) addressFields.get(REGION_FIELD_NAME));
this.postalCode((String) addressFields.get(POSTAL_CODE_FIELD_NAME));
this.country((String) addressFields.get(COUNTRY_FIELD_NAME));
}
/**
* Sets the full mailing address, formatted for display.
* @param formatted the full mailing address
* @return the {@link Builder}
*/
public Builder formatted(String formatted) {
this.formatted = formatted;
return this;
}
/**
* Sets the full street address, which may include house number, street name, P.O.
* Box, etc.
* @param streetAddress the full street address
* @return the {@link Builder}
*/
public Builder streetAddress(String streetAddress) {
this.streetAddress = streetAddress;
return this;
}
/**
* Sets the city or locality.
* @param locality the city or locality
* @return the {@link Builder}
*/
public Builder locality(String locality) {
this.locality = locality;
return this;
}
/**
* Sets the state, province, prefecture, or region.
* @param region the state, province, prefecture, or region
* @return the {@link Builder}
*/
public Builder region(String region) {
this.region = region;
return this;
}
/**
* Sets the zip code or postal code.
* @param postalCode the zip code or postal code
* @return the {@link Builder}
*/
public Builder postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Sets the country.
* @param country the country
* @return the {@link Builder}
*/
public Builder country(String country) {
this.country = country;
return this;
}
/**
* Builds a new {@link DefaultAddressStandardClaim}.
* @return a {@link AddressStandardClaim}
*/
public AddressStandardClaim build() {
DefaultAddressStandardClaim address = new DefaultAddressStandardClaim();
address.formatted = this.formatted;
address.streetAddress = this.streetAddress;
address.locality = this.locality;
address.region = this.region;
address.postalCode = this.postalCode;
address.country = this.country;
return address;
}
}
}
| 6,647 | 26.134694 | 113 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/StandardClaimAccessor.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc;
import java.time.Instant;
import java.util.Map;
import org.springframework.security.oauth2.core.ClaimAccessor;
import org.springframework.util.CollectionUtils;
/**
* A {@link ClaimAccessor} for the "Standard Claims" that can be returned either
* in the UserInfo Response or the ID Token.
*
* @author Joe Grandja
* @since 5.0
* @see ClaimAccessor
* @see StandardClaimNames
* @see OidcUserInfo
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse">UserInfo
* Response</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
*/
public interface StandardClaimAccessor extends ClaimAccessor {
/**
* Returns the Subject identifier {@code (sub)}.
* @return the Subject identifier
*/
default String getSubject() {
return this.getClaimAsString(StandardClaimNames.SUB);
}
/**
* Returns the user's full name {@code (name)} in displayable form.
* @return the user's full name
*/
default String getFullName() {
return this.getClaimAsString(StandardClaimNames.NAME);
}
/**
* Returns the user's given name(s) or first name(s) {@code (given_name)}.
* @return the user's given name(s)
*/
default String getGivenName() {
return this.getClaimAsString(StandardClaimNames.GIVEN_NAME);
}
/**
* Returns the user's surname(s) or last name(s) {@code (family_name)}.
* @return the user's family names(s)
*/
default String getFamilyName() {
return this.getClaimAsString(StandardClaimNames.FAMILY_NAME);
}
/**
* Returns the user's middle name(s) {@code (middle_name)}.
* @return the user's middle name(s)
*/
default String getMiddleName() {
return this.getClaimAsString(StandardClaimNames.MIDDLE_NAME);
}
/**
* Returns the user's nick name {@code (nickname)} that may or may not be the same as
* the {@code (given_name)}.
* @return the user's nick name
*/
default String getNickName() {
return this.getClaimAsString(StandardClaimNames.NICKNAME);
}
/**
* Returns the preferred username {@code (preferred_username)} that the user wishes to
* be referred to.
* @return the user's preferred user name
*/
default String getPreferredUsername() {
return this.getClaimAsString(StandardClaimNames.PREFERRED_USERNAME);
}
/**
* Returns the URL of the user's profile page {@code (profile)}.
* @return the URL of the user's profile page
*/
default String getProfile() {
return this.getClaimAsString(StandardClaimNames.PROFILE);
}
/**
* Returns the URL of the user's profile picture {@code (picture)}.
* @return the URL of the user's profile picture
*/
default String getPicture() {
return this.getClaimAsString(StandardClaimNames.PICTURE);
}
/**
* Returns the URL of the user's web page or blog {@code (website)}.
* @return the URL of the user's web page or blog
*/
default String getWebsite() {
return this.getClaimAsString(StandardClaimNames.WEBSITE);
}
/**
* Returns the user's preferred e-mail address {@code (email)}.
* @return the user's preferred e-mail address
*/
default String getEmail() {
return this.getClaimAsString(StandardClaimNames.EMAIL);
}
/**
* Returns {@code true} if the user's e-mail address has been verified
* {@code (email_verified)}, otherwise {@code false}.
* @return {@code true} if the user's e-mail address has been verified, otherwise
* {@code false}
*/
default Boolean getEmailVerified() {
return this.getClaimAsBoolean(StandardClaimNames.EMAIL_VERIFIED);
}
/**
* Returns the user's gender {@code (gender)}.
* @return the user's gender
*/
default String getGender() {
return this.getClaimAsString(StandardClaimNames.GENDER);
}
/**
* Returns the user's birth date {@code (birthdate)}.
* @return the user's birth date
*/
default String getBirthdate() {
return this.getClaimAsString(StandardClaimNames.BIRTHDATE);
}
/**
* Returns the user's time zone {@code (zoneinfo)}.
* @return the user's time zone
*/
default String getZoneInfo() {
return this.getClaimAsString(StandardClaimNames.ZONEINFO);
}
/**
* Returns the user's locale {@code (locale)}.
* @return the user's locale
*/
default String getLocale() {
return this.getClaimAsString(StandardClaimNames.LOCALE);
}
/**
* Returns the user's preferred phone number {@code (phone_number)}.
* @return the user's preferred phone number
*/
default String getPhoneNumber() {
return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER);
}
/**
* Returns {@code true} if the user's phone number has been verified
* {@code (phone_number_verified)}, otherwise {@code false}.
* @return {@code true} if the user's phone number has been verified, otherwise
* {@code false}
*/
default Boolean getPhoneNumberVerified() {
return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED);
}
/**
* Returns the user's preferred postal address {@code (address)}.
* @return the user's preferred postal address
*/
default AddressStandardClaim getAddress() {
Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS);
return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build()
: new DefaultAddressStandardClaim.Builder().build());
}
/**
* Returns the time the user's information was last updated {@code (updated_at)}.
* @return the time the user's information was last updated
*/
default Instant getUpdatedAt() {
return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT);
}
}
| 6,274 | 28.599057 | 114 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcUserInfo.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc;
import java.io.Serializable;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* A representation of a UserInfo Response that is returned from the OAuth 2.0 Protected
* Resource UserInfo Endpoint.
*
* <p>
* The {@code OidcUserInfo} contains a set of "Standard Claims" about the
* authentication of an End-User.
*
* @author Joe Grandja
* @since 5.0
* @see StandardClaimAccessor
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse">UserInfo
* Response</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#UserInfo">UserInfo Endpoint</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
*/
public class OidcUserInfo implements StandardClaimAccessor, Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Map<String, Object> claims;
/**
* Constructs a {@code OidcUserInfo} using the provided parameters.
* @param claims the claims about the authentication of the End-User
*/
public OidcUserInfo(Map<String, Object> claims) {
Assert.notEmpty(claims, "claims cannot be empty");
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
}
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OidcUserInfo that = (OidcUserInfo) obj;
return this.getClaims().equals(that.getClaims());
}
@Override
public int hashCode() {
return this.getClaims().hashCode();
}
/**
* Create a {@link Builder}
* @return the {@link Builder} for further configuration
* @since 5.3
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link OidcUserInfo}s
*
* @author Josh Cummings
* @since 5.3
*/
public static final class Builder {
private final Map<String, Object> claims = new LinkedHashMap<>();
private Builder() {
}
/**
* Use this claim in the resulting {@link OidcUserInfo}
* @param name The claim name
* @param value The claim value
* @return the {@link Builder} for further configurations
*/
public Builder claim(String name, Object value) {
this.claims.put(name, value);
return this;
}
/**
* Provides access to every {@link #claim(String, Object)} declared so far with
* the possibility to add, replace, or remove.
* @param claimsConsumer the consumer
* @return the {@link Builder} for further configurations
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Use this address in the resulting {@link OidcUserInfo}
* @param address The address to use
* @return the {@link Builder} for further configurations
*/
public Builder address(String address) {
return this.claim(StandardClaimNames.ADDRESS, address);
}
/**
* Use this birthdate in the resulting {@link OidcUserInfo}
* @param birthdate The birthdate to use
* @return the {@link Builder} for further configurations
*/
public Builder birthdate(String birthdate) {
return this.claim(StandardClaimNames.BIRTHDATE, birthdate);
}
/**
* Use this email in the resulting {@link OidcUserInfo}
* @param email The email to use
* @return the {@link Builder} for further configurations
*/
public Builder email(String email) {
return this.claim(StandardClaimNames.EMAIL, email);
}
/**
* Use this verified-email indicator in the resulting {@link OidcUserInfo}
* @param emailVerified The verified-email indicator to use
* @return the {@link Builder} for further configurations
*/
public Builder emailVerified(Boolean emailVerified) {
return this.claim(StandardClaimNames.EMAIL_VERIFIED, emailVerified);
}
/**
* Use this family name in the resulting {@link OidcUserInfo}
* @param familyName The family name to use
* @return the {@link Builder} for further configurations
*/
public Builder familyName(String familyName) {
return claim(StandardClaimNames.FAMILY_NAME, familyName);
}
/**
* Use this gender in the resulting {@link OidcUserInfo}
* @param gender The gender to use
* @return the {@link Builder} for further configurations
*/
public Builder gender(String gender) {
return this.claim(StandardClaimNames.GENDER, gender);
}
/**
* Use this given name in the resulting {@link OidcUserInfo}
* @param givenName The given name to use
* @return the {@link Builder} for further configurations
*/
public Builder givenName(String givenName) {
return claim(StandardClaimNames.GIVEN_NAME, givenName);
}
/**
* Use this locale in the resulting {@link OidcUserInfo}
* @param locale The locale to use
* @return the {@link Builder} for further configurations
*/
public Builder locale(String locale) {
return this.claim(StandardClaimNames.LOCALE, locale);
}
/**
* Use this middle name in the resulting {@link OidcUserInfo}
* @param middleName The middle name to use
* @return the {@link Builder} for further configurations
*/
public Builder middleName(String middleName) {
return claim(StandardClaimNames.MIDDLE_NAME, middleName);
}
/**
* Use this name in the resulting {@link OidcUserInfo}
* @param name The name to use
* @return the {@link Builder} for further configurations
*/
public Builder name(String name) {
return claim(StandardClaimNames.NAME, name);
}
/**
* Use this nickname in the resulting {@link OidcUserInfo}
* @param nickname The nickname to use
* @return the {@link Builder} for further configurations
*/
public Builder nickname(String nickname) {
return claim(StandardClaimNames.NICKNAME, nickname);
}
/**
* Use this picture in the resulting {@link OidcUserInfo}
* @param picture The picture to use
* @return the {@link Builder} for further configurations
*/
public Builder picture(String picture) {
return this.claim(StandardClaimNames.PICTURE, picture);
}
/**
* Use this phone number in the resulting {@link OidcUserInfo}
* @param phoneNumber The phone number to use
* @return the {@link Builder} for further configurations
*/
public Builder phoneNumber(String phoneNumber) {
return this.claim(StandardClaimNames.PHONE_NUMBER, phoneNumber);
}
/**
* Use this verified-phone-number indicator in the resulting {@link OidcUserInfo}
* @param phoneNumberVerified The verified-phone-number indicator to use
* @return the {@link Builder} for further configurations
* @since 5.8
*/
public Builder phoneNumberVerified(Boolean phoneNumberVerified) {
return this.claim(StandardClaimNames.PHONE_NUMBER_VERIFIED, phoneNumberVerified);
}
/**
* Use this preferred username in the resulting {@link OidcUserInfo}
* @param preferredUsername The preferred username to use
* @return the {@link Builder} for further configurations
*/
public Builder preferredUsername(String preferredUsername) {
return claim(StandardClaimNames.PREFERRED_USERNAME, preferredUsername);
}
/**
* Use this profile in the resulting {@link OidcUserInfo}
* @param profile The profile to use
* @return the {@link Builder} for further configurations
*/
public Builder profile(String profile) {
return claim(StandardClaimNames.PROFILE, profile);
}
/**
* Use this subject in the resulting {@link OidcUserInfo}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
return this.claim(StandardClaimNames.SUB, subject);
}
/**
* Use this updated-at {@link Instant} in the resulting {@link OidcUserInfo}
* @param updatedAt The updated-at {@link Instant} to use
* @return the {@link Builder} for further configurations
*/
public Builder updatedAt(String updatedAt) {
return this.claim(StandardClaimNames.UPDATED_AT, updatedAt);
}
/**
* Use this website in the resulting {@link OidcUserInfo}
* @param website The website to use
* @return the {@link Builder} for further configurations
*/
public Builder website(String website) {
return this.claim(StandardClaimNames.WEBSITE, website);
}
/**
* Use this zoneinfo in the resulting {@link OidcUserInfo}
* @param zoneinfo The zoneinfo to use
* @return the {@link Builder} for further configurations
*/
public Builder zoneinfo(String zoneinfo) {
return this.claim(StandardClaimNames.ZONEINFO, zoneinfo);
}
/**
* Build the {@link OidcUserInfo}
* @return The constructed {@link OidcUserInfo}
*/
public OidcUserInfo build() {
return new OidcUserInfo(this.claims);
}
}
}
| 9,818 | 29.493789 | 91 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/OidcScopes.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* The scope values defined by the OpenID Connect Core 1.0 specification that can be used
* to request {@link StandardClaimNames claims}.
* <p>
* The scope(s) associated to an {@link OAuth2AccessToken} determine what claims
* (resources) will be available when they are used to access OAuth 2.0 Protected
* Endpoints, such as the UserInfo Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see StandardClaimNames
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims">Requesting Claims
* using Scope Values</a>
*/
public final class OidcScopes {
/**
* The {@code openid} scope is required for OpenID Connect Authentication Requests.
*/
public static final String OPENID = "openid";
/**
* The {@code profile} scope requests access to the default profile claims, which are:
* {@code name, family_name, given_name, middle_name, nickname, preferred_username,
* profile, picture, website, gender, birthdate, zoneinfo, locale, updated_at}.
*/
public static final String PROFILE = "profile";
/**
* The {@code email} scope requests access to the {@code email} and
* {@code email_verified} claims.
*/
public static final String EMAIL = "email";
/**
* The {@code address} scope requests access to the {@code address} claim.
*/
public static final String ADDRESS = "address";
/**
* The {@code phone} scope requests access to the {@code phone_number} and
* {@code phone_number_verified} claims.
*/
public static final String PHONE = "phone";
private OidcScopes() {
}
}
| 2,314 | 31.605634 | 89 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/IdTokenClaimAccessor.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc;
import java.net.URL;
import java.time.Instant;
import java.util.List;
import org.springframework.security.oauth2.core.ClaimAccessor;
/**
* A {@link ClaimAccessor} for the "claims" that can be returned in the ID
* Token, which provides information about the authentication of an End-User by an
* Authorization Server.
*
* @author Joe Grandja
* @since 5.0
* @see ClaimAccessor
* @see StandardClaimAccessor
* @see StandardClaimNames
* @see IdTokenClaimNames
* @see OidcIdToken
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
*/
public interface IdTokenClaimAccessor extends StandardClaimAccessor {
/**
* Returns the Issuer identifier {@code (iss)}.
* @return the Issuer identifier
*/
default URL getIssuer() {
return this.getClaimAsURL(IdTokenClaimNames.ISS);
}
/**
* Returns the Subject identifier {@code (sub)}.
* @return the Subject identifier
*/
@Override
default String getSubject() {
return this.getClaimAsString(IdTokenClaimNames.SUB);
}
/**
* Returns the Audience(s) {@code (aud)} that this ID Token is intended for.
* @return the Audience(s) that this ID Token is intended for
*/
default List<String> getAudience() {
return this.getClaimAsStringList(IdTokenClaimNames.AUD);
}
/**
* Returns the Expiration time {@code (exp)} on or after which the ID Token MUST NOT
* be accepted.
* @return the Expiration time on or after which the ID Token MUST NOT be accepted
*/
default Instant getExpiresAt() {
return this.getClaimAsInstant(IdTokenClaimNames.EXP);
}
/**
* Returns the time at which the ID Token was issued {@code (iat)}.
* @return the time at which the ID Token was issued
*/
default Instant getIssuedAt() {
return this.getClaimAsInstant(IdTokenClaimNames.IAT);
}
/**
* Returns the time when the End-User authentication occurred {@code (auth_time)}.
* @return the time when the End-User authentication occurred
*/
default Instant getAuthenticatedAt() {
return this.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME);
}
/**
* Returns a {@code String} value {@code (nonce)} used to associate a Client session
* with an ID Token, and to mitigate replay attacks.
* @return the nonce used to associate a Client session with an ID Token
*/
default String getNonce() {
return this.getClaimAsString(IdTokenClaimNames.NONCE);
}
/**
* Returns the Authentication Context Class Reference {@code (acr)}.
* @return the Authentication Context Class Reference
*/
default String getAuthenticationContextClass() {
return this.getClaimAsString(IdTokenClaimNames.ACR);
}
/**
* Returns the Authentication Methods References {@code (amr)}.
* @return the Authentication Methods References
*/
default List<String> getAuthenticationMethods() {
return this.getClaimAsStringList(IdTokenClaimNames.AMR);
}
/**
* Returns the Authorized party {@code (azp)} to which the ID Token was issued.
* @return the Authorized party to which the ID Token was issued
*/
default String getAuthorizedParty() {
return this.getClaimAsString(IdTokenClaimNames.AZP);
}
/**
* Returns the Access Token hash value {@code (at_hash)}.
* @return the Access Token hash value
*/
default String getAccessTokenHash() {
return this.getClaimAsString(IdTokenClaimNames.AT_HASH);
}
/**
* Returns the Authorization Code hash value {@code (c_hash)}.
* @return the Authorization Code hash value
*/
default String getAuthorizationCodeHash() {
return this.getClaimAsString(IdTokenClaimNames.C_HASH);
}
}
| 4,390 | 29.282759 | 85 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/IdTokenClaimNames.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc;
/**
* The names of the "claims" defined by the OpenID Connect Core 1.0
* specification that can be returned in the ID Token.
*
* @author Joe Grandja
* @since 5.0
* @see OidcIdToken
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
*/
public final class IdTokenClaimNames {
/**
* {@code iss} - the Issuer identifier
*/
public static final String ISS = "iss";
/**
* {@code sub} - the Subject identifier
*/
public static final String SUB = "sub";
/**
* {@code aud} - the Audience(s) that the ID Token is intended for
*/
public static final String AUD = "aud";
/**
* {@code exp} - the Expiration time on or after which the ID Token MUST NOT be
* accepted
*/
public static final String EXP = "exp";
/**
* {@code iat} - the time at which the ID Token was issued
*/
public static final String IAT = "iat";
/**
* {@code auth_time} - the time when the End-User authentication occurred
*/
public static final String AUTH_TIME = "auth_time";
/**
* {@code nonce} - a {@code String} value used to associate a Client session with an
* ID Token, and to mitigate replay attacks.
*/
public static final String NONCE = "nonce";
/**
* {@code acr} - the Authentication Context Class Reference
*/
public static final String ACR = "acr";
/**
* {@code amr} - the Authentication Methods References
*/
public static final String AMR = "amr";
/**
* {@code azp} - the Authorized party to which the ID Token was issued
*/
public static final String AZP = "azp";
/**
* {@code at_hash} - the Access Token hash value
*/
public static final String AT_HASH = "at_hash";
/**
* {@code c_hash} - the Authorization Code hash value
*/
public static final String C_HASH = "c_hash";
private IdTokenClaimNames() {
}
}
| 2,529 | 24.816327 | 85 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/AddressStandardClaim.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc;
/**
* The Address Claim represents a physical mailing address defined by the OpenID Connect
* Core 1.0 specification that can be returned either in the UserInfo Response or the ID
* Token.
*
* @author Joe Grandja
* @since 5.0
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim">Address Claim</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse">UserInfo
* Response</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
*/
public interface AddressStandardClaim {
/**
* Returns the full mailing address, formatted for display.
* @return the full mailing address
*/
String getFormatted();
/**
* Returns the full street address, which may include house number, street name, P.O.
* Box, etc.
* @return the full street address
*/
String getStreetAddress();
/**
* Returns the city or locality.
* @return the city or locality
*/
String getLocality();
/**
* Returns the state, province, prefecture, or region.
* @return the state, province, prefecture, or region
*/
String getRegion();
/**
* Returns the zip code or postal code.
* @return the zip code or postal code
*/
String getPostalCode();
/**
* Returns the country.
* @return the country
*/
String getCountry();
}
| 2,080 | 27.121622 | 89 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/package-info.java | /*
* Copyright 2002-2017 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
*
* https://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.
*/
/**
* Provides a model for an OpenID Connect Core 1.0 representation of a user
* {@code Principal}.
*/
package org.springframework.security.oauth2.core.oidc.user;
| 789 | 34.909091 | 75 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUserAuthority.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc.user;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.util.Assert;
/**
* A {@link GrantedAuthority} that may be associated to an {@link OidcUser}.
*
* @author Joe Grandja
* @since 5.0
* @see OidcUser
*/
public class OidcUserAuthority extends OAuth2UserAuthority {
private final OidcIdToken idToken;
private final OidcUserInfo userInfo;
/**
* Constructs a {@code OidcUserAuthority} using the provided parameters.
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
*/
public OidcUserAuthority(OidcIdToken idToken) {
this(idToken, null);
}
/**
* Constructs a {@code OidcUserAuthority} using the provided parameters and defaults
* {@link #getAuthority()} to {@code OIDC_USER}.
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
*/
public OidcUserAuthority(OidcIdToken idToken, OidcUserInfo userInfo) {
this("OIDC_USER", idToken, userInfo);
}
/**
* Constructs a {@code OidcUserAuthority} using the provided parameters.
* @param authority the authority granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
*/
public OidcUserAuthority(String authority, OidcIdToken idToken, OidcUserInfo userInfo) {
super(authority, collectClaims(idToken, userInfo));
this.idToken = idToken;
this.userInfo = userInfo;
}
/**
* Returns the {@link OidcIdToken ID Token} containing claims about the user.
* @return the {@link OidcIdToken} containing claims about the user.
*/
public OidcIdToken getIdToken() {
return this.idToken;
}
/**
* Returns the {@link OidcUserInfo UserInfo} containing claims about the user, may be
* {@code null}.
* @return the {@link OidcUserInfo} containing claims about the user, or {@code null}
*/
public OidcUserInfo getUserInfo() {
return this.userInfo;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
if (!super.equals(obj)) {
return false;
}
OidcUserAuthority that = (OidcUserAuthority) obj;
if (!this.getIdToken().equals(that.getIdToken())) {
return false;
}
return (this.getUserInfo() != null) ? this.getUserInfo().equals(that.getUserInfo())
: that.getUserInfo() == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + this.getIdToken().hashCode();
result = 31 * result + ((this.getUserInfo() != null) ? this.getUserInfo().hashCode() : 0);
return result;
}
static Map<String, Object> collectClaims(OidcIdToken idToken, OidcUserInfo userInfo) {
Assert.notNull(idToken, "idToken cannot be null");
Map<String, Object> claims = new HashMap<>();
if (userInfo != null) {
claims.putAll(userInfo.getClaims());
}
claims.putAll(idToken.getClaims());
return claims;
}
}
| 4,076 | 30.851563 | 92 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/DefaultOidcUser.java | /*
* 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
*
* https://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.core.oidc.user;
import java.util.Collection;
import java.util.Map;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
/**
* The default implementation of an {@link OidcUser}.
*
* <p>
* The default claim used for accessing the "name" of the user {@code Principal}
* from {@link #getClaims()} is {@link IdTokenClaimNames#SUB}.
*
* @author Joe Grandja
* @author Vedran Pavic
* @since 5.0
* @see OidcUser
* @see DefaultOAuth2User
* @see OidcIdToken
* @see OidcUserInfo
*/
public class DefaultOidcUser extends DefaultOAuth2User implements OidcUser {
private final OidcIdToken idToken;
private final OidcUserInfo userInfo;
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken) {
this(authorities, idToken, IdTokenClaimNames.SUB);
}
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param nameAttributeKey the key used to access the user's "name" from
* {@link #getAttributes()}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
String nameAttributeKey) {
this(authorities, idToken, null, nameAttributeKey);
}
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
OidcUserInfo userInfo) {
this(authorities, idToken, userInfo, IdTokenClaimNames.SUB);
}
/**
* Constructs a {@code DefaultOidcUser} using the provided parameters.
* @param authorities the authorities granted to the user
* @param idToken the {@link OidcIdToken ID Token} containing claims about the user
* @param userInfo the {@link OidcUserInfo UserInfo} containing claims about the user,
* may be {@code null}
* @param nameAttributeKey the key used to access the user's "name" from
* {@link #getAttributes()}
*/
public DefaultOidcUser(Collection<? extends GrantedAuthority> authorities, OidcIdToken idToken,
OidcUserInfo userInfo, String nameAttributeKey) {
super(authorities, OidcUserAuthority.collectClaims(idToken, userInfo), nameAttributeKey);
this.idToken = idToken;
this.userInfo = userInfo;
}
@Override
public Map<String, Object> getClaims() {
return this.getAttributes();
}
@Override
public OidcIdToken getIdToken() {
return this.idToken;
}
@Override
public OidcUserInfo getUserInfo() {
return this.userInfo;
}
}
| 4,027 | 34.333333 | 98 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/user/OidcUser.java | /*
* Copyright 2002-2017 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
*
* https://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.core.oidc.user;
import java.util.Map;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimAccessor;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.StandardClaimAccessor;
import org.springframework.security.oauth2.core.user.OAuth2User;
/**
* A representation of a user {@code Principal} that is registered with an OpenID Connect
* 1.0 Provider.
*
* <p>
* An {@code OidcUser} contains "claims" about the authentication of the
* End-User. The claims are aggregated from the {@link OidcIdToken} and the
* {@link OidcUserInfo} (if available).
*
* <p>
* Implementation instances of this interface represent an {@link AuthenticatedPrincipal}
* which is associated to an {@link Authentication} object and may be accessed via
* {@link Authentication#getPrincipal()}.
*
* @author Joe Grandja
* @since 5.0
* @see DefaultOidcUser
* @see OAuth2User
* @see OidcIdToken
* @see OidcUserInfo
* @see IdTokenClaimAccessor
* @see StandardClaimAccessor
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDToken">ID Token</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims">Standard
* Claims</a>
*/
public interface OidcUser extends OAuth2User, IdTokenClaimAccessor {
/**
* Returns the claims about the user. The claims are aggregated from
* {@link #getIdToken()} and {@link #getUserInfo()} (if available).
* @return a {@code Map} of claims about the user
*/
@Override
Map<String, Object> getClaims();
/**
* Returns the {@link OidcUserInfo UserInfo} containing claims about the user.
* @return the {@link OidcUserInfo} containing claims about the user.
*/
OidcUserInfo getUserInfo();
/**
* Returns the {@link OidcIdToken ID Token} containing claims about the user.
* @return the {@link OidcIdToken} containing claims about the user.
*/
OidcIdToken getIdToken();
}
| 2,850 | 34.6375 | 89 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/endpoint/package-info.java | /*
* Copyright 2002-2017 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
*
* https://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.
*/
/**
* Support classes that model the OpenID Connect Core 1.0 Request and Response messages
* from the Authorization Endpoint and Token Endpoint.
*/
package org.springframework.security.oauth2.core.oidc.endpoint;
| 838 | 37.136364 | 87 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/oidc/endpoint/OidcParameterNames.java | /*
* Copyright 2002-2022 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
*
* https://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.core.oidc.endpoint;
/**
* Standard parameter names defined in the OAuth Parameters Registry and used by the
* authorization endpoint and token endpoint.
*
* @author Joe Grandja
* @author Mark Heckler
* @since 5.0
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#OAuthParametersRegistry">18.2
* OAuth Parameters Registration</a>
*/
public final class OidcParameterNames {
/**
* {@code id_token} - used in the Access Token Response.
*/
public static final String ID_TOKEN = "id_token";
/**
* {@code nonce} - used in the Authentication Request.
*/
public static final String NONCE = "nonce";
private OidcParameterNames() {
}
}
| 1,360 | 28.586957 | 87 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2DeviceAuthorizationResponse.java | /*
* Copyright 2002-2023 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
*
* https://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.core.endpoint;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Map;
import org.springframework.security.oauth2.core.OAuth2DeviceCode;
import org.springframework.security.oauth2.core.OAuth2UserCode;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* A representation of an OAuth 2.0 Device Authorization Response.
*
* @author Steve Riesenberg
* @since 6.1
* @see OAuth2DeviceCode
* @see OAuth2UserCode
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc8628#section-3.2">Section
* 3.2 Device Authorization Response</a>
*/
public final class OAuth2DeviceAuthorizationResponse {
private OAuth2DeviceCode deviceCode;
private OAuth2UserCode userCode;
private String verificationUri;
private String verificationUriComplete;
private long interval;
private Map<String, Object> additionalParameters;
private OAuth2DeviceAuthorizationResponse() {
}
/**
* Returns the {@link OAuth2DeviceCode Device Code}.
* @return the {@link OAuth2DeviceCode}
*/
public OAuth2DeviceCode getDeviceCode() {
return this.deviceCode;
}
/**
* Returns the {@link OAuth2UserCode User Code}.
* @return the {@link OAuth2UserCode}
*/
public OAuth2UserCode getUserCode() {
return this.userCode;
}
/**
* Returns the end-user verification URI.
* @return the end-user verification URI
*/
public String getVerificationUri() {
return this.verificationUri;
}
/**
* Returns the end-user verification URI that includes the user code.
* @return the end-user verification URI that includes the user code
*/
public String getVerificationUriComplete() {
return this.verificationUriComplete;
}
/**
* Returns the minimum amount of time (in seconds) that the client should wait between
* polling requests to the token endpoint.
* @return the minimum amount of time between polling requests
*/
public long getInterval() {
return this.interval;
}
/**
* Returns the additional parameters returned in the response.
* @return a {@code Map} of the additional parameters returned in the response, may be
* empty.
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
/**
* Returns a new {@link Builder}, initialized with the provided device code and user
* code values.
* @param deviceCode the value of the device code
* @param userCode the value of the user code
* @return the {@link Builder}
*/
public static Builder with(String deviceCode, String userCode) {
Assert.hasText(deviceCode, "deviceCode cannot be empty");
Assert.hasText(userCode, "userCode cannot be empty");
return new Builder(deviceCode, userCode);
}
/**
* Returns a new {@link Builder}, initialized with the provided device code and user
* code.
* @param deviceCode the {@link OAuth2DeviceCode}
* @param userCode the {@link OAuth2UserCode}
* @return the {@link Builder}
*/
public static Builder with(OAuth2DeviceCode deviceCode, OAuth2UserCode userCode) {
Assert.notNull(deviceCode, "deviceCode cannot be null");
Assert.notNull(userCode, "userCode cannot be null");
return new Builder(deviceCode, userCode);
}
/**
* A builder for {@link OAuth2DeviceAuthorizationResponse}.
*/
public static final class Builder {
private final String deviceCode;
private final String userCode;
private String verificationUri;
private String verificationUriComplete;
private long expiresIn;
private long interval;
private Map<String, Object> additionalParameters;
private Builder(OAuth2DeviceCode deviceCode, OAuth2UserCode userCode) {
this.deviceCode = deviceCode.getTokenValue();
this.userCode = userCode.getTokenValue();
this.expiresIn = ChronoUnit.SECONDS.between(deviceCode.getIssuedAt(), deviceCode.getExpiresAt());
}
private Builder(String deviceCode, String userCode) {
this.deviceCode = deviceCode;
this.userCode = userCode;
}
/**
* Sets the end-user verification URI.
* @param verificationUri the end-user verification URI
* @return the {@link Builder}
*/
public Builder verificationUri(String verificationUri) {
this.verificationUri = verificationUri;
return this;
}
/**
* Sets the end-user verification URI that includes the user code.
* @param verificationUriComplete the end-user verification URI that includes the
* user code
* @return the {@link Builder}
*/
public Builder verificationUriComplete(String verificationUriComplete) {
this.verificationUriComplete = verificationUriComplete;
return this;
}
/**
* Sets the lifetime (in seconds) of the device code and user code.
* @param expiresIn the lifetime (in seconds) of the device code and user code
* @return the {@link Builder}
*/
public Builder expiresIn(long expiresIn) {
this.expiresIn = expiresIn;
return this;
}
/**
* Sets the minimum amount of time (in seconds) that the client should wait
* between polling requests to the token endpoint.
* @param interval the minimum amount of time between polling requests
* @return the {@link Builder}
*/
public Builder interval(long interval) {
this.interval = interval;
return this;
}
/**
* Sets the additional parameters returned in the response.
* @param additionalParameters the additional parameters returned in the response
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
return this;
}
/**
* Builds a new {@link OAuth2DeviceAuthorizationResponse}.
* @return a {@link OAuth2DeviceAuthorizationResponse}
*/
public OAuth2DeviceAuthorizationResponse build() {
Assert.hasText(this.verificationUri, "verificationUri cannot be empty");
Assert.isTrue(this.expiresIn > 0, "expiresIn must be greater than zero");
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plusSeconds(this.expiresIn);
OAuth2DeviceCode deviceCode = new OAuth2DeviceCode(this.deviceCode, issuedAt, expiresAt);
OAuth2UserCode userCode = new OAuth2UserCode(this.userCode, issuedAt, expiresAt);
OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse = new OAuth2DeviceAuthorizationResponse();
deviceAuthorizationResponse.deviceCode = deviceCode;
deviceAuthorizationResponse.userCode = userCode;
deviceAuthorizationResponse.verificationUri = this.verificationUri;
deviceAuthorizationResponse.verificationUriComplete = this.verificationUriComplete;
deviceAuthorizationResponse.interval = this.interval;
deviceAuthorizationResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return deviceAuthorizationResponse;
}
}
}
| 7,566 | 30.139918 | 107 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/package-info.java | /*
* Copyright 2002-2017 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
*
* https://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.
*/
/**
* Support classes that model the OAuth 2.0 Request and Response messages from the
* Authorization Endpoint and Token Endpoint.
*/
package org.springframework.security.oauth2.core.endpoint;
| 819 | 36.272727 | 82 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/PkceParameterNames.java | /*
* Copyright 2002-2022 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
*
* https://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.core.endpoint;
/**
* Standard parameter names defined in the OAuth Parameters Registry and used by the
* authorization endpoint and token endpoint.
*
* @author Stephen Doxsee
* @author Kevin Bolduc
* @since 5.2
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7636#section-6.1">6.1
* OAuth Parameters Registry</a>
*/
public final class PkceParameterNames {
/**
* {@code code_challenge} - used in Authorization Request.
*/
public static final String CODE_CHALLENGE = "code_challenge";
/**
* {@code code_challenge_method} - used in Authorization Request.
*/
public static final String CODE_CHALLENGE_METHOD = "code_challenge_method";
/**
* {@code code_verifier} - used in Token Request.
*/
public static final String CODE_VERIFIER = "code_verifier";
private PkceParameterNames() {
}
}
| 1,499 | 29 | 85 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationExchange.java | /*
* Copyright 2002-2017 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
*
* https://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.core.endpoint;
import org.springframework.util.Assert;
/**
* An "exchange" of an OAuth 2.0 Authorization Request and Response for the
* authorization code grant type.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationResponse
*/
public final class OAuth2AuthorizationExchange {
private final OAuth2AuthorizationRequest authorizationRequest;
private final OAuth2AuthorizationResponse authorizationResponse;
/**
* Constructs a new {@code OAuth2AuthorizationExchange} with the provided
* Authorization Request and Authorization Response.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest Authorization
* Request}
* @param authorizationResponse the {@link OAuth2AuthorizationResponse Authorization
* Response}
*/
public OAuth2AuthorizationExchange(OAuth2AuthorizationRequest authorizationRequest,
OAuth2AuthorizationResponse authorizationResponse) {
Assert.notNull(authorizationRequest, "authorizationRequest cannot be null");
Assert.notNull(authorizationResponse, "authorizationResponse cannot be null");
this.authorizationRequest = authorizationRequest;
this.authorizationResponse = authorizationResponse;
}
/**
* Returns the {@link OAuth2AuthorizationRequest Authorization Request}.
* @return the {@link OAuth2AuthorizationRequest}
*/
public OAuth2AuthorizationRequest getAuthorizationRequest() {
return this.authorizationRequest;
}
/**
* Returns the {@link OAuth2AuthorizationResponse Authorization Response}.
* @return the {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse getAuthorizationResponse() {
return this.authorizationResponse;
}
}
| 2,376 | 33.449275 | 85 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponseType.java | /*
* Copyright 2002-2022 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
*
* https://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.core.endpoint;
import java.io.Serializable;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.util.Assert;
/**
* The {@code response_type} parameter is consumed by the authorization endpoint which is
* used by the authorization code grant type. The client sets the {@code response_type}
* parameter with the desired grant type before initiating the authorization request.
*
* <p>
* The {@code response_type} parameter value may be "code" for requesting an
* authorization code.
*
* @author Joe Grandja
* @since 5.0
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-3.1.1">Section 3.1.1 Response Type</a>
*/
public final class OAuth2AuthorizationResponseType implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public static final OAuth2AuthorizationResponseType CODE = new OAuth2AuthorizationResponseType("code");
private final String value;
public OAuth2AuthorizationResponseType(String value) {
Assert.hasText(value, "value cannot be empty");
this.value = value;
}
/**
* Returns the value of the authorization response type.
* @return the value of the authorization response type
*/
public String getValue() {
return this.value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
OAuth2AuthorizationResponseType that = (OAuth2AuthorizationResponseType) obj;
return this.getValue().equals(that.getValue());
}
@Override
public int hashCode() {
return this.getValue().hashCode();
}
}
| 2,372 | 29.818182 | 104 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationRequest.java | /*
* Copyright 2002-2022 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
*
* https://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.core.endpoint;
import java.io.Serializable;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriBuilder;
import org.springframework.web.util.UriUtils;
/**
* A representation of an OAuth 2.0 Authorization Request for the authorization code grant
* type.
*
* @author Joe Grandja
* @since 5.0
* @see AuthorizationGrantType
* @see OAuth2AuthorizationResponseType
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Code
* Grant Request</a>
*/
public final class OAuth2AuthorizationRequest implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String authorizationUri;
private AuthorizationGrantType authorizationGrantType;
private OAuth2AuthorizationResponseType responseType;
private String clientId;
private String redirectUri;
private Set<String> scopes;
private String state;
private Map<String, Object> additionalParameters;
private String authorizationRequestUri;
private Map<String, Object> attributes;
private OAuth2AuthorizationRequest() {
}
/**
* Returns the uri for the authorization endpoint.
* @return the uri for the authorization endpoint
*/
public String getAuthorizationUri() {
return this.authorizationUri;
}
/**
* Returns the {@link AuthorizationGrantType grant type}.
* @return the {@link AuthorizationGrantType}
*/
public AuthorizationGrantType getGrantType() {
return this.authorizationGrantType;
}
/**
* Returns the {@link OAuth2AuthorizationResponseType response type}.
* @return the {@link OAuth2AuthorizationResponseType}
*/
public OAuth2AuthorizationResponseType getResponseType() {
return this.responseType;
}
/**
* Returns the client identifier.
* @return the client identifier
*/
public String getClientId() {
return this.clientId;
}
/**
* Returns the uri for the redirection endpoint.
* @return the uri for the redirection endpoint
*/
public String getRedirectUri() {
return this.redirectUri;
}
/**
* Returns the scope(s).
* @return the scope(s), or an empty {@code Set} if not available
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the state.
* @return the state
*/
public String getState() {
return this.state;
}
/**
* Returns the additional parameter(s) used in the request.
* @return a {@code Map} of the additional parameter(s), or an empty {@code Map} if
* not available
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
/**
* Returns the attribute(s) associated to the request.
* @return a {@code Map} of the attribute(s), or an empty {@code Map} if not available
* @since 5.2
*/
public Map<String, Object> getAttributes() {
return this.attributes;
}
/**
* Returns the value of an attribute associated to the request.
* @param <T> the type of the attribute
* @param name the name of the attribute
* @return the value of the attribute associated to the request, or {@code null} if
* not available
* @since 5.2
*/
@SuppressWarnings("unchecked")
public <T> T getAttribute(String name) {
return (T) this.getAttributes().get(name);
}
/**
* Returns the {@code URI} string representation of the OAuth 2.0 Authorization
* Request.
*
* <p>
* <b>NOTE:</b> The {@code URI} string is encoded in the
* {@code application/x-www-form-urlencoded} MIME format.
* @return the {@code URI} string representation of the OAuth 2.0 Authorization
* Request
* @since 5.1
*/
public String getAuthorizationRequestUri() {
return this.authorizationRequestUri;
}
/**
* Returns a new {@link Builder}, initialized with the authorization code grant type.
* @return the {@link Builder}
*/
public static Builder authorizationCode() {
return new Builder(AuthorizationGrantType.AUTHORIZATION_CODE);
}
/**
* Returns a new {@link Builder}, initialized with the values from the provided
* {@code authorizationRequest}.
* @param authorizationRequest the authorization request used for initializing the
* {@link Builder}
* @return the {@link Builder}
* @since 5.1
*/
public static Builder from(OAuth2AuthorizationRequest authorizationRequest) {
Assert.notNull(authorizationRequest, "authorizationRequest cannot be null");
// @formatter:off
return new Builder(authorizationRequest.getGrantType())
.authorizationUri(authorizationRequest.getAuthorizationUri())
.clientId(authorizationRequest.getClientId())
.redirectUri(authorizationRequest.getRedirectUri())
.scopes(authorizationRequest.getScopes())
.state(authorizationRequest.getState())
.additionalParameters(authorizationRequest.getAdditionalParameters())
.attributes(authorizationRequest.getAttributes());
// @formatter:on
}
/**
* A builder for {@link OAuth2AuthorizationRequest}.
*/
public static final class Builder {
private String authorizationUri;
private AuthorizationGrantType authorizationGrantType;
private OAuth2AuthorizationResponseType responseType;
private String clientId;
private String redirectUri;
private Set<String> scopes;
private String state;
private Map<String, Object> additionalParameters = new LinkedHashMap<>();
private Consumer<Map<String, Object>> parametersConsumer = (params) -> {
};
private Map<String, Object> attributes = new LinkedHashMap<>();
private String authorizationRequestUri;
private Function<UriBuilder, URI> authorizationRequestUriFunction = (builder) -> builder.build();
private final DefaultUriBuilderFactory uriBuilderFactory;
private Builder(AuthorizationGrantType authorizationGrantType) {
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
this.authorizationGrantType = authorizationGrantType;
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) {
this.responseType = OAuth2AuthorizationResponseType.CODE;
}
this.uriBuilderFactory = new DefaultUriBuilderFactory();
// The supplied authorizationUri may contain encoded parameters
// so disable encoding in UriBuilder and instead apply encoding within this
// builder
this.uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
}
/**
* Sets the uri for the authorization endpoint.
* @param authorizationUri the uri for the authorization endpoint
* @return the {@link Builder}
*/
public Builder authorizationUri(String authorizationUri) {
this.authorizationUri = authorizationUri;
return this;
}
/**
* Sets the client identifier.
* @param clientId the client identifier
* @return the {@link Builder}
*/
public Builder clientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* Sets the uri for the redirection endpoint.
* @param redirectUri the uri for the redirection endpoint
* @return the {@link Builder}
*/
public Builder redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* Sets the scope(s).
* @param scope the scope(s)
* @return the {@link Builder}
*/
public Builder scope(String... scope) {
if (scope != null && scope.length > 0) {
return scopes(new LinkedHashSet<>(Arrays.asList(scope)));
}
return this;
}
/**
* Sets the scope(s).
* @param scopes the scope(s)
* @return the {@link Builder}
*/
public Builder scopes(Set<String> scopes) {
this.scopes = scopes;
return this;
}
/**
* Sets the state.
* @param state the state
* @return the {@link Builder}
*/
public Builder state(String state) {
this.state = state;
return this;
}
/**
* Sets the additional parameter(s) used in the request.
* @param additionalParameters the additional parameter(s) used in the request
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
if (!CollectionUtils.isEmpty(additionalParameters)) {
this.additionalParameters.putAll(additionalParameters);
}
return this;
}
/**
* A {@code Consumer} to be provided access to the additional parameter(s)
* allowing the ability to add, replace, or remove.
* @param additionalParametersConsumer a {@code Consumer} of the additional
* parameters
* @since 5.3
*/
public Builder additionalParameters(Consumer<Map<String, Object>> additionalParametersConsumer) {
if (additionalParametersConsumer != null) {
additionalParametersConsumer.accept(this.additionalParameters);
}
return this;
}
/**
* A {@code Consumer} to be provided access to all the parameters allowing the
* ability to add, replace, or remove.
* @param parametersConsumer a {@code Consumer} of all the parameters
* @since 5.3
*/
public Builder parameters(Consumer<Map<String, Object>> parametersConsumer) {
if (parametersConsumer != null) {
this.parametersConsumer = parametersConsumer;
}
return this;
}
/**
* Sets the attributes associated to the request.
* @param attributes the attributes associated to the request
* @return the {@link Builder}
* @since 5.2
*/
public Builder attributes(Map<String, Object> attributes) {
if (!CollectionUtils.isEmpty(attributes)) {
this.attributes.putAll(attributes);
}
return this;
}
/**
* A {@code Consumer} to be provided access to the attribute(s) allowing the
* ability to add, replace, or remove.
* @param attributesConsumer a {@code Consumer} of the attribute(s)
* @since 5.3
*/
public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
if (attributesConsumer != null) {
attributesConsumer.accept(this.attributes);
}
return this;
}
/**
* Sets the {@code URI} string representation of the OAuth 2.0 Authorization
* Request.
*
* <p>
* <b>NOTE:</b> The {@code URI} string is <b>required</b> to be encoded in the
* {@code application/x-www-form-urlencoded} MIME format.
* @param authorizationRequestUri the {@code URI} string representation of the
* OAuth 2.0 Authorization Request
* @return the {@link Builder}
* @since 5.1
*/
public Builder authorizationRequestUri(String authorizationRequestUri) {
this.authorizationRequestUri = authorizationRequestUri;
return this;
}
/**
* A {@code Function} to be provided a {@code UriBuilder} representation of the
* OAuth 2.0 Authorization Request allowing for further customizations.
* @param authorizationRequestUriFunction a {@code Function} to be provided a
* {@code UriBuilder} representation of the OAuth 2.0 Authorization Request
* @since 5.3
*/
public Builder authorizationRequestUri(Function<UriBuilder, URI> authorizationRequestUriFunction) {
if (authorizationRequestUriFunction != null) {
this.authorizationRequestUriFunction = authorizationRequestUriFunction;
}
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationRequest}.
* @return a {@link OAuth2AuthorizationRequest}
*/
public OAuth2AuthorizationRequest build() {
Assert.hasText(this.authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(this.clientId, "clientId cannot be empty");
OAuth2AuthorizationRequest authorizationRequest = new OAuth2AuthorizationRequest();
authorizationRequest.authorizationUri = this.authorizationUri;
authorizationRequest.authorizationGrantType = this.authorizationGrantType;
authorizationRequest.responseType = this.responseType;
authorizationRequest.clientId = this.clientId;
authorizationRequest.redirectUri = this.redirectUri;
authorizationRequest.state = this.state;
authorizationRequest.scopes = Collections.unmodifiableSet(
CollectionUtils.isEmpty(this.scopes) ? Collections.emptySet() : new LinkedHashSet<>(this.scopes));
authorizationRequest.additionalParameters = Collections.unmodifiableMap(this.additionalParameters);
authorizationRequest.attributes = Collections.unmodifiableMap(this.attributes);
authorizationRequest.authorizationRequestUri = StringUtils.hasText(this.authorizationRequestUri)
? this.authorizationRequestUri : this.buildAuthorizationRequestUri();
return authorizationRequest;
}
private String buildAuthorizationRequestUri() {
Map<String, Object> parameters = getParameters(); // Not encoded
this.parametersConsumer.accept(parameters);
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
parameters.forEach((k, v) -> queryParams.set(encodeQueryParam(k), encodeQueryParam(String.valueOf(v)))); // Encoded
UriBuilder uriBuilder = this.uriBuilderFactory.uriString(this.authorizationUri).queryParams(queryParams);
return this.authorizationRequestUriFunction.apply(uriBuilder).toString();
}
private Map<String, Object> getParameters() {
Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put(OAuth2ParameterNames.RESPONSE_TYPE, this.responseType.getValue());
parameters.put(OAuth2ParameterNames.CLIENT_ID, this.clientId);
if (!CollectionUtils.isEmpty(this.scopes)) {
parameters.put(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.scopes, " "));
}
if (this.state != null) {
parameters.put(OAuth2ParameterNames.STATE, this.state);
}
if (this.redirectUri != null) {
parameters.put(OAuth2ParameterNames.REDIRECT_URI, this.redirectUri);
}
parameters.putAll(this.additionalParameters);
return parameters;
}
// Encode query parameter value according to RFC 3986
private static String encodeQueryParam(String value) {
return UriUtils.encodeQueryParam(value, StandardCharsets.UTF_8);
}
}
}
| 15,113 | 30.953488 | 118 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/DefaultOAuth2AccessTokenResponseMapConverter.java | /*
* Copyright 2002-2021 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
*
* https://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.core.endpoint;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* A {@link Converter} that converts the provided {@link OAuth2AccessTokenResponse} to a
* {@code Map} representation of the OAuth 2.0 Access Token Response parameters.
*
* @author Steve Riesenberg
* @since 5.6
*/
public final class DefaultOAuth2AccessTokenResponseMapConverter
implements Converter<OAuth2AccessTokenResponse, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2AccessTokenResponse tokenResponse) {
Map<String, Object> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.ACCESS_TOKEN, tokenResponse.getAccessToken().getTokenValue());
parameters.put(OAuth2ParameterNames.TOKEN_TYPE, tokenResponse.getAccessToken().getTokenType().getValue());
parameters.put(OAuth2ParameterNames.EXPIRES_IN, getExpiresIn(tokenResponse));
if (!CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
parameters.put(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(tokenResponse.getAccessToken().getScopes(), " "));
}
if (tokenResponse.getRefreshToken() != null) {
parameters.put(OAuth2ParameterNames.REFRESH_TOKEN, tokenResponse.getRefreshToken().getTokenValue());
}
if (!CollectionUtils.isEmpty(tokenResponse.getAdditionalParameters())) {
for (Map.Entry<String, Object> entry : tokenResponse.getAdditionalParameters().entrySet()) {
parameters.put(entry.getKey(), entry.getValue());
}
}
return parameters;
}
private static long getExpiresIn(OAuth2AccessTokenResponse tokenResponse) {
if (tokenResponse.getAccessToken().getExpiresAt() != null) {
return ChronoUnit.SECONDS.between(Instant.now(), tokenResponse.getAccessToken().getExpiresAt());
}
return -1;
}
}
| 2,648 | 38.537313 | 108 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2ParameterNames.java | /*
* Copyright 2002-2023 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
*
* https://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.core.endpoint;
/**
* Standard and custom (non-standard) parameter names defined in the OAuth Parameters
* Registry and used by the authorization endpoint, token endpoint and token revocation
* endpoint.
*
* @author Joe Grandja
* @author Steve Riesenberg
* @since 5.0
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-11.2">11.2
* OAuth Parameters Registry</a>
*/
public final class OAuth2ParameterNames {
/**
* {@code grant_type} - used in Access Token Request.
*/
public static final String GRANT_TYPE = "grant_type";
/**
* {@code response_type} - used in Authorization Request.
*/
public static final String RESPONSE_TYPE = "response_type";
/**
* {@code client_id} - used in Authorization Request and Access Token Request.
*/
public static final String CLIENT_ID = "client_id";
/**
* {@code client_secret} - used in Access Token Request.
*/
public static final String CLIENT_SECRET = "client_secret";
/**
* {@code client_assertion_type} - used in Access Token Request.
* @since 5.5
*/
public static final String CLIENT_ASSERTION_TYPE = "client_assertion_type";
/**
* {@code client_assertion} - used in Access Token Request.
* @since 5.5
*/
public static final String CLIENT_ASSERTION = "client_assertion";
/**
* {@code assertion} - used in Access Token Request.
* @since 5.5
*/
public static final String ASSERTION = "assertion";
/**
* {@code redirect_uri} - used in Authorization Request and Access Token Request.
*/
public static final String REDIRECT_URI = "redirect_uri";
/**
* {@code scope} - used in Authorization Request, Authorization Response, Access Token
* Request and Access Token Response.
*/
public static final String SCOPE = "scope";
/**
* {@code state} - used in Authorization Request and Authorization Response.
*/
public static final String STATE = "state";
/**
* {@code code} - used in Authorization Response and Access Token Request.
*/
public static final String CODE = "code";
/**
* {@code access_token} - used in Authorization Response and Access Token Response.
*/
public static final String ACCESS_TOKEN = "access_token";
/**
* {@code token_type} - used in Authorization Response and Access Token Response.
*/
public static final String TOKEN_TYPE = "token_type";
/**
* {@code expires_in} - used in Authorization Response and Access Token Response.
*/
public static final String EXPIRES_IN = "expires_in";
/**
* {@code refresh_token} - used in Access Token Request and Access Token Response.
*/
public static final String REFRESH_TOKEN = "refresh_token";
/**
* {@code username} - used in Access Token Request.
*/
public static final String USERNAME = "username";
/**
* {@code password} - used in Access Token Request.
*/
public static final String PASSWORD = "password";
/**
* {@code error} - used in Authorization Response and Access Token Response.
*/
public static final String ERROR = "error";
/**
* {@code error_description} - used in Authorization Response and Access Token
* Response.
*/
public static final String ERROR_DESCRIPTION = "error_description";
/**
* {@code error_uri} - used in Authorization Response and Access Token Response.
*/
public static final String ERROR_URI = "error_uri";
/**
* Non-standard parameter (used internally).
*/
public static final String REGISTRATION_ID = "registration_id";
/**
* {@code token} - used in Token Revocation Request.
* @since 5.5
*/
public static final String TOKEN = "token";
/**
* {@code token_type_hint} - used in Token Revocation Request.
* @since 5.5
*/
public static final String TOKEN_TYPE_HINT = "token_type_hint";
/**
* {@code device_code} - used in Device Authorization Response and Device Access Token
* Request.
* @since 6.1
*/
public static final String DEVICE_CODE = "device_code";
/**
* {@code user_code} - used in Device Authorization Response.
* @since 6.1
*/
public static final String USER_CODE = "user_code";
/**
* {@code verification_uri} - used in Device Authorization Response.
* @since 6.1
*/
public static final String VERIFICATION_URI = "verification_uri";
/**
* {@code verification_uri_complete} - used in Device Authorization Response.
* @since 6.1
*/
public static final String VERIFICATION_URI_COMPLETE = "verification_uri_complete";
/**
* {@code interval} - used in Device Authorization Response.
* @since 6.1
*/
public static final String INTERVAL = "interval";
private OAuth2ParameterNames() {
}
}
| 5,245 | 26.756614 | 87 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AuthorizationResponse.java | /*
* Copyright 2002-2017 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
*
* https://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.core.endpoint;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A representation of an OAuth 2.0 Authorization Response for the authorization code
* grant type.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2Error
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization
* Response</a>
*/
public final class OAuth2AuthorizationResponse {
private String redirectUri;
private String state;
private String code;
private OAuth2Error error;
private OAuth2AuthorizationResponse() {
}
/**
* Returns the uri where the response was redirected to.
* @return the uri where the response was redirected to
*/
public String getRedirectUri() {
return this.redirectUri;
}
/**
* Returns the state.
* @return the state
*/
public String getState() {
return this.state;
}
/**
* Returns the authorization code.
* @return the authorization code
*/
public String getCode() {
return this.code;
}
/**
* Returns the {@link OAuth2Error OAuth 2.0 Error} if the Authorization Request
* failed, otherwise {@code null}.
* @return the {@link OAuth2Error} if the Authorization Request failed, otherwise
* {@code null}
*/
public OAuth2Error getError() {
return this.error;
}
/**
* Returns {@code true} if the Authorization Request succeeded, otherwise
* {@code false}.
* @return {@code true} if the Authorization Request succeeded, otherwise
* {@code false}
*/
public boolean statusOk() {
return !this.statusError();
}
/**
* Returns {@code true} if the Authorization Request failed, otherwise {@code false}.
* @return {@code true} if the Authorization Request failed, otherwise {@code false}
*/
public boolean statusError() {
return (this.error != null && this.error.getErrorCode() != null);
}
/**
* Returns a new {@link Builder}, initialized with the authorization code.
* @param code the authorization code
* @return the {@link Builder}
*/
public static Builder success(String code) {
Assert.hasText(code, "code cannot be empty");
return new Builder().code(code);
}
/**
* Returns a new {@link Builder}, initialized with the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public static Builder error(String errorCode) {
Assert.hasText(errorCode, "errorCode cannot be empty");
return new Builder().errorCode(errorCode);
}
/**
* A builder for {@link OAuth2AuthorizationResponse}.
*/
public static final class Builder {
private String redirectUri;
private String state;
private String code;
private String errorCode;
private String errorDescription;
private String errorUri;
private Builder() {
}
/**
* Sets the uri where the response was redirected to.
* @param redirectUri the uri where the response was redirected to
* @return the {@link Builder}
*/
public Builder redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* Sets the state.
* @param state the state
* @return the {@link Builder}
*/
public Builder state(String state) {
this.state = state;
return this;
}
/**
* Sets the authorization code.
* @param code the authorization code
* @return the {@link Builder}
*/
public Builder code(String code) {
this.code = code;
return this;
}
/**
* Sets the error code.
* @param errorCode the error code
* @return the {@link Builder}
*/
public Builder errorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
/**
* Sets the error description.
* @param errorDescription the error description
* @return the {@link Builder}
*/
public Builder errorDescription(String errorDescription) {
this.errorDescription = errorDescription;
return this;
}
/**
* Sets the error uri.
* @param errorUri the error uri
* @return the {@link Builder}
*/
public Builder errorUri(String errorUri) {
this.errorUri = errorUri;
return this;
}
/**
* Builds a new {@link OAuth2AuthorizationResponse}.
* @return a {@link OAuth2AuthorizationResponse}
*/
public OAuth2AuthorizationResponse build() {
if (StringUtils.hasText(this.code) && StringUtils.hasText(this.errorCode)) {
throw new IllegalArgumentException("code and errorCode cannot both be set");
}
Assert.hasText(this.redirectUri, "redirectUri cannot be empty");
OAuth2AuthorizationResponse authorizationResponse = new OAuth2AuthorizationResponse();
authorizationResponse.redirectUri = this.redirectUri;
authorizationResponse.state = this.state;
if (StringUtils.hasText(this.code)) {
authorizationResponse.code = this.code;
}
else {
authorizationResponse.error = new OAuth2Error(this.errorCode, this.errorDescription, this.errorUri);
}
return authorizationResponse;
}
}
}
| 5,649 | 24.336323 | 104 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/DefaultMapOAuth2AccessTokenResponseConverter.java | /*
* Copyright 2002-2021 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
*
* https://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.core.endpoint;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.util.StringUtils;
/**
* A {@link Converter} that converts the provided OAuth 2.0 Access Token Response
* parameters to an {@link OAuth2AccessTokenResponse}.
*
* @author Steve Riesenberg
* @since 5.6
*/
public final class DefaultMapOAuth2AccessTokenResponseConverter
implements Converter<Map<String, Object>, OAuth2AccessTokenResponse> {
private static final Set<String> TOKEN_RESPONSE_PARAMETER_NAMES = new HashSet<>(
Arrays.asList(OAuth2ParameterNames.ACCESS_TOKEN, OAuth2ParameterNames.EXPIRES_IN,
OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ParameterNames.SCOPE, OAuth2ParameterNames.TOKEN_TYPE));
@Override
public OAuth2AccessTokenResponse convert(Map<String, Object> source) {
String accessToken = getParameterValue(source, OAuth2ParameterNames.ACCESS_TOKEN);
OAuth2AccessToken.TokenType accessTokenType = getAccessTokenType(source);
long expiresIn = getExpiresIn(source);
Set<String> scopes = getScopes(source);
String refreshToken = getParameterValue(source, OAuth2ParameterNames.REFRESH_TOKEN);
Map<String, Object> additionalParameters = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : source.entrySet()) {
if (!TOKEN_RESPONSE_PARAMETER_NAMES.contains(entry.getKey())) {
additionalParameters.put(entry.getKey(), entry.getValue());
}
}
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken)
.tokenType(accessTokenType)
.expiresIn(expiresIn)
.scopes(scopes)
.refreshToken(refreshToken)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
private static OAuth2AccessToken.TokenType getAccessTokenType(Map<String, Object> tokenResponseParameters) {
if (OAuth2AccessToken.TokenType.BEARER.getValue()
.equalsIgnoreCase(getParameterValue(tokenResponseParameters, OAuth2ParameterNames.TOKEN_TYPE))) {
return OAuth2AccessToken.TokenType.BEARER;
}
return null;
}
private static long getExpiresIn(Map<String, Object> tokenResponseParameters) {
return getParameterValue(tokenResponseParameters, OAuth2ParameterNames.EXPIRES_IN, 0L);
}
private static Set<String> getScopes(Map<String, Object> tokenResponseParameters) {
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
String scope = getParameterValue(tokenResponseParameters, OAuth2ParameterNames.SCOPE);
return new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
}
return Collections.emptySet();
}
private static String getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName) {
Object obj = tokenResponseParameters.get(parameterName);
return (obj != null) ? obj.toString() : null;
}
private static long getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName,
long defaultValue) {
long parameterValue = defaultValue;
Object obj = tokenResponseParameters.get(parameterName);
if (obj != null) {
// Final classes Long and Integer do not need to be coerced
if (obj.getClass() == Long.class) {
parameterValue = (Long) obj;
}
else if (obj.getClass() == Integer.class) {
parameterValue = (Integer) obj;
}
else {
// Attempt to coerce to a long (typically from a String)
try {
parameterValue = Long.parseLong(obj.toString());
}
catch (NumberFormatException ignored) {
}
}
}
return parameterValue;
}
}
| 4,391 | 35.6 | 109 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/endpoint/OAuth2AccessTokenResponse.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.core.endpoint;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* A representation of an OAuth 2.0 Access Token Response.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2AccessToken
* @see OAuth2RefreshToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-5.1">Section
* 5.1 Access Token Response</a>
*/
public final class OAuth2AccessTokenResponse {
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
private Map<String, Object> additionalParameters;
private OAuth2AccessTokenResponse() {
}
/**
* Returns the {@link OAuth2AccessToken Access Token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken Refresh Token}.
* @return the {@link OAuth2RefreshToken}
* @since 5.1
*/
public @Nullable OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the additional parameters returned in the response.
* @return a {@code Map} of the additional parameters returned in the response, may be
* empty.
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
/**
* Returns a new {@link Builder}, initialized with the provided access token value.
* @param tokenValue the value of the access token
* @return the {@link Builder}
*/
public static Builder withToken(String tokenValue) {
return new Builder(tokenValue);
}
/**
* Returns a new {@link Builder}, initialized with the provided response.
* @param response the response to initialize the builder with
* @return the {@link Builder}
*/
public static Builder withResponse(OAuth2AccessTokenResponse response) {
return new Builder(response);
}
/**
* A builder for {@link OAuth2AccessTokenResponse}.
*/
public static final class Builder {
private String tokenValue;
private OAuth2AccessToken.TokenType tokenType;
private Instant issuedAt;
private Instant expiresAt;
private long expiresIn;
private Set<String> scopes;
private String refreshToken;
private Map<String, Object> additionalParameters;
private Builder(OAuth2AccessTokenResponse response) {
OAuth2AccessToken accessToken = response.getAccessToken();
this.tokenValue = accessToken.getTokenValue();
this.tokenType = accessToken.getTokenType();
this.issuedAt = accessToken.getIssuedAt();
this.expiresAt = accessToken.getExpiresAt();
this.scopes = accessToken.getScopes();
this.refreshToken = (response.getRefreshToken() != null) ? response.getRefreshToken().getTokenValue()
: null;
this.additionalParameters = response.getAdditionalParameters();
}
private Builder(String tokenValue) {
this.tokenValue = tokenValue;
}
/**
* Sets the {@link OAuth2AccessToken.TokenType token type}.
* @param tokenType the type of token issued
* @return the {@link Builder}
*/
public Builder tokenType(OAuth2AccessToken.TokenType tokenType) {
this.tokenType = tokenType;
return this;
}
/**
* Sets the lifetime (in seconds) of the access token.
* @param expiresIn the lifetime of the access token, in seconds.
* @return the {@link Builder}
*/
public Builder expiresIn(long expiresIn) {
this.expiresIn = expiresIn;
this.expiresAt = null;
return this;
}
/**
* Sets the scope(s) associated to the access token.
* @param scopes the scope(s) associated to the access token.
* @return the {@link Builder}
*/
public Builder scopes(Set<String> scopes) {
this.scopes = scopes;
return this;
}
/**
* Sets the refresh token associated to the access token.
* @param refreshToken the refresh token associated to the access token.
* @return the {@link Builder}
*/
public Builder refreshToken(String refreshToken) {
this.refreshToken = refreshToken;
return this;
}
/**
* Sets the additional parameters returned in the response.
* @param additionalParameters the additional parameters returned in the response
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
return this;
}
/**
* Builds a new {@link OAuth2AccessTokenResponse}.
* @return a {@link OAuth2AccessTokenResponse}
*/
public OAuth2AccessTokenResponse build() {
Instant issuedAt = getIssuedAt();
Instant expiresAt = getExpiresAt();
OAuth2AccessTokenResponse accessTokenResponse = new OAuth2AccessTokenResponse();
accessTokenResponse.accessToken = new OAuth2AccessToken(this.tokenType, this.tokenValue, issuedAt,
expiresAt, this.scopes);
if (StringUtils.hasText(this.refreshToken)) {
accessTokenResponse.refreshToken = new OAuth2RefreshToken(this.refreshToken, issuedAt);
}
accessTokenResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return accessTokenResponse;
}
private Instant getIssuedAt() {
if (this.issuedAt == null) {
this.issuedAt = Instant.now();
}
return this.issuedAt;
}
/**
* expires_in is RECOMMENDED, as per spec
* https://tools.ietf.org/html/rfc6749#section-5.1 Therefore, expires_in may not
* be returned in the Access Token response which would result in the default
* value of 0. For these instances, default the expiresAt to +1 second from
* issuedAt time.
* @return
*/
private Instant getExpiresAt() {
if (this.expiresAt == null) {
Instant issuedAt = getIssuedAt();
this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1);
}
return this.expiresAt;
}
}
}
| 6,807 | 28.859649 | 107 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/http/converter/HttpMessageConverters.java | /*
* 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
*
* https://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.core.http.converter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.http.converter.json.JsonbHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.ClassUtils;
/**
* Utility methods for {@link HttpMessageConverter}'s.
*
* @author Joe Grandja
* @author luamas
* @since 5.1
*/
final class HttpMessageConverters {
private static final boolean jackson2Present;
private static final boolean gsonPresent;
private static final boolean jsonbPresent;
static {
ClassLoader classLoader = HttpMessageConverters.class.getClassLoader();
jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader)
&& ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader);
jsonbPresent = ClassUtils.isPresent("jakarta.json.bind.Jsonb", classLoader);
}
private HttpMessageConverters() {
}
static GenericHttpMessageConverter<Object> getJsonMessageConverter() {
if (jackson2Present) {
return new MappingJackson2HttpMessageConverter();
}
if (gsonPresent) {
return new GsonHttpMessageConverter();
}
if (jsonbPresent) {
return new JsonbHttpMessageConverter();
}
return null;
}
}
| 2,174 | 31.954545 | 100 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/http/converter/OAuth2DeviceAuthorizationResponseHttpMessageConverter.java | /*
* Copyright 2002-2023 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
*
* https://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.core.http.converter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.oauth2.core.endpoint.OAuth2DeviceAuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* A {@link HttpMessageConverter} for an {@link OAuth2DeviceAuthorizationResponse OAuth
* 2.0 Device Authorization Response}.
*
* @author Steve Riesenberg
* @since 6.1
* @see AbstractHttpMessageConverter
* @see OAuth2DeviceAuthorizationResponse
*/
public class OAuth2DeviceAuthorizationResponseHttpMessageConverter
extends AbstractHttpMessageConverter<OAuth2DeviceAuthorizationResponse> {
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<>() {
};
private final GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters
.getJsonMessageConverter();
private Converter<Map<String, Object>, OAuth2DeviceAuthorizationResponse> deviceAuthorizationResponseConverter = new DefaultMapOAuth2DeviceAuthorizationResponseConverter();
private Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> deviceAuthorizationResponseParametersConverter = new DefaultOAuth2DeviceAuthorizationResponseMapConverter();
@Override
protected boolean supports(Class<?> clazz) {
return OAuth2DeviceAuthorizationResponse.class.isAssignableFrom(clazz);
}
@Override
@SuppressWarnings("unchecked")
protected OAuth2DeviceAuthorizationResponse readInternal(Class<? extends OAuth2DeviceAuthorizationResponse> clazz,
HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
try {
Map<String, Object> deviceAuthorizationResponseParameters = (Map<String, Object>) this.jsonMessageConverter
.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
return this.deviceAuthorizationResponseConverter.convert(deviceAuthorizationResponseParameters);
}
catch (Exception ex) {
throw new HttpMessageNotReadableException(
"An error occurred reading the OAuth 2.0 Device Authorization Response: " + ex.getMessage(), ex,
inputMessage);
}
}
@Override
protected void writeInternal(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse,
HttpOutputMessage outputMessage) throws HttpMessageNotWritableException {
try {
Map<String, Object> deviceAuthorizationResponseParameters = this.deviceAuthorizationResponseParametersConverter
.convert(deviceAuthorizationResponse);
this.jsonMessageConverter.write(deviceAuthorizationResponseParameters, STRING_OBJECT_MAP.getType(),
MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Device Authorization Response: " + ex.getMessage(), ex);
}
}
/**
* Sets the {@link Converter} used for converting the OAuth 2.0 Device Authorization
* Response parameters to an {@link OAuth2DeviceAuthorizationResponse}.
* @param deviceAuthorizationResponseConverter the {@link Converter} used for
* converting to an {@link OAuth2DeviceAuthorizationResponse}
*/
public final void setDeviceAuthorizationResponseConverter(
Converter<Map<String, Object>, OAuth2DeviceAuthorizationResponse> deviceAuthorizationResponseConverter) {
Assert.notNull(deviceAuthorizationResponseConverter, "deviceAuthorizationResponseConverter cannot be null");
this.deviceAuthorizationResponseConverter = deviceAuthorizationResponseConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2DeviceAuthorizationResponse} to a {@code Map} representation of the
* OAuth 2.0 Device Authorization Response parameters.
* @param deviceAuthorizationResponseParametersConverter the {@link Converter} used
* for converting to a {@code Map} representation of the Device Authorization Response
* parameters
*/
public final void setDeviceAuthorizationResponseParametersConverter(
Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> deviceAuthorizationResponseParametersConverter) {
Assert.notNull(deviceAuthorizationResponseParametersConverter,
"deviceAuthorizationResponseParametersConverter cannot be null");
this.deviceAuthorizationResponseParametersConverter = deviceAuthorizationResponseParametersConverter;
}
private static final class DefaultMapOAuth2DeviceAuthorizationResponseConverter
implements Converter<Map<String, Object>, OAuth2DeviceAuthorizationResponse> {
private static final Set<String> DEVICE_AUTHORIZATION_RESPONSE_PARAMETER_NAMES = new HashSet<>(
Arrays.asList(OAuth2ParameterNames.DEVICE_CODE, OAuth2ParameterNames.USER_CODE,
OAuth2ParameterNames.VERIFICATION_URI, OAuth2ParameterNames.VERIFICATION_URI_COMPLETE,
OAuth2ParameterNames.EXPIRES_IN, OAuth2ParameterNames.INTERVAL));
@Override
public OAuth2DeviceAuthorizationResponse convert(Map<String, Object> parameters) {
String deviceCode = getParameterValue(parameters, OAuth2ParameterNames.DEVICE_CODE);
String userCode = getParameterValue(parameters, OAuth2ParameterNames.USER_CODE);
String verificationUri = getParameterValue(parameters, OAuth2ParameterNames.VERIFICATION_URI);
String verificationUriComplete = getParameterValue(parameters,
OAuth2ParameterNames.VERIFICATION_URI_COMPLETE);
long expiresIn = getParameterValue(parameters, OAuth2ParameterNames.EXPIRES_IN, 0L);
long interval = getParameterValue(parameters, OAuth2ParameterNames.INTERVAL, 0L);
Map<String, Object> additionalParameters = new LinkedHashMap<>();
parameters.forEach((key, value) -> {
if (!DEVICE_AUTHORIZATION_RESPONSE_PARAMETER_NAMES.contains(key)) {
additionalParameters.put(key, value);
}
});
// @formatter:off
return OAuth2DeviceAuthorizationResponse.with(deviceCode, userCode)
.verificationUri(verificationUri)
.verificationUriComplete(verificationUriComplete)
.expiresIn(expiresIn)
.interval(interval)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
private static String getParameterValue(Map<String, Object> parameters, String parameterName) {
Object obj = parameters.get(parameterName);
return (obj != null) ? obj.toString() : null;
}
private static long getParameterValue(Map<String, Object> parameters, String parameterName, long defaultValue) {
long parameterValue = defaultValue;
Object obj = parameters.get(parameterName);
if (obj != null) {
// Final classes Long and Integer do not need to be coerced
if (obj.getClass() == Long.class) {
parameterValue = (Long) obj;
}
else if (obj.getClass() == Integer.class) {
parameterValue = (Integer) obj;
}
else {
// Attempt to coerce to a long (typically from a String)
try {
parameterValue = Long.parseLong(obj.toString());
}
catch (NumberFormatException ignored) {
}
}
}
return parameterValue;
}
}
private static final class DefaultOAuth2DeviceAuthorizationResponseMapConverter
implements Converter<OAuth2DeviceAuthorizationResponse, Map<String, Object>> {
@Override
public Map<String, Object> convert(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
Map<String, Object> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.DEVICE_CODE,
deviceAuthorizationResponse.getDeviceCode().getTokenValue());
parameters.put(OAuth2ParameterNames.USER_CODE, deviceAuthorizationResponse.getUserCode().getTokenValue());
parameters.put(OAuth2ParameterNames.VERIFICATION_URI, deviceAuthorizationResponse.getVerificationUri());
if (StringUtils.hasText(deviceAuthorizationResponse.getVerificationUriComplete())) {
parameters.put(OAuth2ParameterNames.VERIFICATION_URI_COMPLETE,
deviceAuthorizationResponse.getVerificationUriComplete());
}
parameters.put(OAuth2ParameterNames.EXPIRES_IN, getExpiresIn(deviceAuthorizationResponse));
if (deviceAuthorizationResponse.getInterval() > 0) {
parameters.put(OAuth2ParameterNames.INTERVAL, deviceAuthorizationResponse.getInterval());
}
if (!CollectionUtils.isEmpty(deviceAuthorizationResponse.getAdditionalParameters())) {
parameters.putAll(deviceAuthorizationResponse.getAdditionalParameters());
}
return parameters;
}
private static long getExpiresIn(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) {
if (deviceAuthorizationResponse.getDeviceCode().getExpiresAt() != null) {
Instant issuedAt = (deviceAuthorizationResponse.getDeviceCode().getIssuedAt() != null)
? deviceAuthorizationResponse.getDeviceCode().getIssuedAt() : Instant.now();
return ChronoUnit.SECONDS.between(issuedAt, deviceAuthorizationResponse.getDeviceCode().getExpiresAt());
}
return -1;
}
}
}
| 10,377 | 43.540773 | 183 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/http/converter/OAuth2ErrorHttpMessageConverter.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.core.http.converter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A {@link HttpMessageConverter} for an {@link OAuth2Error OAuth 2.0 Error}.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractHttpMessageConverter
* @see OAuth2Error
*/
public class OAuth2ErrorHttpMessageConverter extends AbstractHttpMessageConverter<OAuth2Error> {
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters.getJsonMessageConverter();
protected Converter<Map<String, String>, OAuth2Error> errorConverter = new OAuth2ErrorConverter();
protected Converter<OAuth2Error, Map<String, String>> errorParametersConverter = new OAuth2ErrorParametersConverter();
public OAuth2ErrorHttpMessageConverter() {
super(DEFAULT_CHARSET, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
}
@Override
protected boolean supports(Class<?> clazz) {
return OAuth2Error.class.isAssignableFrom(clazz);
}
@Override
@SuppressWarnings("unchecked")
protected OAuth2Error readInternal(Class<? extends OAuth2Error> clazz, HttpInputMessage inputMessage)
throws HttpMessageNotReadableException {
try {
// gh-8157: Parse parameter values as Object in order to handle potential JSON
// Object and then convert values to String
Map<String, Object> errorParameters = (Map<String, Object>) this.jsonMessageConverter
.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
return this.errorConverter.convert(errorParameters.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> String.valueOf(entry.getValue()))));
}
catch (Exception ex) {
throw new HttpMessageNotReadableException(
"An error occurred reading the OAuth 2.0 Error: " + ex.getMessage(), ex, inputMessage);
}
}
@Override
protected void writeInternal(OAuth2Error oauth2Error, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try {
Map<String, String> errorParameters = this.errorParametersConverter.convert(oauth2Error);
this.jsonMessageConverter.write(errorParameters, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON,
outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Error: " + ex.getMessage(), ex);
}
}
/**
* Sets the {@link Converter} used for converting the OAuth 2.0 Error parameters to an
* {@link OAuth2Error}.
* @param errorConverter the {@link Converter} used for converting to an
* {@link OAuth2Error}
*/
public final void setErrorConverter(Converter<Map<String, String>, OAuth2Error> errorConverter) {
Assert.notNull(errorConverter, "errorConverter cannot be null");
this.errorConverter = errorConverter;
}
/**
* Sets the {@link Converter} used for converting the {@link OAuth2Error} to a
* {@code Map} representation of the OAuth 2.0 Error parameters.
* @param errorParametersConverter the {@link Converter} used for converting to a
* {@code Map} representation of the Error parameters
*/
public final void setErrorParametersConverter(
Converter<OAuth2Error, Map<String, String>> errorParametersConverter) {
Assert.notNull(errorParametersConverter, "errorParametersConverter cannot be null");
this.errorParametersConverter = errorParametersConverter;
}
/**
* A {@link Converter} that converts the provided OAuth 2.0 Error parameters to an
* {@link OAuth2Error}.
*/
private static class OAuth2ErrorConverter implements Converter<Map<String, String>, OAuth2Error> {
@Override
public OAuth2Error convert(Map<String, String> parameters) {
String errorCode = parameters.get(OAuth2ParameterNames.ERROR);
String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI);
return new OAuth2Error(errorCode, errorDescription, errorUri);
}
}
/**
* A {@link Converter} that converts the provided {@link OAuth2Error} to a {@code Map}
* representation of OAuth 2.0 Error parameters.
*/
private static class OAuth2ErrorParametersConverter implements Converter<OAuth2Error, Map<String, String>> {
@Override
public Map<String, String> convert(OAuth2Error oauth2Error) {
Map<String, String> parameters = new HashMap<>();
parameters.put(OAuth2ParameterNames.ERROR, oauth2Error.getErrorCode());
if (StringUtils.hasText(oauth2Error.getDescription())) {
parameters.put(OAuth2ParameterNames.ERROR_DESCRIPTION, oauth2Error.getDescription());
}
if (StringUtils.hasText(oauth2Error.getUri())) {
parameters.put(OAuth2ParameterNames.ERROR_URI, oauth2Error.getUri());
}
return parameters;
}
}
}
| 6,529 | 39.06135 | 145 | java |
null | spring-security-main/oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/http/converter/OAuth2AccessTokenResponseHttpMessageConverter.java | /*
* Copyright 2002-2022 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
*
* https://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.core.http.converter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.oauth2.core.endpoint.DefaultMapOAuth2AccessTokenResponseConverter;
import org.springframework.security.oauth2.core.endpoint.DefaultOAuth2AccessTokenResponseMapConverter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.util.Assert;
/**
* A {@link HttpMessageConverter} for an {@link OAuth2AccessTokenResponse OAuth 2.0 Access
* Token Response}.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractHttpMessageConverter
* @see OAuth2AccessTokenResponse
*/
public class OAuth2AccessTokenResponseHttpMessageConverter
extends AbstractHttpMessageConverter<OAuth2AccessTokenResponse> {
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters.getJsonMessageConverter();
private Converter<Map<String, Object>, OAuth2AccessTokenResponse> accessTokenResponseConverter = new DefaultMapOAuth2AccessTokenResponseConverter();
private Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter = new DefaultOAuth2AccessTokenResponseMapConverter();
public OAuth2AccessTokenResponseHttpMessageConverter() {
super(DEFAULT_CHARSET, MediaType.APPLICATION_JSON, new MediaType("application", "*+json"));
}
@Override
protected boolean supports(Class<?> clazz) {
return OAuth2AccessTokenResponse.class.isAssignableFrom(clazz);
}
@Override
@SuppressWarnings("unchecked")
protected OAuth2AccessTokenResponse readInternal(Class<? extends OAuth2AccessTokenResponse> clazz,
HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
try {
Map<String, Object> tokenResponseParameters = (Map<String, Object>) this.jsonMessageConverter
.read(STRING_OBJECT_MAP.getType(), null, inputMessage);
return this.accessTokenResponseConverter.convert(tokenResponseParameters);
}
catch (Exception ex) {
throw new HttpMessageNotReadableException(
"An error occurred reading the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex,
inputMessage);
}
}
@Override
protected void writeInternal(OAuth2AccessTokenResponse tokenResponse, HttpOutputMessage outputMessage)
throws HttpMessageNotWritableException {
try {
Map<String, Object> tokenResponseParameters = this.accessTokenResponseParametersConverter
.convert(tokenResponse);
this.jsonMessageConverter.write(tokenResponseParameters, STRING_OBJECT_MAP.getType(),
MediaType.APPLICATION_JSON, outputMessage);
}
catch (Exception ex) {
throw new HttpMessageNotWritableException(
"An error occurred writing the OAuth 2.0 Access Token Response: " + ex.getMessage(), ex);
}
}
/**
* Sets the {@link Converter} used for converting the OAuth 2.0 Access Token Response
* parameters to an {@link OAuth2AccessTokenResponse}.
* @param accessTokenResponseConverter the {@link Converter} used for converting to an
* {@link OAuth2AccessTokenResponse}
* @since 5.6
*/
public final void setAccessTokenResponseConverter(
Converter<Map<String, Object>, OAuth2AccessTokenResponse> accessTokenResponseConverter) {
Assert.notNull(accessTokenResponseConverter, "accessTokenResponseConverter cannot be null");
this.accessTokenResponseConverter = accessTokenResponseConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2AccessTokenResponse} to a {@code Map} representation of the OAuth 2.0
* Access Token Response parameters.
* @param accessTokenResponseParametersConverter the {@link Converter} used for
* converting to a {@code Map} representation of the Access Token Response parameters
* @since 5.6
*/
public final void setAccessTokenResponseParametersConverter(
Converter<OAuth2AccessTokenResponse, Map<String, Object>> accessTokenResponseParametersConverter) {
Assert.notNull(accessTokenResponseParametersConverter, "accessTokenResponseParametersConverter cannot be null");
this.accessTokenResponseParametersConverter = accessTokenResponseParametersConverter;
}
}
| 5,653 | 42.829457 | 159 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/R2dbcReactiveOAuth2AuthorizedClientServiceTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import io.r2dbc.h2.H2ConnectionFactory;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.Result;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.r2dbc.connection.init.CompositeDatabasePopulator;
import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer;
import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link R2dbcReactiveOAuth2AuthorizedClientService}
*
* @author Ovidiu Popa
*
*/
public class R2dbcReactiveOAuth2AuthorizedClientServiceTests {
private static final String OAUTH2_CLIENT_SCHEMA_SQL_RESOURCE = "org/springframework/security/oauth2/client/oauth2-client-schema.sql";
private ClientRegistration clientRegistration;
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private DatabaseClient databaseClient;
private static int principalId = 1000;
private R2dbcReactiveOAuth2AuthorizedClientService authorizedClientService;
@BeforeEach
public void setUp() {
final ConnectionFactory connectionFactory = createDb();
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(this.clientRegistrationRepository.findByRegistrationId(anyString()))
.willReturn(Mono.just(this.clientRegistration));
this.databaseClient = DatabaseClient.create(connectionFactory);
this.authorizedClientService = new R2dbcReactiveOAuth2AuthorizedClientService(this.databaseClient,
this.clientRegistrationRepository);
}
@Test
public void constructorWhenDatabaseClientIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(
() -> new R2dbcReactiveOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
.withMessageContaining("databaseClient cannot be null");
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> new R2dbcReactiveOAuth2AuthorizedClientService(this.databaseClient, null))
.withMessageContaining("clientRegistrationRepository cannot be null");
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
.withMessageContaining("clientRegistrationId cannot be empty");
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessageContaining("principalName cannot be empty");
}
@Test
public void loadAuthorizedClientWhenDoesNotExistThenReturnNull() {
this.authorizedClientService.loadAuthorizedClient("registration-not-found", "principalName")
.as(StepVerifier::create).expectNextCount(0).verifyComplete();
}
@Test
public void loadAuthorizedClientWhenExistsThenReturnAuthorizedClient() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
.verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).assertNext((authorizedClient) -> {
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(expected.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(expected.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt())
.isEqualTo(expected.getAccessToken().getIssuedAt());
assertThat(authorizedClient.getAccessToken().getExpiresAt())
.isEqualTo(expected.getAccessToken().getExpiresAt());
assertThat(authorizedClient.getAccessToken().getScopes())
.isEqualTo(expected.getAccessToken().getScopes());
assertThat(authorizedClient.getRefreshToken().getTokenValue())
.isEqualTo(expected.getRefreshToken().getTokenValue());
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
.isEqualTo(expected.getRefreshToken().getIssuedAt());
}).verifyComplete();
}
@Test
public void loadAuthorizedClientWhenExistsButNotFoundInClientRegistrationRepositoryThenThrowDataRetrievalFailureException() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.empty());
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
.verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create)
.verifyErrorSatisfies((exception) -> assertThat(exception)
.isInstanceOf(DataRetrievalFailureException.class)
.hasMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
+ "' exists in the data source, however, it was not found in the ReactiveClientRegistrationRepository."));
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
.withMessageContaining("authorizedClient cannot be null");
}
@Test
public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
.withMessageContaining("principal cannot be null");
}
@Test
public void saveAuthorizedClientWhenSaveThenLoadReturnsSaved() {
Authentication principal = createPrincipal();
final OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal).as(StepVerifier::create)
.verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).assertNext((authorizedClient) -> {
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(expected.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(expected.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt())
.isEqualTo(expected.getAccessToken().getIssuedAt());
assertThat(authorizedClient.getAccessToken().getExpiresAt())
.isEqualTo(expected.getAccessToken().getExpiresAt());
assertThat(authorizedClient.getAccessToken().getScopes())
.isEqualTo(expected.getAccessToken().getScopes());
assertThat(authorizedClient.getRefreshToken().getTokenValue())
.isEqualTo(expected.getRefreshToken().getTokenValue());
assertThat(authorizedClient.getRefreshToken().getIssuedAt())
.isEqualTo(expected.getRefreshToken().getIssuedAt());
}).verifyComplete();
// Test save/load of NOT NULL attributes only
principal = createPrincipal();
OAuth2AuthorizedClient updatedExpectedPrincipal = createAuthorizedClient(principal, this.clientRegistration,
true);
this.authorizedClientService.saveAuthorizedClient(updatedExpectedPrincipal, principal).as(StepVerifier::create)
.verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).assertNext((authorizedClient) -> {
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration())
.isEqualTo(updatedExpectedPrincipal.getClientRegistration());
assertThat(authorizedClient.getPrincipalName())
.isEqualTo(updatedExpectedPrincipal.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt())
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getIssuedAt());
assertThat(authorizedClient.getAccessToken().getExpiresAt())
.isEqualTo(updatedExpectedPrincipal.getAccessToken().getExpiresAt());
assertThat(authorizedClient.getAccessToken().getScopes()).isEmpty();
assertThat(authorizedClient.getRefreshToken()).isNull();
}).verifyComplete();
}
@Test
public void saveAuthorizedClientWhenSaveClientWithExistingPrimaryKeyThenUpdate() {
// Given a saved authorized client
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal).as(StepVerifier::create)
.verifyComplete();
// When a client with the same principal and registration id is saved
OAuth2AuthorizedClient updatedAuthorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(updatedAuthorizedClient, principal).as(StepVerifier::create)
.verifyComplete();
// Then the saved client is updated
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).assertNext((savedClient) -> {
assertThat(savedClient).isNotNull();
assertThat(savedClient.getClientRegistration())
.isEqualTo(updatedAuthorizedClient.getClientRegistration());
assertThat(savedClient.getPrincipalName()).isEqualTo(updatedAuthorizedClient.getPrincipalName());
assertThat(savedClient.getAccessToken().getTokenType())
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenType());
assertThat(savedClient.getAccessToken().getTokenValue())
.isEqualTo(updatedAuthorizedClient.getAccessToken().getTokenValue());
assertThat(savedClient.getAccessToken().getIssuedAt())
.isEqualTo(updatedAuthorizedClient.getAccessToken().getIssuedAt());
assertThat(savedClient.getAccessToken().getExpiresAt())
.isEqualTo(updatedAuthorizedClient.getAccessToken().getExpiresAt());
assertThat(savedClient.getAccessToken().getScopes())
.isEqualTo(updatedAuthorizedClient.getAccessToken().getScopes());
assertThat(savedClient.getRefreshToken().getTokenValue())
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getTokenValue());
assertThat(savedClient.getRefreshToken().getIssuedAt())
.isEqualTo(updatedAuthorizedClient.getRefreshToken().getIssuedAt());
});
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
.withMessageContaining("clientRegistrationId cannot be empty");
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessageContaining("principalName cannot be empty");
}
@Test
public void removeAuthorizedClientWhenExistsThenRemoved() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal).as(StepVerifier::create)
.verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).assertNext((dbAuthorizedClient) -> assertThat(dbAuthorizedClient).isNotNull())
.verifyComplete();
this.authorizedClientService
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).verifyComplete();
this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName())
.as(StepVerifier::create).expectNextCount(0).verifyComplete();
}
@Test
public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
.withMessageContaining("authorizedClientRowMapper cannot be nul");
}
@Test
public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
.withMessageContaining("authorizedClientParametersMapper cannot be nul");
}
private static ConnectionFactory createDb() {
ConnectionFactory connectionFactory = H2ConnectionFactory.inMemory("oauth-test");
Mono.from(connectionFactory.create())
.flatMapMany((connection) -> Flux
.from(connection.createStatement("drop table oauth2_authorized_client").execute())
.flatMap(Result::getRowsUpdated).onErrorResume((e) -> Mono.empty())
.thenMany(connection.close()))
.as(StepVerifier::create).verifyComplete();
ConnectionFactoryInitializer createDb = createDb(OAUTH2_CLIENT_SCHEMA_SQL_RESOURCE);
createDb.setConnectionFactory(connectionFactory);
createDb.afterPropertiesSet();
return connectionFactory;
}
private static ConnectionFactoryInitializer createDb(String schema) {
ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource(schema)));
initializer.setDatabasePopulator(populator);
return initializer;
}
private static Authentication createPrincipal() {
return new TestingAuthenticationToken("principal-" + principalId++, "password");
}
private static OAuth2AuthorizedClient createAuthorizedClient(Authentication principal,
ClientRegistration clientRegistration) {
return createAuthorizedClient(principal, clientRegistration, false);
}
private static OAuth2AuthorizedClient createAuthorizedClient(Authentication principal,
ClientRegistration clientRegistration, boolean requiredAttributesOnly) {
Instant issuedAt = Instant.ofEpochSecond(1234567890, 123456000);
OAuth2AccessToken accessToken;
if (!requiredAttributesOnly) {
accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "scopes", issuedAt,
issuedAt.plus(Duration.ofDays(1)), new HashSet<>(Arrays.asList("read", "write")));
}
else {
accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "no-scopes", issuedAt,
issuedAt.plus(Duration.ofDays(1)));
}
OAuth2RefreshToken refreshToken = null;
if (!requiredAttributesOnly) {
refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
}
return new OAuth2AuthorizedClient(clientRegistration, principal.getName(), accessToken, refreshToken);
}
}
| 18,714 | 47.234536 | 135 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link RefreshTokenReactiveOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class RefreshTokenReactiveOAuth2AuthorizedClientProviderTests {
private RefreshTokenReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new RefreshTokenReactiveOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(ReactiveOAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken expiredAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
expiredAccessToken, TestOAuth2RefreshTokens.refreshToken());
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotAuthorizedThenUnableToReauthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenAuthorizedAndRefreshTokenIsNullThenUnableToReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), this.authorizedClient.getAccessToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), this.authorizedClient.getRefreshToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
// gh-7511
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.refreshToken("new-refresh-token").build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken, this.authorizedClient.getRefreshToken());
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
.block();
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
@Test
public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.refreshToken("new-refresh-token").build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient).principal(this.principal).build();
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
.block();
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
@Test
public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.refreshToken("new-refresh-token").build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
String[] requestScope = new String[] { "read", "write" };
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, requestScope)
.build();
// @formatter:on
this.authorizedClientProvider.authorize(authorizationContext).block();
ArgumentCaptor<OAuth2RefreshTokenGrantRequest> refreshTokenGrantRequestArgCaptor = ArgumentCaptor
.forClass(OAuth2RefreshTokenGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(refreshTokenGrantRequestArgCaptor.capture());
assertThat(refreshTokenGrantRequestArgCaptor.getValue().getScopes())
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
}
@Test
public void authorizeWhenAuthorizedAndInvalidRequestScopeProvidedThenThrowIllegalArgumentException() {
String invalidRequestScope = "read write";
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope)
.build();
// @formatter:on
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
.withMessageStartingWith("The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
}
}
| 11,196 | 45.849372 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientIdTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizedClientId}.
*
* @author Vedran Pavic
*/
public class OAuth2AuthorizedClientIdTests {
@Test
public void constructorWhenRegistrationIdNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId(null, "test-principal"))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void constructorWhenPrincipalNameNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientId("test-client", null))
.withMessage("principalName cannot be empty");
}
@Test
public void equalsWhenSameRegistrationIdAndPrincipalThenShouldReturnTrue() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client", "test-principal");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client", "test-principal");
assertThat(id1.equals(id2)).isTrue();
}
@Test
public void equalsWhenDifferentRegistrationIdAndSamePrincipalThenShouldReturnFalse() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client1", "test-principal");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client2", "test-principal");
assertThat(id1.equals(id2)).isFalse();
}
@Test
public void equalsWhenSameRegistrationIdAndDifferentPrincipalThenShouldReturnFalse() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client", "test-principal1");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client", "test-principal2");
assertThat(id1.equals(id2)).isFalse();
}
@Test
public void hashCodeWhenSameRegistrationIdAndPrincipalThenShouldReturnSame() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client", "test-principal");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client", "test-principal");
assertThat(id1.hashCode()).isEqualTo(id2.hashCode());
}
@Test
public void hashCodeWhenDifferentRegistrationIdAndSamePrincipalThenShouldNotReturnSame() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client1", "test-principal");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client2", "test-principal");
assertThat(id1.hashCode()).isNotEqualTo(id2.hashCode());
}
@Test
public void hashCodeWhenSameRegistrationIdAndDifferentPrincipalThenShouldNotReturnSame() {
OAuth2AuthorizedClientId id1 = new OAuth2AuthorizedClientId("test-client", "test-principal1");
OAuth2AuthorizedClientId id2 = new OAuth2AuthorizedClientId("test-client", "test-principal2");
assertThat(id1.hashCode()).isNotEqualTo(id2.hashCode());
}
}
| 3,538 | 40.151163 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link AuthorizationCodeOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class AuthorizationCodeOAuth2AuthorizedClientProviderTests {
private AuthorizationCodeOAuth2AuthorizedClientProvider authorizedClientProvider;
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new AuthorizationCodeOAuth2AuthorizedClientProvider();
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, "principal",
TestOAuth2AccessTokens.scopes("read", "write"));
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null));
}
@Test
public void authorizeWhenNotAuthorizationCodeThenUnableToAuthorize() {
ClientRegistration clientCredentialsClient = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientCredentialsClient).principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenAuthorizationCodeAndAuthorizedThenNotAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient).principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration).principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext));
}
}
| 3,683 | 38.191489 | 103 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JwtBearerReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link JwtBearerReactiveOAuth2AuthorizedClientProvider}.
*
* @author Steve Riesenberg
*/
public class JwtBearerReactiveOAuth2AuthorizedClientProviderTests {
private JwtBearerReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Jwt jwtAssertion;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(ReactiveOAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
// @formatter:off
this.clientRegistration = ClientRegistration.withRegistrationId("jwt-bearer")
.clientId("client-id")
.clientSecret("client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.tokenUri("https://example.com/oauth2/token")
.build();
// @formatter:on
this.jwtAssertion = TestJwts.jwt().build();
this.principal = new TestingAuthenticationToken(this.jwtAssertion, this.jwtAssertion);
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setJwtAssertionResolverWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
.withMessage("jwtAssertionResolver cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotJwtBearerThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenJwtBearerAndTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenJwtBearerAndTokenExpiredThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(30));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234",
issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenClockSetThenCalled() {
Clock clock = mock(Clock.class);
given(clock.instant()).willReturn(Instant.now());
this.authorizedClientProvider.setClock(clock);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
verify(clock).instant();
}
@Test
public void authorizeWhenJwtBearerAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.plus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken);
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
.block();
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtDoesNotResolveThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(new TestingAuthenticationToken("user", "password"))
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenInvalidRequestThenThrowClientAuthorizationException() {
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(
Mono.error(new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST))));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
// @formatter:off
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block())
.withMessageContaining(OAuth2ErrorCodes.INVALID_REQUEST);
// @formatter:on
}
@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenCustomJwtAssertionResolverSetThenUsed() {
Function<OAuth2AuthorizationContext, Mono<Jwt>> jwtAssertionResolver = mock(Function.class);
given(jwtAssertionResolver.apply(any())).willReturn(Mono.just(this.jwtAssertion));
this.authorizedClientProvider.setJwtAssertionResolver(jwtAssertionResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
verify(jwtAssertionResolver).apply(any());
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 13,594 | 44.468227 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JdbcOAuth2AuthorizedClientServiceTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.nio.charset.StandardCharsets;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.jdbc.core.ArgumentPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.within;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link JdbcOAuth2AuthorizedClientService}.
*
* @author Joe Grandja
* @author Stav Shamir
*/
public class JdbcOAuth2AuthorizedClientServiceTests {
private static final String OAUTH2_CLIENT_SCHEMA_SQL_RESOURCE = "org/springframework/security/oauth2/client/oauth2-client-schema.sql";
private static int principalId = 1000;
private ClientRegistration clientRegistration;
private ClientRegistrationRepository clientRegistrationRepository;
private EmbeddedDatabase db;
private JdbcOperations jdbcOperations;
private JdbcOAuth2AuthorizedClientService authorizedClientService;
@BeforeEach
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(this.clientRegistration);
this.db = createDb();
this.jdbcOperations = new JdbcTemplate(this.db);
this.authorizedClientService = new JdbcOAuth2AuthorizedClientService(this.jdbcOperations,
this.clientRegistrationRepository);
}
@AfterEach
public void tearDown() {
this.db.shutdown();
}
@Test
public void constructorWhenJdbcOperationsIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(null, this.clientRegistrationRepository))
.withMessage("jdbcOperations cannot be null");
// @formatter:on
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new JdbcOAuth2AuthorizedClientService(this.jdbcOperations, null))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void setAuthorizedClientRowMapperWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientRowMapper(null))
.withMessage("authorizedClientRowMapper cannot be null");
// @formatter:on
}
@Test
public void setAuthorizedClientParametersMapperWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.setAuthorizedClientParametersMapper(null))
.withMessage("authorizedClientParametersMapper cannot be null");
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, "principalName"))
.withMessage("clientRegistrationId cannot be empty");
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessage("principalName cannot be empty");
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenDoesNotExistThenReturnNull() {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient("registration-not-found", "principalName");
assertThat(authorizedClient).isNull();
}
@Test
public void loadAuthorizedClientWhenExistsThenReturnAuthorizedClient() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(expected.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(expected.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getScopes()).isEqualTo(expected.getAccessToken().getScopes());
assertThat(authorizedClient.getRefreshToken().getTokenValue())
.isEqualTo(expected.getRefreshToken().getTokenValue());
assertThat(authorizedClient.getRefreshToken().getIssuedAt()).isCloseTo(expected.getRefreshToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
}
@Test
public void loadAuthorizedClientWhenExistsButNotFoundInClientRegistrationRepositoryThenThrowDataRetrievalFailureException() {
given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(null);
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal);
assertThatExceptionOfType(DataRetrievalFailureException.class)
.isThrownBy(() -> this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName()))
.withMessage("The ClientRegistration with id '" + this.clientRegistration.getRegistrationId()
+ "' exists in the data source, however, it was not found in the ClientRegistrationRepository.");
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, principal))
.withMessage("authorizedClient cannot be null");
}
@Test
public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, null))
.withMessage("principal cannot be null");
}
@Test
public void saveAuthorizedClientWhenSaveThenLoadReturnsSaved() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient expected = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(expected, principal);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(expected.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(expected.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getScopes()).isEqualTo(expected.getAccessToken().getScopes());
assertThat(authorizedClient.getRefreshToken().getTokenValue())
.isEqualTo(expected.getRefreshToken().getTokenValue());
assertThat(authorizedClient.getRefreshToken().getIssuedAt()).isCloseTo(expected.getRefreshToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
// Test save/load of NOT NULL attributes only
principal = createPrincipal();
expected = createAuthorizedClient(principal, this.clientRegistration, true);
this.authorizedClientService.saveAuthorizedClient(expected, principal);
authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(expected.getClientRegistration());
assertThat(authorizedClient.getPrincipalName()).isEqualTo(expected.getPrincipalName());
assertThat(authorizedClient.getAccessToken().getTokenType())
.isEqualTo(expected.getAccessToken().getTokenType());
assertThat(authorizedClient.getAccessToken().getTokenValue())
.isEqualTo(expected.getAccessToken().getTokenValue());
assertThat(authorizedClient.getAccessToken().getIssuedAt()).isCloseTo(expected.getAccessToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getExpiresAt()).isCloseTo(expected.getAccessToken().getExpiresAt(),
within(1, ChronoUnit.MILLIS));
assertThat(authorizedClient.getAccessToken().getScopes()).isEmpty();
assertThat(authorizedClient.getRefreshToken()).isNull();
}
@Test
public void saveAuthorizedClientWhenSaveClientWithExistingPrimaryKeyThenUpdate() {
// Given a saved authorized client
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
// When a client with the same principal and registration id is saved
OAuth2AuthorizedClient updatedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(updatedClient, principal);
// Then the saved client is updated
OAuth2AuthorizedClient savedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(savedClient).isNotNull();
assertThat(savedClient.getClientRegistration()).isEqualTo(updatedClient.getClientRegistration());
assertThat(savedClient.getPrincipalName()).isEqualTo(updatedClient.getPrincipalName());
assertThat(savedClient.getAccessToken().getTokenType())
.isEqualTo(updatedClient.getAccessToken().getTokenType());
assertThat(savedClient.getAccessToken().getTokenValue())
.isEqualTo(updatedClient.getAccessToken().getTokenValue());
assertThat(savedClient.getAccessToken().getIssuedAt()).isCloseTo(updatedClient.getAccessToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
assertThat(savedClient.getAccessToken().getExpiresAt()).isCloseTo(updatedClient.getAccessToken().getExpiresAt(),
within(1, ChronoUnit.MILLIS));
assertThat(savedClient.getAccessToken().getScopes()).isEqualTo(updatedClient.getAccessToken().getScopes());
assertThat(savedClient.getRefreshToken().getTokenValue())
.isEqualTo(updatedClient.getRefreshToken().getTokenValue());
assertThat(savedClient.getRefreshToken().getIssuedAt()).isCloseTo(updatedClient.getRefreshToken().getIssuedAt(),
within(1, ChronoUnit.MILLIS));
}
@Test
public void saveLoadAuthorizedClientWhenCustomStrategiesSetThenCalled() throws Exception {
JdbcOAuth2AuthorizedClientService.OAuth2AuthorizedClientRowMapper authorizedClientRowMapper = spy(
new JdbcOAuth2AuthorizedClientService.OAuth2AuthorizedClientRowMapper(
this.clientRegistrationRepository));
this.authorizedClientService.setAuthorizedClientRowMapper(authorizedClientRowMapper);
JdbcOAuth2AuthorizedClientService.OAuth2AuthorizedClientParametersMapper authorizedClientParametersMapper = spy(
new JdbcOAuth2AuthorizedClientService.OAuth2AuthorizedClientParametersMapper());
this.authorizedClientService.setAuthorizedClientParametersMapper(authorizedClientParametersMapper);
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
this.authorizedClientService.loadAuthorizedClient(this.clientRegistration.getRegistrationId(),
principal.getName());
verify(authorizedClientRowMapper).mapRow(any(), anyInt());
verify(authorizedClientParametersMapper).apply(any());
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, "principalName"))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.clientRegistration.getRegistrationId(), null))
.withMessage("principalName cannot be empty");
}
@Test
public void removeAuthorizedClientWhenExistsThenRemoved() {
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNotNull();
this.authorizedClientService.removeAuthorizedClient(this.clientRegistration.getRegistrationId(),
principal.getName());
authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNull();
}
@Test
public void tableDefinitionWhenCustomThenAbleToOverride() {
CustomTableDefinitionJdbcOAuth2AuthorizedClientService customAuthorizedClientService = new CustomTableDefinitionJdbcOAuth2AuthorizedClientService(
new JdbcTemplate(createDb("custom-oauth2-client-schema.sql")), this.clientRegistrationRepository);
Authentication principal = createPrincipal();
OAuth2AuthorizedClient authorizedClient = createAuthorizedClient(principal, this.clientRegistration);
customAuthorizedClientService.saveAuthorizedClient(authorizedClient, principal);
authorizedClient = customAuthorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNotNull();
customAuthorizedClientService.removeAuthorizedClient(this.clientRegistration.getRegistrationId(),
principal.getName());
authorizedClient = customAuthorizedClientService
.loadAuthorizedClient(this.clientRegistration.getRegistrationId(), principal.getName());
assertThat(authorizedClient).isNull();
}
private static EmbeddedDatabase createDb() {
return createDb(OAUTH2_CLIENT_SCHEMA_SQL_RESOURCE);
}
private static EmbeddedDatabase createDb(String schema) {
// @formatter:off
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(EmbeddedDatabaseType.HSQL)
.setScriptEncoding("UTF-8")
.addScript(schema)
.build();
// @formatter:on
}
private static Authentication createPrincipal() {
return new TestingAuthenticationToken("principal-" + principalId++, "password");
}
private static OAuth2AuthorizedClient createAuthorizedClient(Authentication principal,
ClientRegistration clientRegistration) {
return createAuthorizedClient(principal, clientRegistration, false);
}
private static OAuth2AuthorizedClient createAuthorizedClient(Authentication principal,
ClientRegistration clientRegistration, boolean requiredAttributesOnly) {
OAuth2AccessToken accessToken;
if (!requiredAttributesOnly) {
accessToken = TestOAuth2AccessTokens.scopes("read", "write");
}
else {
accessToken = TestOAuth2AccessTokens.noScopes();
}
OAuth2RefreshToken refreshToken = null;
if (!requiredAttributesOnly) {
refreshToken = TestOAuth2RefreshTokens.refreshToken();
}
return new OAuth2AuthorizedClient(clientRegistration, principal.getName(), accessToken, refreshToken);
}
private static final class CustomTableDefinitionJdbcOAuth2AuthorizedClientService
extends JdbcOAuth2AuthorizedClientService {
private static final String COLUMN_NAMES = "clientRegistrationId, " + "principalName, " + "accessTokenType, "
+ "accessTokenValue, " + "accessTokenIssuedAt, " + "accessTokenExpiresAt, " + "accessTokenScopes, "
+ "refreshTokenValue, " + "refreshTokenIssuedAt";
private static final String TABLE_NAME = "oauth2AuthorizedClient";
private static final String PK_FILTER = "clientRegistrationId = ? AND principalName = ?";
private static final String LOAD_AUTHORIZED_CLIENT_SQL = "SELECT " + COLUMN_NAMES + " FROM " + TABLE_NAME
+ " WHERE " + PK_FILTER;
private static final String SAVE_AUTHORIZED_CLIENT_SQL = "INSERT INTO " + TABLE_NAME + " (" + COLUMN_NAMES
+ ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String REMOVE_AUTHORIZED_CLIENT_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + PK_FILTER;
private CustomTableDefinitionJdbcOAuth2AuthorizedClientService(JdbcOperations jdbcOperations,
ClientRegistrationRepository clientRegistrationRepository) {
super(jdbcOperations, clientRegistrationRepository);
setAuthorizedClientRowMapper(new OAuth2AuthorizedClientRowMapper(clientRegistrationRepository));
}
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
String principalName) {
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, clientRegistrationId),
new SqlParameterValue(Types.VARCHAR, principalName) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
List<OAuth2AuthorizedClient> result = this.jdbcOperations.query(LOAD_AUTHORIZED_CLIENT_SQL, pss,
this.authorizedClientRowMapper);
return !result.isEmpty() ? (T) result.get(0) : null;
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
List<SqlParameterValue> parameters = this.authorizedClientParametersMapper
.apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal));
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters.toArray());
this.jdbcOperations.update(SAVE_AUTHORIZED_CLIENT_SQL, pss);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
SqlParameterValue[] parameters = new SqlParameterValue[] {
new SqlParameterValue(Types.VARCHAR, clientRegistrationId),
new SqlParameterValue(Types.VARCHAR, principalName) };
PreparedStatementSetter pss = new ArgumentPreparedStatementSetter(parameters);
this.jdbcOperations.update(REMOVE_AUTHORIZED_CLIENT_SQL, pss);
}
private static final class OAuth2AuthorizedClientRowMapper implements RowMapper<OAuth2AuthorizedClient> {
private final ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientRowMapper(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
public OAuth2AuthorizedClient mapRow(ResultSet rs, int rowNum) throws SQLException {
String clientRegistrationId = rs.getString("clientRegistrationId");
ClientRegistration clientRegistration = this.clientRegistrationRepository
.findByRegistrationId(clientRegistrationId);
if (clientRegistration == null) {
throw new DataRetrievalFailureException(
"The ClientRegistration with id '" + clientRegistrationId + "' exists in the data source, "
+ "however, it was not found in the ClientRegistrationRepository.");
}
OAuth2AccessToken.TokenType tokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(rs.getString("accessTokenType"))) {
tokenType = OAuth2AccessToken.TokenType.BEARER;
}
String tokenValue = new String(rs.getBytes("accessTokenValue"), StandardCharsets.UTF_8);
Instant issuedAt = rs.getTimestamp("accessTokenIssuedAt").toInstant();
Instant expiresAt = rs.getTimestamp("accessTokenExpiresAt").toInstant();
Set<String> scopes = Collections.emptySet();
String accessTokenScopes = rs.getString("accessTokenScopes");
if (accessTokenScopes != null) {
scopes = StringUtils.commaDelimitedListToSet(accessTokenScopes);
}
OAuth2AccessToken accessToken = new OAuth2AccessToken(tokenType, tokenValue, issuedAt, expiresAt,
scopes);
OAuth2RefreshToken refreshToken = null;
byte[] refreshTokenValue = rs.getBytes("refreshTokenValue");
if (refreshTokenValue != null) {
tokenValue = new String(refreshTokenValue, StandardCharsets.UTF_8);
issuedAt = null;
Timestamp refreshTokenIssuedAt = rs.getTimestamp("refreshTokenIssuedAt");
if (refreshTokenIssuedAt != null) {
issuedAt = refreshTokenIssuedAt.toInstant();
}
refreshToken = new OAuth2RefreshToken(tokenValue, issuedAt);
}
String principalName = rs.getString("principalName");
return new OAuth2AuthorizedClient(clientRegistration, principalName, accessToken, refreshToken);
}
}
}
}
| 24,938 | 48.189349 | 148 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryReactiveOAuth2AuthorizedClientServiceTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class InMemoryReactiveOAuth2AuthorizedClientServiceTests {
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private InMemoryReactiveOAuth2AuthorizedClientService authorizedClientService;
private String clientRegistrationId = "github";
private String principalName = "username";
private Authentication principal = new TestingAuthenticationToken(this.principalName, "notused");
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(),
Instant.now().plus(Duration.ofDays(1)));
// @formatter:off
private ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(this.clientRegistrationId)
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://github.com/login/oauth/authorize")
.tokenUri("https://github.com/login/oauth/access_token")
.userInfoUri("https://api.github.com/user")
.userNameAttributeName("id")
.clientName("GitHub")
.clientId("clientId")
.clientSecret("clientSecret")
.build();
// @formatter:on
@BeforeEach
public void setup() {
this.authorizedClientService = new InMemoryReactiveOAuth2AuthorizedClientService(
this.clientRegistrationRepository);
}
@Test
public void constructorNullClientRegistrationRepositoryThenThrowsIllegalArgumentException() {
this.clientRegistrationRepository = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
this.clientRegistrationId = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
this.clientRegistrationId = "";
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
this.principalName = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
this.principalName = "";
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdNotFoundThenEmpty() {
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
.willReturn(Mono.empty());
StepVerifier.create(
this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.verifyComplete();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationFoundAndNotAuthorizedClientThenEmpty() {
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
.willReturn(Mono.just(this.clientRegistration));
StepVerifier.create(
this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName))
.verifyComplete();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationFoundThenFound() {
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
// @formatter:off
Mono<OAuth2AuthorizedClient> saveAndLoad = this.authorizedClientService
.saveAuthorizedClient(authorizedClient, this.principal)
.then(this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
StepVerifier.create(saveAndLoad)
.expectNext(authorizedClient)
.verifyComplete();
// @formatter:on
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientNullThenIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
// @formatter:on
}
@Test
public void saveAuthorizedClientWhenPrincipalNullThenIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
this.principal = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal));
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdNullThenIllegalArgumentException() {
this.clientRegistrationId = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdEmptyThenIllegalArgumentException() {
this.clientRegistrationId = "";
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenPrincipalNameNullThenIllegalArgumentException() {
this.principalName = null;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenPrincipalNameEmptyThenIllegalArgumentException() {
this.principalName = "";
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId, this.principalName));
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenClientIdThenNoException() {
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
.willReturn(Mono.empty());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
// @formatter:off
Mono<Void> saveAndDeleteAndLoad = this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)
.then(this.authorizedClientService
.removeAuthorizedClient(this.clientRegistrationId, this.principalName)
);
StepVerifier.create(saveAndDeleteAndLoad)
.verifyComplete();
// @formatter:on
}
@Test
public void removeAuthorizedClientWhenClientRegistrationFoundRemovedThenNotFound() {
given(this.clientRegistrationRepository.findByRegistrationId(this.clientRegistrationId))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
// @formatter:off
Mono<OAuth2AuthorizedClient> saveAndDeleteAndLoad = this.authorizedClientService.saveAuthorizedClient(authorizedClient, this.principal)
.then(this.authorizedClientService.removeAuthorizedClient(this.clientRegistrationId,
this.principalName))
.then(this.authorizedClientService.loadAuthorizedClient(this.clientRegistrationId, this.principalName));
StepVerifier.create(saveAndDeleteAndLoad)
.verifyComplete();
// @formatter:on
}
}
| 9,979 | 38.92 | 137 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link PasswordReactiveOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class PasswordReactiveOAuth2AuthorizedClientProviderTests {
private PasswordReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new PasswordReactiveOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(ReactiveOAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.password().build();
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotPasswordThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal).
build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedAndEmptyUsernameThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, null)
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedAndEmptyPasswordThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, null)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-expired", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken); // without refresh token
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-expired", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken, TestOAuth2RefreshTokens.refreshToken()); // with
// refresh
// token
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
// gh-7511
@Test
public void authorizeWhenPasswordAndAuthorizedAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken); // without refresh
// token
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
.block();
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 11,318 | 45.580247 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizeRequestTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;
/**
* Tests for {@link OAuth2AuthorizeRequest}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizeRequestTests {
private ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
private Authentication principal = new TestingAuthenticationToken("principal", "password");
private OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"),
TestOAuth2RefreshTokens.refreshToken());
@Test
public void withClientRegistrationIdWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withClientRegistrationId(null))
.withMessage("clientRegistrationId cannot be empty");
}
@Test
public void withAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest.withAuthorizedClient(null))
.withMessage("authorizedClient cannot be null");
}
@Test
public void withClientRegistrationIdWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).build())
.withMessage("principal cannot be null");
}
@Test
public void withClientRegistrationIdWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal((String) null).build())
.withMessage("principalName cannot be empty");
}
@Test
public void withClientRegistrationIdWhenAllValuesProvidedThenAllValuesAreSet() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.attributes((attrs) -> {
attrs.put("name1", "value1");
attrs.put("name2", "value2");
}).build();
assertThat(authorizeRequest.getClientRegistrationId()).isEqualTo(this.clientRegistration.getRegistrationId());
assertThat(authorizeRequest.getAuthorizedClient()).isNull();
assertThat(authorizeRequest.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizeRequest.getAttributes()).contains(entry("name1", "value1"), entry("name2", "value2"));
}
@Test
public void withAuthorizedClientWhenAllValuesProvidedThenAllValuesAreSet() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).attributes((attrs) -> {
attrs.put("name1", "value1");
attrs.put("name2", "value2");
}).build();
assertThat(authorizeRequest.getClientRegistrationId())
.isEqualTo(this.authorizedClient.getClientRegistration().getRegistrationId());
assertThat(authorizeRequest.getAuthorizedClient()).isEqualTo(this.authorizedClient);
assertThat(authorizeRequest.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizeRequest.getAttributes()).contains(entry("name1", "value1"), entry("name2", "value2"));
}
@Test
public void withClientRegistrationIdWhenPrincipalNameProvidedThenPrincipalCreated() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal("principalName")
.build();
assertThat(authorizeRequest.getClientRegistrationId()).isEqualTo(this.clientRegistration.getRegistrationId());
assertThat(authorizeRequest.getAuthorizedClient()).isNull();
assertThat(authorizeRequest.getPrincipal().getName()).isEqualTo("principalName");
}
}
| 5,154 | 44.619469 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientProviderBuilderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.DefaultPasswordTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link OAuth2AuthorizedClientProviderBuilder}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizedClientProviderBuilderTests {
private RestOperations accessTokenClient;
private DefaultClientCredentialsTokenResponseClient clientCredentialsTokenResponseClient;
private DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient;
private DefaultPasswordTokenResponseClient passwordTokenResponseClient;
private Authentication principal;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
this.accessTokenClient = mock(RestOperations.class);
given(this.accessTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class)))
.willReturn(new ResponseEntity(accessTokenResponse, HttpStatus.OK));
this.refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
this.refreshTokenTokenResponseClient.setRestOperations(this.accessTokenClient);
this.clientCredentialsTokenResponseClient = new DefaultClientCredentialsTokenResponseClient();
this.clientCredentialsTokenResponseClient.setRestOperations(this.accessTokenClient);
this.passwordTokenResponseClient = new DefaultPasswordTokenResponseClient();
this.passwordTokenResponseClient.setRestOperations(this.accessTokenClient);
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void providerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizedClientProviderBuilder.builder().provider(null));
}
@Test
public void buildWhenAuthorizationCodeProviderThenProviderAuthorizes() {
// @formatter:off
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.clientRegistration().build())
.principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext));
}
@Test
public void buildWhenRefreshTokenProviderThenProviderReauthorizes() {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.refreshToken(
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
.build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
TestClientRegistrations.clientRegistration().build(), this.principal.getName(), expiredAccessToken(),
TestOAuth2RefreshTokens.refreshToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient).isNotNull();
verify(this.accessTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
}
@Test
public void buildWhenClientCredentialsProviderThenProviderAuthorizes() {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.clientCredentials(
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
.build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.clientCredentials().build())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
verify(this.accessTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
}
@Test
public void buildWhenPasswordProviderThenProviderAuthorizes() {
// @formatter:off
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.password().build())
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient).isNotNull();
verify(this.accessTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
}
@Test
public void buildWhenAllProvidersThenProvidersAuthorize() {
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken(
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
.clientCredentials(
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
.build();
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
// authorization_code
// @formatter:off
OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext));
// refresh_token
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
OAuth2AuthorizationContext refreshTokenContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(refreshTokenContext);
assertThat(reauthorizedClient).isNotNull();
verify(this.accessTokenClient, times(1)).exchange(any(RequestEntity.class),
eq(OAuth2AccessTokenResponse.class));
// client_credentials
// @formatter:off
OAuth2AuthorizationContext clientCredentialsContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.clientCredentials().build())
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = authorizedClientProvider.authorize(clientCredentialsContext);
assertThat(authorizedClient).isNotNull();
verify(this.accessTokenClient, times(2)).exchange(any(RequestEntity.class),
eq(OAuth2AccessTokenResponse.class));
// password
// @formatter:off
OAuth2AuthorizationContext passwordContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.password().build())
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
authorizedClient = authorizedClientProvider.authorize(passwordContext);
assertThat(authorizedClient).isNotNull();
verify(this.accessTokenClient, times(3)).exchange(any(RequestEntity.class),
eq(OAuth2AccessTokenResponse.class));
}
@Test
public void buildWhenCustomProviderThenProviderCalled() {
OAuth2AuthorizedClientProvider customProvider = mock(OAuth2AuthorizedClientProvider.class);
// @formatter:off
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.provider(customProvider)
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(TestClientRegistrations.clientRegistration().build())
.principal(this.principal)
.build();
// @formatter:on
authorizedClientProvider.authorize(authorizationContext);
verify(customProvider).authorize(any(OAuth2AuthorizationContext.class));
}
private OAuth2AccessToken expiredAccessToken() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
}
}
| 11,324 | 46.584034 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ReactiveOAuth2AuthorizedClientProviderBuilderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link ReactiveOAuth2AuthorizedClientProviderBuilder}.
*
* @author Joe Grandja
*/
public class ReactiveOAuth2AuthorizedClientProviderBuilderTests {
private ClientRegistration.Builder clientRegistrationBuilder;
private Authentication principal;
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().tokenUri(tokenUri);
this.principal = new TestingAuthenticationToken("principal", "password");
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void providerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveOAuth2AuthorizedClientProviderBuilder.builder().provider(null));
}
@Test
public void buildWhenAuthorizationCodeProviderThenProviderAuthorizes() {
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.authorizationCode()
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder.build())
.principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationContext).block());
}
@Test
public void buildWhenRefreshTokenProviderThenProviderReauthorizes() throws Exception {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.refreshToken()
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(authorizationContext).block();
assertThat(reauthorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(1);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=refresh_token");
}
@Test
public void buildWhenClientCredentialsProviderThenProviderAuthorizes() throws Exception {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.clientCredentials()
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(1);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=client_credentials");
}
@Test
public void buildWhenPasswordProviderThenProviderAuthorizes() throws Exception {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder().password().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(
this.clientRegistrationBuilder.authorizationGrantType(AuthorizationGrantType.PASSWORD).build())
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
OAuth2AuthorizedClient authorizedClient = authorizedClientProvider.authorize(authorizationContext)
.block();
// @formatter:on
assertThat(authorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(1);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=password");
}
@Test
public void buildWhenAllProvidersThenProvidersAuthorize() throws Exception {
String accessTokenSuccessResponse = "{\n" + " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n" + " \"expires_in\": \"3600\"\n" + "}\n";
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
this.server.enqueue(jsonResponse(accessTokenSuccessResponse));
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder().authorizationCode().refreshToken().clientCredentials().password().build();
// authorization_code
// @formatter:off
OAuth2AuthorizationContext authorizationCodeContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder.build())
.principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> authorizedClientProvider.authorize(authorizationCodeContext).block());
// refresh_token
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistrationBuilder.build(),
this.principal.getName(), expiredAccessToken(), TestOAuth2RefreshTokens.refreshToken());
OAuth2AuthorizationContext refreshTokenContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient).principal(this.principal).build();
OAuth2AuthorizedClient reauthorizedClient = authorizedClientProvider.authorize(refreshTokenContext).block();
assertThat(reauthorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(1);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=refresh_token");
// client_credentials
// @formatter:off
OAuth2AuthorizationContext clientCredentialsContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).build())
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = authorizedClientProvider.authorize(clientCredentialsContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(2);
recordedRequest = this.server.takeRequest();
formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=client_credentials");
// password
// @formatter:off
OAuth2AuthorizationContext passwordContext = OAuth2AuthorizationContext
.withClientRegistration(
this.clientRegistrationBuilder.authorizationGrantType(AuthorizationGrantType.PASSWORD).build())
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
authorizedClient = authorizedClientProvider.authorize(passwordContext).block();
assertThat(authorizedClient).isNotNull();
assertThat(this.server.getRequestCount()).isEqualTo(3);
recordedRequest = this.server.takeRequest();
formParameters = recordedRequest.getBody().readUtf8();
assertThat(formParameters).contains("grant_type=password");
}
@Test
public void buildWhenCustomProviderThenProviderCalled() {
ReactiveOAuth2AuthorizedClientProvider customProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(customProvider.authorize(any())).willReturn(Mono.empty());
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.provider(customProvider)
.build();
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistrationBuilder.build())
.principal(this.principal)
.build();
// @formatter:on
authorizedClientProvider.authorize(authorizationContext).block();
verify(customProvider).authorize(any(OAuth2AuthorizationContext.class));
}
private OAuth2AccessToken expiredAccessToken() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", issuedAt, expiresAt);
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 12,181 | 45.319392 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizedClientTests.java | /*
* Copyright 2002-2017 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
*
* https://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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2AuthorizedClient}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizedClientTests {
private ClientRegistration clientRegistration;
private String principalName;
private OAuth2AccessToken accessToken;
@BeforeEach
public void setUp() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principalName = "principal";
this.accessToken = TestOAuth2AccessTokens.noScopes();
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClient(null, this.principalName, this.accessToken));
}
@Test
public void constructorWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, null, this.accessToken));
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, null));
}
@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principalName, this.accessToken);
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
assertThat(authorizedClient.getAccessToken()).isEqualTo(this.accessToken);
}
}
| 2,843 | 35.461538 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import reactor.test.publisher.PublisherProbe;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager}.
*
* @author Ankur Pathak
* @author Phil Clay
*/
public class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ReactiveOAuth2AuthorizedClientService authorizedClientService;
private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper;
private AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
private ArgumentCaptor<OAuth2AuthorizationContext> authorizationContextCaptor;
private PublisherProbe<Void> saveAuthorizedClientProbe;
private PublisherProbe<Void> removeAuthorizedClientProbe;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
this.authorizedClientService = mock(ReactiveOAuth2AuthorizedClientService.class);
this.saveAuthorizedClientProbe = PublisherProbe.empty();
given(this.authorizedClientService.saveAuthorizedClient(any(), any()))
.willReturn(this.saveAuthorizedClientProbe.mono());
this.removeAuthorizedClientProbe = PublisherProbe.empty();
given(this.authorizedClientService.removeAuthorizedClient(any(), any()))
.willReturn(this.removeAuthorizedClientProbe.mono());
this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
this.contextAttributesMapper = mock(Function.class);
given(this.contextAttributesMapper.apply(any())).willReturn(Mono.empty());
this.authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientService);
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(null,
this.authorizedClientService))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, null))
.withMessage("authorizedClientService cannot be null");
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null))
.withMessage("authorizeRequest cannot be null");
}
@Test
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
String clientRegistrationId = "invalid-registration-id";
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
.principal(this.principal).build();
given(this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)).willReturn(Mono.empty());
StepVerifier.create(this.authorizedClientManager.authorize(authorizeRequest))
.verifyError(IllegalArgumentException.class);
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
given(this.authorizedClientProvider.authorize(any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
StepVerifier.create(authorizedClient).verifyComplete();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class),
eq(this.principal));
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
PublisherProbe<Void> authorizationSuccessHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationSuccessHandler(
(client, principal, attributes) -> authorizationSuccessHandlerProbe.mono());
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
authorizationSuccessHandlerProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
}
@Test
public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()));
this.removeAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@Test
public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()));
this.removeAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@Test
public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@Test
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@Test
public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationFailureHandler(
(client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
authorizationFailureHandlerProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
// @formatter:off
StepVerifier.create(authorizedClient)
.expectNext(reauthorizedClient)
.verifyComplete();
// @formatter:on
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.empty());
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
StepVerifier.create(authorizedClient).expectNext(this.authorizedClient).verifyComplete();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class),
eq(this.principal));
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenSupportedProviderThenReauthorized() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
StepVerifier.create(authorizedClient).expectNext(reauthorizedClient).verifyComplete();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenRequestAttributeScopeThenMappedToContext() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build();
this.authorizedClientManager.setContextAttributesMapper(
new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
Mono<OAuth2AuthorizedClient> authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
// @formatter:off
StepVerifier.create(authorizedClient)
.expectNext(reauthorizedClient)
.verifyComplete();
// @formatter:on
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizationContext.getAttributes())
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
String[] requestScopeAttribute = authorizationContext
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
assertThat(requestScopeAttribute).contains("read", "write");
}
}
| 28,785 | 55.889328 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link AuthorizationCodeReactiveOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class AuthorizationCodeReactiveOAuth2AuthorizedClientProviderTests {
private AuthorizationCodeReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new AuthorizationCodeReactiveOAuth2AuthorizedClientProvider();
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, "principal",
TestOAuth2AccessTokens.scopes("read", "write"));
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientProvider.authorize(null).block());
}
@Test
public void authorizeWhenNotAuthorizationCodeThenUnableToAuthorize() {
ClientRegistration clientCredentialsClient = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientCredentialsClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenAuthorizationCodeAndAuthorizedThenNotAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenAuthorizationCodeAndNotAuthorizedThenAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext).block());
}
}
| 3,762 | 37.793814 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link ClientCredentialsReactiveOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class ClientCredentialsReactiveOAuth2AuthorizedClientProviderTests {
private ClientCredentialsReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new ClientCredentialsReactiveOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(ReactiveOAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.clientCredentials().build();
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null).block())
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotClientCredentialsThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
@Test
public void authorizeWhenClientCredentialsAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenClientCredentialsAndTokenExpiredThenReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234",
issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext).block();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenClientCredentialsAndTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext).block()).isNull();
}
// gh-7511
@Test
public void authorizeWhenClientCredentialsAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken);
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext)
.block();
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 9,199 | 44.098039 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/RefreshTokenOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link RefreshTokenOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class RefreshTokenOAuth2AuthorizedClientProviderTests {
private RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider;
private OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken expiredAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
expiredAccessToken, TestOAuth2RefreshTokens.refreshToken());
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotAuthorizedThenUnableToReauthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenAuthorizedAndRefreshTokenIsNullThenUnableToReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), this.authorizedClient.getAccessToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), this.authorizedClient.getRefreshToken());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
// gh-7511
@Test
public void authorizeWhenAuthorizedAndAccessTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse()
.refreshToken("new-refresh-token").build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken, this.authorizedClient.getRefreshToken());
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
@Test
public void authorizeWhenAuthorizedAndAccessTokenExpiredThenReauthorize() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses
.accessTokenResponse()
.refreshToken("new-refresh-token")
.build();
// @formatter:on
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
assertThat(reauthorizedClient.getRefreshToken()).isEqualTo(accessTokenResponse.getRefreshToken());
}
@Test
public void authorizeWhenAuthorizedAndRequestScopeProvidedThenScopeRequested() {
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses
.accessTokenResponse()
.refreshToken("new-refresh-token")
.build();
// @formatter:on
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
String[] requestScope = new String[] { "read", "write" };
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, requestScope)
.build();
// @formatter:on
this.authorizedClientProvider.authorize(authorizationContext);
ArgumentCaptor<OAuth2RefreshTokenGrantRequest> refreshTokenGrantRequestArgCaptor = ArgumentCaptor
.forClass(OAuth2RefreshTokenGrantRequest.class);
verify(this.accessTokenResponseClient).getTokenResponse(refreshTokenGrantRequestArgCaptor.capture());
assertThat(refreshTokenGrantRequestArgCaptor.getValue().getScopes())
.isEqualTo(new HashSet<>(Arrays.asList(requestScope)));
}
@Test
public void authorizeWhenAuthorizedAndInvalidRequestScopeProvidedThenThrowIllegalArgumentException() {
String invalidRequestScope = "read write";
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME, invalidRequestScope)
.build();
// @formatter:on
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(authorizationContext))
.withMessageStartingWith("The context attribute must be of type String[] '"
+ OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'");
}
}
| 11,232 | 43.224409 | 108 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link AuthorizedClientServiceOAuth2AuthorizedClientManager}.
*
* @author Joe Grandja
*/
public class AuthorizedClientServiceOAuth2AuthorizedClientManagerTests {
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientService authorizedClientService;
private OAuth2AuthorizedClientProvider authorizedClientProvider;
private Function contextAttributesMapper;
private OAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private OAuth2AuthorizationFailureHandler authorizationFailureHandler;
private AuthorizedClientServiceOAuth2AuthorizedClientManager authorizedClientManager;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
private ArgumentCaptor<OAuth2AuthorizationContext> authorizationContextCaptor;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
this.authorizedClientService = mock(OAuth2AuthorizedClientService.class);
this.authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
this.contextAttributesMapper = mock(Function.class);
this.authorizationSuccessHandler = spy(new OAuth2AuthorizationSuccessHandler() {
@Override
public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
Map<String, Object> attributes) {
AuthorizedClientServiceOAuth2AuthorizedClientManagerTests.this.authorizedClientService
.saveAuthorizedClient(authorizedClient, principal);
}
});
this.authorizationFailureHandler = spy(new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> this.authorizedClientService
.removeAuthorizedClient(clientRegistrationId, principal.getName())));
this.authorizedClientManager = new AuthorizedClientServiceOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientService);
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
this.authorizedClientManager.setAuthorizationSuccessHandler(this.authorizationSuccessHandler);
this.authorizedClientManager.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(null, this.authorizedClientService))
.withMessage("clientRegistrationRepository cannot be null");
// @formatter:on
}
@Test
public void constructorWhenOAuth2AuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthorizedClientServiceOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
.withMessage("authorizedClientService cannot be null");
// @formatter:on
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
// @formatter:on
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
// @formatter:on
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
// @formatter:on
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.authorize(null))
.withMessage("authorizeRequest cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId("invalid-registration-id")
.principal(this.principal).build();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.withMessage("Could not find ClientRegistration with id 'invalid-registration-id'");
// @formatter:on
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isNull();
verifyNoInteractions(this.authorizationSuccessHandler);
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(this.authorizedClient);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(this.authorizedClient), eq(this.principal),
any());
verify(this.authorizedClientService).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal));
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientService.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()))).willReturn(this.authorizedClient);
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
any());
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
verifyNoInteractions(this.authorizationSuccessHandler);
verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenSupportedProviderThenReauthorized() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
any());
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenRequestAttributeScopeThenMappedToContext() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// Override the mock with the default
this.authorizedClientManager.setContextAttributesMapper(
new AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).attribute(OAuth2ParameterNames.SCOPE, "read write").build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizationContext.getAttributes())
.containsKey(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
String[] requestScopeAttribute = authorizationContext
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
assertThat(requestScopeAttribute).contains("read", "write");
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
any());
verify(this.authorizedClientService).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal));
}
@Test
public void reauthorizeWhenErrorCodeMatchThenRemoveAuthorizedClient() {
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());
verify(this.authorizedClientService).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal.getName()));
}
@Test
public void reauthorizeWhenErrorCodeDoesNotMatchThenDoNotRemoveAuthorizedClient() {
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
new OAuth2Error("non-matching-error-code", null, null), this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.build();
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
// @formatter:on
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());
verifyNoInteractions(this.authorizedClientService);
}
}
| 19,219 | 51.228261 | 120 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DelegatingOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class DelegatingOAuth2AuthorizedClientProviderTests {
@Test
public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(new OAuth2AuthorizedClientProvider[0]));
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingOAuth2AuthorizedClientProvider(Collections.emptyList()));
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
mock(OAuth2AuthorizedClientProvider.class));
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null))
.withMessage("context cannot be null");
}
@Test
public void authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient() {
Authentication principal = new TestingAuthenticationToken("principal", "password");
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(),
TestOAuth2AccessTokens.noScopes());
OAuth2AuthorizedClientProvider authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider.authorize(any())).willReturn(authorizedClient);
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
mock(OAuth2AuthorizedClientProvider.class), mock(OAuth2AuthorizedClientProvider.class),
authorizedClientProvider);
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
.principal(principal).build();
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context);
assertThat(reauthorizedClient).isSameAs(authorizedClient);
}
@Test
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
.principal(new TestingAuthenticationToken("principal", "password")).build();
DelegatingOAuth2AuthorizedClientProvider delegate = new DelegatingOAuth2AuthorizedClientProvider(
mock(OAuth2AuthorizedClientProvider.class), mock(OAuth2AuthorizedClientProvider.class));
assertThat(delegate.authorize(context)).isNull();
}
}
| 4,011 | 45.651163 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/OAuth2AuthorizationContextTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;
/**
* Tests for {@link OAuth2AuthorizationContext}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationContextTests {
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication principal;
@BeforeEach
public void setup() {
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, "principal",
TestOAuth2AccessTokens.scopes("read", "write"));
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void withClientRegistrationWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(null).build())
.withMessage("clientRegistration cannot be null");
}
@Test
public void withAuthorizedClientWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withAuthorizedClient(null).build())
.withMessage("authorizedClient cannot be null");
}
@Test
public void withClientRegistrationWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> OAuth2AuthorizationContext.withClientRegistration(this.clientRegistration).build())
.withMessage("principal cannot be null");
}
@Test
public void withAuthorizedClientWhenAllValuesProvidedThenAllValuesAreSet() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attributes) -> {
attributes.put("attribute1", "value1");
attributes.put("attribute2", "value2");
})
.build();
// @formatter:on
assertThat(authorizationContext.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isSameAs(this.principal);
assertThat(authorizationContext.getAttributes()).contains(entry("attribute1", "value1"),
entry("attribute2", "value2"));
}
}
| 3,591 | 37.212766 | 105 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/PasswordOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link PasswordOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class PasswordOAuth2AuthorizedClientProviderTests {
private PasswordOAuth2AuthorizedClientProvider authorizedClientProvider;
private OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new PasswordOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.password().build();
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotPasswordThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedAndEmptyUsernameThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, null)
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedAndEmptyPasswordThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, null)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenPasswordAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenPasswordAndAuthorizedWithoutRefreshTokenAndTokenExpiredThenReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-expired", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken); // without refresh token
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenPasswordAndAuthorizedWithRefreshTokenAndTokenExpiredThenNotReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-expired", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken, TestOAuth2RefreshTokens.refreshToken()); // with
// refresh
// token
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
// gh-7511
@Test
public void authorizeWhenPasswordAndAuthorizedAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.plus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken); // without refresh
// token
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.attribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, "username")
.attribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, "password")
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 11,123 | 45.157676 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/DelegatingReactiveOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DelegatingReactiveOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class DelegatingReactiveOAuth2AuthorizedClientProviderTests {
@Test
public void constructorWhenProvidersIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(
new ReactiveOAuth2AuthorizedClientProvider[0]));
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingReactiveOAuth2AuthorizedClientProvider(Collections.emptyList()));
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
mock(ReactiveOAuth2AuthorizedClientProvider.class));
assertThatIllegalArgumentException().isThrownBy(() -> delegate.authorize(null).block())
.withMessage("context cannot be null");
}
@Test
public void authorizeWhenProviderCanAuthorizeThenReturnAuthorizedClient() {
Authentication principal = new TestingAuthenticationToken("principal", "password");
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration, principal.getName(),
TestOAuth2AccessTokens.noScopes());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(
ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(
ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider3 = mock(
ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider3.authorize(any())).willReturn(Mono.just(authorizedClient));
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
authorizedClientProvider1, authorizedClientProvider2, authorizedClientProvider3);
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
.principal(principal).build();
OAuth2AuthorizedClient reauthorizedClient = delegate.authorize(context).block();
assertThat(reauthorizedClient).isSameAs(authorizedClient);
}
@Test
public void authorizeWhenProviderCantAuthorizeThenReturnNull() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2AuthorizationContext context = OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
.principal(new TestingAuthenticationToken("principal", "password")).build();
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider1 = mock(
ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider1.authorize(any())).willReturn(Mono.empty());
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider2 = mock(
ReactiveOAuth2AuthorizedClientProvider.class);
given(authorizedClientProvider2.authorize(any())).willReturn(Mono.empty());
DelegatingReactiveOAuth2AuthorizedClientProvider delegate = new DelegatingReactiveOAuth2AuthorizedClientProvider(
authorizedClientProvider1, authorizedClientProvider2);
assertThat(delegate.authorize(context).block()).isNull();
}
}
| 4,946 | 48.969697 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/JwtBearerOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link JwtBearerOAuth2AuthorizedClientProvider}.
*
* @author Hassene Laaribi
* @author Joe Grandja
*/
public class JwtBearerOAuth2AuthorizedClientProviderTests {
private JwtBearerOAuth2AuthorizedClientProvider authorizedClientProvider;
private OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Jwt jwtAssertion;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
// @formatter:off
this.clientRegistration = ClientRegistration.withRegistrationId("jwt-bearer")
.clientId("client-id")
.clientSecret("client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.tokenUri("https://example.com/oauth2/token")
.build();
// @formatter:on
this.jwtAssertion = TestJwts.jwt().build();
this.principal = new TestingAuthenticationToken(this.jwtAssertion, this.jwtAssertion);
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.withMessage("accessTokenResponseClient cannot be null");
}
@Test
public void setJwtAssertionResolverWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setJwtAssertionResolver(null))
.withMessage("jwtAssertionResolver cannot be null");
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotJwtBearerThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenJwtBearerAndTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.scopes("read", "write"));
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenJwtBearerAndTokenExpiredThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(30));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234",
issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenJwtBearerAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.plus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken);
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtDoesNotResolveThenUnableToAuthorize() {
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(new TestingAuthenticationToken("user", "password"))
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenJwtBearerAndNotAuthorizedAndJwtResolvesThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenCustomJwtAssertionResolverSetThenUsed() {
Function<OAuth2AuthorizationContext, Jwt> jwtAssertionResolver = mock(Function.class);
given(jwtAssertionResolver.apply(any())).willReturn(this.jwtAssertion);
this.authorizedClientProvider.setJwtAssertionResolver(jwtAssertionResolver);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
TestingAuthenticationToken principal = new TestingAuthenticationToken("user", "password");
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
verify(jwtAssertionResolver).apply(any());
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 11,673 | 44.248062 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/InMemoryOAuth2AuthorizedClientServiceTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatObject;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link InMemoryOAuth2AuthorizedClientService}.
*
* @author Joe Grandja
* @author Vedran Pavic
*/
public class InMemoryOAuth2AuthorizedClientServiceTests {
private String principalName1 = "principal-1";
private String principalName2 = "principal-2";
private ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();
private ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
private ClientRegistration registration3 = TestClientRegistrations.clientRegistration().clientId("client-3")
.registrationId("registration-3").build();
private ClientRegistrationRepository clientRegistrationRepository = new InMemoryClientRegistrationRepository(
this.registration1, this.registration2, this.registration3);
private InMemoryOAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(
this.clientRegistrationRepository);
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(null));
}
@Test
public void constructorWhenAuthorizedClientsIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository, null))
.withMessage("authorizedClients cannot be empty");
// @formatter:on
}
@Test
public void constructorWhenAuthorizedClientsProvidedThenUseProvidedAuthorizedClients() {
String registrationId = this.registration3.getRegistrationId();
Map<OAuth2AuthorizedClientId, OAuth2AuthorizedClient> authorizedClients = Collections.singletonMap(
new OAuth2AuthorizedClientId(this.registration3.getRegistrationId(), this.principalName1),
mock(OAuth2AuthorizedClient.class));
ClientRegistrationRepository clientRegistrationRepository = mock(ClientRegistrationRepository.class);
given(clientRegistrationRepository.findByRegistrationId(eq(registrationId))).willReturn(this.registration3);
InMemoryOAuth2AuthorizedClientService authorizedClientService = new InMemoryOAuth2AuthorizedClientService(
clientRegistrationRepository, authorizedClients);
assertThatObject(authorizedClientService.loadAuthorizedClient(registrationId, this.principalName1)).isNotNull();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.loadAuthorizedClient(null, this.principalName1));
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.loadAuthorizedClient(this.registration1.getRegistrationId(), null));
}
@Test
public void loadAuthorizedClientWhenClientRegistrationNotFoundThenReturnNull() {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient("registration-not-found", this.principalName1);
assertThat(authorizedClient).isNull();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationFoundButNotAssociatedToPrincipalThenReturnNull() {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration1.getRegistrationId(), "principal-not-found");
assertThat(authorizedClient).isNull();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationFoundAndAssociatedToPrincipalThenReturnAuthorizedClient() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName1);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.saveAuthorizedClient(null, mock(Authentication.class)));
}
@Test
public void saveAuthorizedClientWhenPrincipalIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientService.saveAuthorizedClient(mock(OAuth2AuthorizedClient.class), null));
}
@Test
public void saveAuthorizedClientWhenSavedThenCanLoad() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration3, this.principalName2,
mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration3.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientService.removeAuthorizedClient(null, this.principalName2));
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientService
.removeAuthorizedClient(this.registration3.getRegistrationId(), null));
}
@Test
public void removeAuthorizedClientWhenSavedThenRemoved() {
Authentication authentication = mock(Authentication.class);
given(authentication.getName()).willReturn(this.principalName2);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName2,
mock(OAuth2AccessToken.class));
this.authorizedClientService.saveAuthorizedClient(authorizedClient, authentication);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNotNull();
this.authorizedClientService.removeAuthorizedClient(this.registration2.getRegistrationId(),
this.principalName2);
loadedAuthorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration2.getRegistrationId(), this.principalName2);
assertThat(loadedAuthorizedClient).isNull();
}
}
| 8,515 | 45.791209 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/ClientCredentialsOAuth2AuthorizedClientProviderTests.java | /*
* Copyright 2002-2019 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
*
* https://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;
import java.time.Duration;
import java.time.Instant;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link ClientCredentialsOAuth2AuthorizedClientProvider}.
*
* @author Joe Grandja
*/
public class ClientCredentialsOAuth2AuthorizedClientProviderTests {
private ClientCredentialsOAuth2AuthorizedClientProvider authorizedClientProvider;
private OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> accessTokenResponseClient;
private ClientRegistration clientRegistration;
private Authentication principal;
@BeforeEach
public void setup() {
this.authorizedClientProvider = new ClientCredentialsOAuth2AuthorizedClientProvider();
this.accessTokenResponseClient = mock(OAuth2AccessTokenResponseClient.class);
this.authorizedClientProvider.setAccessTokenResponseClient(this.accessTokenResponseClient);
this.clientRegistration = TestClientRegistrations.clientCredentials().build();
this.principal = new TestingAuthenticationToken("principal", "password");
}
@Test
public void setAccessTokenResponseClientWhenClientIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setAccessTokenResponseClient(null))
.isInstanceOf(IllegalArgumentException.class).withMessage("accessTokenResponseClient cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(null))
.withMessage("clockSkew cannot be null");
// @formatter:on
}
@Test
public void setClockSkewWhenNegativeSecondsThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(-1)))
.withMessage("clockSkew must be >= 0");
// @formatter:on
}
@Test
public void setClockWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.setClock(null))
.withMessage("clock cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenContextIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientProvider.authorize(null))
.withMessage("context cannot be null");
// @formatter:on
}
@Test
public void authorizeWhenNotClientCredentialsThenUnableToAuthorize() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
@Test
public void authorizeWhenClientCredentialsAndNotAuthorizedThenAuthorize() {
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withClientRegistration(this.clientRegistration)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenClientCredentialsAndTokenExpiredThenReauthorize() {
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(60));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234",
issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), accessToken);
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(authorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
@Test
public void authorizeWhenClientCredentialsAndTokenNotExpiredThenNotReauthorize() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes());
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
assertThat(this.authorizedClientProvider.authorize(authorizationContext)).isNull();
}
// gh-7511
@Test
public void authorizeWhenClientCredentialsAndTokenNotExpiredButClockSkewForcesExpiryThenReauthorize() {
Instant now = Instant.now();
Instant issuedAt = now.minus(Duration.ofMinutes(60));
Instant expiresAt = now.minus(Duration.ofMinutes(1));
OAuth2AccessToken expiresInOneMinAccessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token-1234", issuedAt, expiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), expiresInOneMinAccessToken);
// Shorten the lifespan of the access token by 90 seconds, which will ultimately
// force it to expire on the client
this.authorizedClientProvider.setClockSkew(Duration.ofSeconds(90));
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
OAuth2AuthorizationContext authorizationContext = OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(this.principal)
.build();
// @formatter:on
OAuth2AuthorizedClient reauthorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
assertThat(reauthorizedClient.getClientRegistration()).isSameAs(this.clientRegistration);
assertThat(reauthorizedClient.getPrincipalName()).isEqualTo(this.principal.getName());
assertThat(reauthorizedClient.getAccessToken()).isEqualTo(accessTokenResponse.getAccessToken());
}
}
| 9,066 | 43.886139 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserServiceTests.java | /*
* Copyright 2002-2022 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
*
* https://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.userinfo;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.web.client.RestOperations;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DefaultOAuth2UserService}.
*
* @author Joe Grandja
* @author Eddú Meléndez
*/
public class DefaultOAuth2UserServiceTests {
private ClientRegistration.Builder clientRegistrationBuilder;
private OAuth2AccessToken accessToken;
private DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
// @formatter:off
this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration()
.userInfoUri(null)
.userNameAttributeName(null);
// @formatter:on
this.accessToken = TestOAuth2AccessTokens.noScopes();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void setRequestEntityConverterWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRequestEntityConverter(null));
}
@Test
public void setRestOperationsWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.setRestOperations(null));
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.userService.loadUser(null));
}
@Test
public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() {
ClientRegistration clientRegistration = this.clientRegistrationBuilder.build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_info_uri");
}
@Test
public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() {
// @formatter:off
ClientRegistration clientRegistration = this.clientRegistrationBuilder
.userInfoUri("https://provider.com/user")
.build();
// @formatter:on
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining("missing_user_name_attribute");
}
@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes().size()).isEqualTo(6);
assertThat((String) user.getAttribute("user-name")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
@Test
public void loadUserWhenUserInfoErrorResponseWwwAuthenticateHeaderThenThrowOAuth2AuthenticationException() {
String wwwAuthenticateHeader = "Bearer realm=\"auth-realm\" error=\"insufficient_scope\" error_description=\"The access token expired\"";
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticateHeader);
response.setResponseCode(400);
this.server.enqueue(response);
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: insufficient_scope, Error Description: The access token expired");
}
@Test
public void loadUserWhenUserInfoErrorResponseThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoErrorResponse = "{\n"
+ " \"error\": \"invalid_token\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoErrorResponse).setResponseCode(400));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource")
.withMessageContaining("Error Code: invalid_token");
}
@Test
public void loadUserWhenServerErrorThenThrowOAuth2AuthenticationException() {
this.server.enqueue(new MockResponse().setResponseCode(500));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource: 500 Server Error");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
String userInfoUri = "https://invalid-provider.com/user";
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
// gh-5294
@Test
public void loadUserWhenUserInfoSuccessResponseThenAcceptHeaderJson() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
assertThat(this.server.takeRequest(1, TimeUnit.SECONDS).getHeader(HttpHeaders.ACCEPT))
.isEqualTo(MediaType.APPLICATION_JSON_VALUE);
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.GET.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodFormSuccessResponseThenHttpMethodPost() throws Exception {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"user-name\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(userInfoResponse));
String userInfoUri = this.server.url("/user").toString();
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM).userNameAttributeName("user-name").build();
this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
assertThat(request.getBody().readUtf8()).isEqualTo("access_token=" + this.accessToken.getTokenValue());
}
@Test
public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.scopes("message:read", "message:write"));
OAuth2User user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(3);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:read"));
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:write"));
}
@Test
public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.noScopes());
OAuth2User user = userService.loadUser(request);
assertThat(user.getAuthorities()).hasSize(1);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
}
// gh-8764
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2AuthenticationException() {
String userInfoUri = this.server.url("/user").toString();
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
response.setBody("invalid content type");
this.server.enqueue(response);
ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(
() -> this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken)))
.withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource "
+ "from '" + userInfoUri + "': response contains invalid content type 'text/plain'.");
}
private DefaultOAuth2UserService withMockResponse(Map<String, Object> response) {
ResponseEntity<Map<String, Object>> responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = mock(Converter.class);
RestOperations rest = mock(RestOperations.class);
given(rest.exchange(nullable(RequestEntity.class), any(ParameterizedTypeReference.class)))
.willReturn(responseEntity);
DefaultOAuth2UserService userService = new DefaultOAuth2UserService();
userService.setRequestEntityConverter(requestEntityConverter);
userService.setRestOperations(rest);
return userService;
}
private MockResponse jsonResponse(String json) {
return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json);
}
}
| 18,151 | 46.643045 | 139 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DelegatingOAuth2UserServiceTests.java | /*
* Copyright 2002-2017 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
*
* https://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.userinfo;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.user.OAuth2User;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link DelegatingOAuth2UserService}.
*
* @author Joe Grandja
*/
public class DelegatingOAuth2UserServiceTests {
@Test
public void constructorWhenUserServicesIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new DelegatingOAuth2UserService<>(null));
}
@Test
public void constructorWhenUserServicesIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DelegatingOAuth2UserService<>(Collections.emptyList()));
}
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(
Arrays.asList(userService, userService));
assertThatIllegalArgumentException().isThrownBy(() -> delegatingUserService.loadUser(null));
}
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCanLoadThenReturnUser() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
OAuth2User mockUser = mock(OAuth2User.class);
given(userService3.loadUser(any(OAuth2UserRequest.class))).willReturn(mockUser);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(
Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isEqualTo(mockUser);
}
@Test
@SuppressWarnings("unchecked")
public void loadUserWhenUserServiceCannotLoadThenReturnNull() {
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService1 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService2 = mock(OAuth2UserService.class);
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService3 = mock(OAuth2UserService.class);
DelegatingOAuth2UserService<OAuth2UserRequest, OAuth2User> delegatingUserService = new DelegatingOAuth2UserService<>(
Arrays.asList(userService1, userService2, userService3));
OAuth2User loadedUser = delegatingUserService.loadUser(mock(OAuth2UserRequest.class));
assertThat(loadedUser).isNull();
}
}
| 3,691 | 41.930233 | 119 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestEntityConverterTests.java | /*
* 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
*
* https://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.userinfo;
import java.time.Instant;
import java.util.Arrays;
import java.util.LinkedHashSet;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OAuth2UserRequestEntityConverter}.
*
* @author Joe Grandja
*/
public class OAuth2UserRequestEntityConverterTests {
private OAuth2UserRequestEntityConverter converter = new OAuth2UserRequestEntityConverter();
@SuppressWarnings("unchecked")
@Test
public void convertWhenAuthenticationMethodHeaderThenGetRequest() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
OAuth2UserRequest userRequest = new OAuth2UserRequest(clientRegistration, this.createAccessToken());
RequestEntity<?> requestEntity = this.converter.convert(userRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.GET);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON);
assertThat(headers.getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + userRequest.getAccessToken().getTokenValue());
}
@SuppressWarnings("unchecked")
@Test
public void convertWhenAuthenticationMethodFormThenPostRequest() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.userInfoAuthenticationMethod(AuthenticationMethod.FORM).build();
OAuth2UserRequest userRequest = new OAuth2UserRequest(clientRegistration, this.createAccessToken());
RequestEntity<?> requestEntity = this.converter.convert(userRequest);
assertThat(requestEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(requestEntity.getUrl().toASCIIString())
.isEqualTo(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri());
HttpHeaders headers = requestEntity.getHeaders();
assertThat(headers.getAccept()).contains(MediaType.APPLICATION_JSON);
assertThat(headers.getContentType())
.isEqualTo(MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8"));
MultiValueMap<String, String> formParameters = (MultiValueMap<String, String>) requestEntity.getBody();
assertThat(formParameters.getFirst(OAuth2ParameterNames.ACCESS_TOKEN))
.isEqualTo(userRequest.getAccessToken().getTokenValue());
}
private OAuth2AccessToken createAccessToken() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234",
Instant.now(), Instant.now().plusSeconds(3600), new LinkedHashSet<>(Arrays.asList("read", "write")));
return accessToken;
}
}
| 4,014 | 44.625 | 112 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserRequestTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.userinfo;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link OAuth2UserRequest}.
*
* @author Joe Grandja
*/
public class OAuth2UserRequestTests {
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private Map<String, Object> additionalParameters;
@BeforeEach
public void setUp() {
// @formatter:off
this.clientRegistration = ClientRegistration.withRegistrationId("registration-1")
.clientId("client-1")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("https://client.com")
.scope(new LinkedHashSet<>(Arrays.asList("scope1", "scope2")))
.authorizationUri("https://provider.com/oauth2/authorization")
.tokenUri("https://provider.com/oauth2/token")
.clientName("Client 1")
.build();
// @formatter:on
this.accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token-1234", Instant.now(),
Instant.now().plusSeconds(60), new LinkedHashSet<>(Arrays.asList("scope1", "scope2")));
this.additionalParameters = new HashMap<>();
this.additionalParameters.put("param1", "value1");
this.additionalParameters.put("param2", "value2");
}
@Test
public void constructorWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserRequest(null, this.accessToken));
}
@Test
public void constructorWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2UserRequest(this.clientRegistration, null));
}
@Test
public void constructorWhenAllParametersProvidedAndValidThenCreated() {
OAuth2UserRequest userRequest = new OAuth2UserRequest(this.clientRegistration, this.accessToken,
this.additionalParameters);
assertThat(userRequest.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(userRequest.getAccessToken()).isEqualTo(this.accessToken);
assertThat(userRequest.getAdditionalParameters()).containsAllEntriesOf(this.additionalParameters);
}
}
| 3,469 | 37.131868 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/userinfo/DefaultReactiveOAuth2UserServiceTests.java | /*
* Copyright 2002-2022 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
*
* https://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.userinfo;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* @author Rob Winch
* @author Eddú Meléndez
* @since 5.1
*/
public class DefaultReactiveOAuth2UserServiceTests {
private ClientRegistration.Builder clientRegistration;
private DefaultReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
private MockWebServer server;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
String userInfoUri = this.server.url("/user").toString();
// @formatter:off
this.clientRegistration = TestClientRegistrations.clientRegistration()
.userInfoUri(userInfoUri);
// @formatter:on
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void loadUserWhenUserRequestIsNullThenThrowIllegalArgumentException() {
OAuth2UserRequest request = null;
StepVerifier.create(this.userService.loadUser(request)).expectError(IllegalArgumentException.class).verify();
}
@Test
public void loadUserWhenUserInfoUriIsNullThenThrowOAuth2AuthenticationException() {
this.clientRegistration.userInfoUri(null);
StepVerifier.create(this.userService.loadUser(oauth2UserRequest())).expectErrorSatisfies((ex) -> assertThat(ex)
.isInstanceOf(OAuth2AuthenticationException.class).hasMessageContaining("missing_user_info_uri"))
.verify();
}
@Test
public void loadUserWhenUserNameAttributeNameIsNullThenThrowOAuth2AuthenticationException() {
this.clientRegistration.userNameAttributeName(null);
// @formatter:off
StepVerifier.create(this.userService.loadUser(oauth2UserRequest()))
.expectErrorSatisfies((ex) -> assertThat(ex)
.isInstanceOf(OAuth2AuthenticationException.class)
.hasMessageContaining("missing_user_name_attribute")
)
.verify();
// @formatter:on
}
@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
OAuth2User user = this.userService.loadUser(oauth2UserRequest()).block();
assertThat(user.getName()).isEqualTo("user1");
assertThat(user.getAttributes().size()).isEqualTo(6);
assertThat((String) user.getAttribute("id")).isEqualTo("user1");
assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
assertThat((String) user.getAttribute("address")).isEqualTo("address");
assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
assertThat(user.getAuthorities().size()).isEqualTo(1);
assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
assertThat(userAuthority.getAuthority()).isEqualTo("OAUTH2_USER");
assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
// gh-9336
@Test
public void loadUserWhenUserInfo201CreatedResponseThenReturnUser() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(new MockResponse().setResponseCode(201)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(userInfoResponse));
assertThatNoException().isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block());
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodHeaderSuccessResponseThenHttpMethodGet() throws Exception {
this.clientRegistration.userInfoAuthenticationMethod(AuthenticationMethod.HEADER);
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
this.userService.loadUser(oauth2UserRequest()).block();
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.GET.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-5500
@Test
public void loadUserWhenAuthenticationMethodFormSuccessResponseThenHttpMethodPost() throws Exception {
this.clientRegistration.userInfoAuthenticationMethod(AuthenticationMethod.FORM);
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n"
+ "}\n";
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
this.userService.loadUser(oauth2UserRequest()).block();
RecordedRequest request = this.server.takeRequest();
assertThat(request.getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).contains(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
assertThat(request.getBody().readUtf8()).isEqualTo("access_token=" + this.accessToken.getTokenValue());
}
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidThenThrowOAuth2AuthenticationException() {
// @formatter:off
String userInfoResponse = "{\n"
+ " \"id\": \"user1\",\n"
+ " \"first-name\": \"first\",\n"
+ " \"last-name\": \"last\",\n"
+ " \"middle-name\": \"middle\",\n"
+ " \"address\": \"address\",\n"
+ " \"email\": \"user1@example.com\"\n";
// "}\n"; // Make the JSON invalid/malformed
// @formatter:on
enqueueApplicationJsonBody(userInfoResponse);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block())
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoErrorResponseThenThrowOAuth2AuthenticationException() {
this.server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setResponseCode(500).setBody("{}"));
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block())
.withMessageContaining("invalid_user_info_response");
}
@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
this.clientRegistration.userInfoUri("https://invalid-provider.com/user");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(oauth2UserRequest()).block());
}
@Test
public void loadUserWhenTokenContainsScopesThenIndividualScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultReactiveOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.scopes("message:read", "message:write"));
OAuth2User user = userService.loadUser(request).block();
assertThat(user.getAuthorities()).hasSize(3);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:read"));
assertThat(authorities.next()).isEqualTo(new SimpleGrantedAuthority("SCOPE_message:write"));
}
@Test
public void loadUserWhenTokenDoesNotContainScopesThenNoScopeAuthorities() {
Map<String, Object> body = new HashMap<>();
body.put("id", "id");
DefaultReactiveOAuth2UserService userService = withMockResponse(body);
OAuth2UserRequest request = new OAuth2UserRequest(TestClientRegistrations.clientRegistration().build(),
TestOAuth2AccessTokens.noScopes());
OAuth2User user = userService.loadUser(request).block();
assertThat(user.getAuthorities()).hasSize(1);
Iterator<? extends GrantedAuthority> authorities = user.getAuthorities().iterator();
assertThat(authorities.next()).isInstanceOf(OAuth2UserAuthority.class);
}
// gh-8764
@Test
public void loadUserWhenUserInfoSuccessResponseInvalidContentTypeThenThrowOAuth2AuthenticationException() {
MockResponse response = new MockResponse();
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
response.setBody("invalid content type");
this.server.enqueue(response);
OAuth2UserRequest userRequest = oauth2UserRequest();
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> this.userService.loadUser(userRequest).block()).withMessageContaining(
"[invalid_user_info_response] An error occurred while attempting to "
+ "retrieve the UserInfo Resource from '" + userRequest.getClientRegistration()
.getProviderDetails().getUserInfoEndpoint().getUri()
+ "': " + "response contains invalid content type 'text/plain'");
}
private DefaultReactiveOAuth2UserService withMockResponse(Map<String, Object> body) {
WebClient real = WebClient.builder().build();
WebClient.RequestHeadersUriSpec spec = spy(real.post());
WebClient rest = spy(WebClient.class);
WebClient.ResponseSpec clientResponse = mock(WebClient.ResponseSpec.class);
given(rest.get()).willReturn(spec);
given(spec.retrieve()).willReturn(clientResponse);
given(clientResponse.onStatus(any(Predicate.class), any(Function.class))).willReturn(clientResponse);
given(clientResponse.bodyToMono(any(ParameterizedTypeReference.class))).willReturn(Mono.just(body));
DefaultReactiveOAuth2UserService userService = new DefaultReactiveOAuth2UserService();
userService.setWebClient(rest);
return userService;
}
private OAuth2UserRequest oauth2UserRequest() {
return new OAuth2UserRequest(this.clientRegistration.build(), this.accessToken);
}
private void enqueueApplicationJsonBody(String json) {
this.server.enqueue(
new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(json));
}
}
| 13,648 | 42.468153 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryClientRegistrationRepositoryTests.java | /*
* Copyright 2002-2019 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
*
* https://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.registration;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link InMemoryClientRegistrationRepository}.
*
* @author Rob Winch
* @author Vedran Pavic
* @since 5.0
*/
public class InMemoryClientRegistrationRepositoryTests {
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private InMemoryClientRegistrationRepository clients = new InMemoryClientRegistrationRepository(this.registration);
@Test
public void constructorListClientRegistrationWhenNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryClientRegistrationRepository((List<ClientRegistration>) null));
}
@Test
public void constructorListClientRegistrationWhenEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryClientRegistrationRepository(Collections.emptyList()));
}
@Test
public void constructorMapClientRegistrationWhenNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryClientRegistrationRepository((Map<String, ClientRegistration>) null));
}
@Test
public void constructorMapClientRegistrationWhenEmptyMapThenRepositoryIsEmpty() {
InMemoryClientRegistrationRepository clients = new InMemoryClientRegistrationRepository(new HashMap<>());
assertThat(clients).isEmpty();
}
@Test
public void constructorListClientRegistrationWhenDuplicateIdThenIllegalArgumentException() {
List<ClientRegistration> registrations = Arrays.asList(this.registration, this.registration);
assertThatIllegalStateException().isThrownBy(() -> new InMemoryClientRegistrationRepository(registrations));
}
@Test
public void findByRegistrationIdWhenFoundThenFound() {
String id = this.registration.getRegistrationId();
assertThat(this.clients.findByRegistrationId(id)).isEqualTo(this.registration);
}
@Test
public void findByRegistrationIdWhenNotFoundThenNull() {
String id = this.registration.getRegistrationId() + "MISSING";
assertThat(this.clients.findByRegistrationId(id)).isNull();
}
@Test
public void findByRegistrationIdWhenNullIdThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.clients.findByRegistrationId(null));
}
@Test
public void iteratorWhenRemoveThenThrowsUnsupportedOperationException() {
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(this.clients.iterator()::remove);
}
@Test
public void iteratorWhenGetThenContainsAll() {
assertThat(this.clients).containsOnly(this.registration);
}
}
| 3,699 | 34.92233 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/TestClientRegistrations.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.registration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
/**
* @author Rob Winch
* @since 5.1
*/
public final class TestClientRegistrations {
private TestClientRegistrations() {
}
public static ClientRegistration.Builder clientRegistration() {
// @formatter:off
return ClientRegistration.withRegistrationId("registration-id")
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.jwkSetUri("https://example.com/oauth2/jwk")
.issuerUri("https://example.com")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Client Name")
.clientId("client-id")
.clientSecret("client-secret");
// @formatter:on
}
public static ClientRegistration.Builder clientRegistration2() {
// @formatter:off
return ClientRegistration.withRegistrationId("registration-id-2")
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Client Name")
.clientId("client-id-2")
.clientSecret("client-secret");
// @formatter:on
}
public static ClientRegistration.Builder clientCredentials() {
// @formatter:off
return clientRegistration()
.registrationId("client-credentials")
.clientId("client-id")
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS);
// @formatter:on
}
public static ClientRegistration.Builder password() {
// @formatter:off
return ClientRegistration.withRegistrationId("password")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.scope("read", "write")
.tokenUri("https://example.com/login/oauth/access_token")
.clientName("Client Name")
.clientId("client-id")
.clientSecret("client-secret");
// @formatter:on
}
}
| 3,266 | 35.3 | 79 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepositoryTests.java | /*
* 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
*
* https://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.registration;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Rob Winch
* @since 5.1
*/
public class InMemoryReactiveClientRegistrationRepositoryTests {
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private InMemoryReactiveClientRegistrationRepository repository;
@BeforeEach
public void setup() {
this.repository = new InMemoryReactiveClientRegistrationRepository(this.registration);
}
@Test
public void constructorWhenZeroVarArgsThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository());
}
@Test
public void constructorWhenClientRegistrationArrayThenIllegalArgumentException() {
ClientRegistration[] registrations = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
}
@Test
public void constructorWhenClientRegistrationListThenIllegalArgumentException() {
List<ClientRegistration> registrations = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
}
@Test
public void constructorListClientRegistrationWhenDuplicateIdThenIllegalArgumentException() {
List<ClientRegistration> registrations = Arrays.asList(this.registration, this.registration);
assertThatIllegalStateException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registrations));
}
@Test
public void constructorWhenClientRegistrationIsNullThenIllegalArgumentException() {
ClientRegistration registration = null;
assertThatIllegalArgumentException()
.isThrownBy(() -> new InMemoryReactiveClientRegistrationRepository(registration));
}
@Test
public void findByRegistrationIdWhenValidIdThenFound() {
// @formatter:off
StepVerifier.create(this.repository.findByRegistrationId(this.registration.getRegistrationId()))
.expectNext(this.registration)
.verifyComplete();
// @formatter:on
}
@Test
public void findByRegistrationIdWhenNotValidIdThenEmpty() {
StepVerifier.create(this.repository.findByRegistrationId(this.registration.getRegistrationId() + "invalid"))
.verifyComplete();
}
@Test
public void iteratorWhenContainsGithubThenContains() {
assertThat(this.repository).containsOnly(this.registration);
}
}
| 3,393 | 33.282828 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationsTests.java | /*
* Copyright 2002-2021 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
*
* https://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.registration;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Rob Winch
* @author Rafiullah Hamedy
* @since 5.1
*/
public class ClientRegistrationsTests {
/**
* Contains all optional parameters that are found in ClientRegistration
*/
// @formatter:off
private static final String DEFAULT_RESPONSE = "{\n"
+ " \"authorization_endpoint\": \"https://example.com/o/oauth2/v2/auth\", \n"
+ " \"claims_supported\": [\n"
+ " \"aud\", \n"
+ " \"email\", \n"
+ " \"email_verified\", \n"
+ " \"exp\", \n"
+ " \"family_name\", \n"
+ " \"given_name\", \n"
+ " \"iat\", \n"
+ " \"iss\", \n"
+ " \"locale\", \n"
+ " \"name\", \n"
+ " \"picture\", \n"
+ " \"sub\"\n"
+ " ], \n"
+ " \"code_challenge_methods_supported\": [\n"
+ " \"plain\", \n"
+ " \"S256\"\n"
+ " ], \n"
+ " \"id_token_signing_alg_values_supported\": [\n"
+ " \"RS256\"\n"
+ " ], \n"
+ " \"issuer\": \"https://example.com\", \n"
+ " \"jwks_uri\": \"https://example.com/oauth2/v3/certs\", \n"
+ " \"response_types_supported\": [\n"
+ " \"code\", \n"
+ " \"token\", \n"
+ " \"id_token\", \n"
+ " \"code token\", \n"
+ " \"code id_token\", \n"
+ " \"token id_token\", \n"
+ " \"code token id_token\", \n"
+ " \"none\"\n"
+ " ], \n"
+ " \"revocation_endpoint\": \"https://example.com/o/oauth2/revoke\", \n"
+ " \"scopes_supported\": [\n"
+ " \"openid\", \n"
+ " \"email\", \n"
+ " \"profile\"\n"
+ " ], \n"
+ " \"subject_types_supported\": [\n"
+ " \"public\"\n"
+ " ], \n"
+ " \"grant_types_supported\" : [\"authorization_code\"], \n"
+ " \"token_endpoint\": \"https://example.com/oauth2/v4/token\", \n"
+ " \"token_endpoint_auth_methods_supported\": [\n"
+ " \"client_secret_post\", \n"
+ " \"client_secret_basic\", \n"
+ " \"none\"\n"
+ " ], \n"
+ " \"userinfo_endpoint\": \"https://example.com/oauth2/v3/userinfo\"\n"
+ "}";
// @formatter:on
private MockWebServer server;
private ObjectMapper mapper = new ObjectMapper();
private Map<String, Object> response;
private String issuer;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.response = this.mapper.readValue(DEFAULT_RESPONSE, new TypeReference<Map<String, Object>>() {
});
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void issuerWhenAllInformationThenSuccess() throws Exception {
ClientRegistration registration = registration("").build();
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertIssuerMetadata(registration, provider);
assertThat(provider.getUserInfoEndpoint().getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo");
}
/**
*
* Test compatibility with OpenID v1 discovery endpoint by making a <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
* Provider Configuration Request</a> as highlighted
* <a href="https://tools.ietf.org/html/rfc8414#section-5"> Compatibility Notes</a> of
* <a href="https://tools.ietf.org/html/rfc8414">RFC 8414</a> specification.
*/
@Test
public void issuerWhenOidcFallbackAllInformationThenSuccess() throws Exception {
ClientRegistration registration = registrationOidcFallback("issuer1", null).build();
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertIssuerMetadata(registration, provider);
assertThat(provider.getUserInfoEndpoint().getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo");
}
@Test
public void issuerWhenOAuth2AllInformationThenSuccess() throws Exception {
ClientRegistration registration = registrationOAuth2("", null).build();
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertIssuerMetadata(registration, provider);
}
private void assertIssuerMetadata(ClientRegistration registration, ClientRegistration.ProviderDetails provider) {
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(registration.getRegistrationId()).isEqualTo(URI.create(this.issuer).getHost());
assertThat(registration.getClientName()).isEqualTo(this.issuer);
assertThat(registration.getScopes()).isNull();
assertThat(provider.getAuthorizationUri()).isEqualTo("https://example.com/o/oauth2/v2/auth");
assertThat(provider.getTokenUri()).isEqualTo("https://example.com/oauth2/v4/token");
assertThat(provider.getJwkSetUri()).isEqualTo("https://example.com/oauth2/v3/certs");
assertThat(provider.getIssuerUri()).isEqualTo(this.issuer);
assertThat(provider.getConfigurationMetadata()).containsKeys("authorization_endpoint", "claims_supported",
"code_challenge_methods_supported", "id_token_signing_alg_values_supported", "issuer", "jwks_uri",
"response_types_supported", "revocation_endpoint", "scopes_supported", "subject_types_supported",
"grant_types_supported", "token_endpoint", "token_endpoint_auth_methods_supported",
"userinfo_endpoint");
}
// gh-7512
@Test
public void issuerWhenResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
this.response.remove("jwks_uri");
assertThatIllegalArgumentException().isThrownBy(() -> registration("").build())
.withMessageContaining("The public JWK set URI must not be null");
}
// gh-7512
@Test
public void issuerWhenOidcFallbackResponseMissingJwksUriThenThrowsIllegalArgumentException() throws Exception {
this.response.remove("jwks_uri");
assertThatIllegalArgumentException().isThrownBy(() -> registrationOidcFallback("issuer1", null).build())
.withMessageContaining("The public JWK set URI must not be null");
}
// gh-7512
@Test
public void issuerWhenOAuth2ResponseMissingJwksUriThenThenSuccess() throws Exception {
this.response.remove("jwks_uri");
ClientRegistration registration = registrationOAuth2("", null).build();
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertThat(provider.getJwkSetUri()).isNull();
}
// gh-8187
@Test
public void issuerWhenResponseMissingUserInfoUriThenSuccess() throws Exception {
this.response.remove("userinfo_endpoint");
ClientRegistration registration = registration("").build();
assertThat(registration.getProviderDetails().getUserInfoEndpoint().getUri()).isNull();
}
@Test
public void issuerWhenContainsTrailingSlashThenSuccess() throws Exception {
assertThat(registration("")).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenOidcFallbackContainsTrailingSlashThenSuccess() throws Exception {
assertThat(registrationOidcFallback("", null)).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenOAuth2ContainsTrailingSlashThenSuccess() throws Exception {
assertThat(registrationOAuth2("", null)).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenGrantTypesSupportedNullThenDefaulted() throws Exception {
this.response.remove("grant_types_supported");
ClientRegistration registration = registration("").build();
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
}
@Test
public void issuerWhenOAuth2GrantTypesSupportedNullThenDefaulted() throws Exception {
this.response.remove("grant_types_supported");
ClientRegistration registration = registrationOAuth2("", null).build();
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
}
// gh-9828
@Test
public void issuerWhenImplicitGrantTypeThenSuccess() throws Exception {
this.response.put("grant_types_supported", Arrays.asList("implicit"));
ClientRegistration registration = registration("").build();
// The authorization_code grant type is still the default
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
}
// gh-9828
@Test
public void issuerWhenOAuth2JwtBearerGrantTypeThenSuccess() throws Exception {
this.response.put("grant_types_supported", Arrays.asList("urn:ietf:params:oauth:grant-type:jwt-bearer"));
ClientRegistration registration = registrationOAuth2("", null).build();
// The authorization_code grant type is still the default
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
}
// gh-9795
@Test
public void issuerWhenResponseAuthorizationEndpointIsNullThenSuccess() throws Exception {
this.response.put("grant_types_supported", Arrays.asList("urn:ietf:params:oauth:grant-type:jwt-bearer"));
this.response.remove("authorization_endpoint");
ClientRegistration registration = registration("").authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.build();
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.JWT_BEARER);
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertThat(provider.getAuthorizationUri()).isNull();
}
// gh-9795
@Test
public void issuerWhenOAuth2ResponseAuthorizationEndpointIsNullThenSuccess() throws Exception {
this.response.put("grant_types_supported", Arrays.asList("urn:ietf:params:oauth:grant-type:jwt-bearer"));
this.response.remove("authorization_endpoint");
ClientRegistration registration = registrationOAuth2("", null)
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER).build();
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.JWT_BEARER);
ClientRegistration.ProviderDetails provider = registration.getProviderDetails();
assertThat(provider.getAuthorizationUri()).isNull();
}
@Test
public void issuerWhenTokenEndpointAuthMethodsNullThenDefaulted() throws Exception {
this.response.remove("token_endpoint_auth_methods_supported");
ClientRegistration registration = registration("").build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void issuerWhenOAuth2TokenEndpointAuthMethodsNullThenDefaulted() throws Exception {
this.response.remove("token_endpoint_auth_methods_supported");
ClientRegistration registration = registrationOAuth2("", null).build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenClientSecretBasicAuthMethodThenMethodIsBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_basic"));
ClientRegistration registration = registration("").build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenOAuth2ClientSecretBasicAuthMethodThenMethodIsBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_basic"));
ClientRegistration registration = registrationOAuth2("", null).build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void issuerWhenTokenEndpointAuthMethodsPostThenMethodIsPost() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_post"));
ClientRegistration registration = registration("").build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_POST);
}
@Test
public void issuerWhenOAuth2TokenEndpointAuthMethodsPostThenMethodIsPost() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_post"));
ClientRegistration registration = registrationOAuth2("", null).build();
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_POST);
}
// gh-9780
@Test
public void issuerWhenClientSecretJwtAuthMethodThenMethodIsClientSecretBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_jwt"));
ClientRegistration registration = registration("").build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenOAuth2ClientSecretJwtAuthMethodThenMethodIsClientSecretBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("client_secret_jwt"));
ClientRegistration registration = registrationOAuth2("", null).build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenPrivateKeyJwtAuthMethodThenMethodIsClientSecretBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("private_key_jwt"));
ClientRegistration registration = registration("").build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenOAuth2PrivateKeyJwtAuthMethodThenMethodIsClientSecretBasic() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("private_key_jwt"));
ClientRegistration registration = registrationOAuth2("", null).build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void issuerWhenTokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none"));
ClientRegistration registration = registration("").build();
assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE);
}
@Test
public void issuerWhenOAuth2TokenEndpointAuthMethodsNoneThenMethodIsNone() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("none"));
ClientRegistration registration = registrationOAuth2("", null).build();
assertThat(registration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE);
}
// gh-9780
@Test
public void issuerWhenTlsClientAuthMethodThenSuccess() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
ClientRegistration registration = registration("").build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
// gh-9780
@Test
public void issuerWhenOAuth2TlsClientAuthMethodThenSuccess() throws Exception {
this.response.put("token_endpoint_auth_methods_supported", Arrays.asList("tls_client_auth"));
ClientRegistration registration = registrationOAuth2("", null).build();
// The client_secret_basic auth method is still the default
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void issuerWhenOAuth2EmptyStringThenMeaningfulErrorMessage() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistrations.fromIssuerLocation(""))
.withMessageContaining("issuer cannot be empty");
// @formatter:on
}
@Test
public void issuerWhenEmptyStringThenMeaningfulErrorMessage() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(""))
.withMessageContaining("issuer cannot be empty");
// @formatter:on
}
@Test
public void issuerWhenOpenIdConfigurationDoesNotMatchThenMeaningfulErrorMessage() throws Exception {
this.issuer = createIssuerFromServer("");
String body = this.mapper.writeValueAsString(this.response);
MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(mockResponse);
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> ClientRegistrations.fromOidcIssuerLocation(this.issuer))
.withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata did "
+ "not match the requested issuer \"" + this.issuer + "\"");
// @formatter:on
}
@Test
public void issuerWhenOAuth2ConfigurationDoesNotMatchThenMeaningfulErrorMessage() throws Exception {
this.issuer = createIssuerFromServer("");
String body = this.mapper.writeValueAsString(this.response);
MockResponse mockResponse = new MockResponse().setBody(body).setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(mockResponse);
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> ClientRegistrations.fromIssuerLocation(this.issuer))
.withMessageContaining("The Issuer \"https://example.com\" provided in the configuration metadata "
+ "did not match the requested issuer \"" + this.issuer + "\"");
// @formatter:on
}
private ClientRegistration.Builder registration(String path) throws Exception {
this.issuer = createIssuerFromServer(path);
this.response.put("issuer", this.issuer);
String body = this.mapper.writeValueAsString(this.response);
// @formatter:off
MockResponse mockResponse = new MockResponse()
.setBody(body)
.setHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_JSON_VALUE);
this.server.enqueue(mockResponse);
return ClientRegistrations.fromOidcIssuerLocation(this.issuer)
.clientId("client-id")
.clientSecret("client-secret");
// @formatter:on
}
private ClientRegistration.Builder registrationOAuth2(String path, String body) throws Exception {
this.issuer = createIssuerFromServer(path);
this.response.put("issuer", this.issuer);
this.issuer = this.server.url(path).toString();
final String responseBody = (body != null) ? body : this.mapper.writeValueAsString(this.response);
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
return switch (request.getPath()) {
case "/.well-known/oauth-authorization-server/issuer1", "/.well-known/oauth-authorization-server/" ->
buildSuccessMockResponse(responseBody);
default -> new MockResponse().setResponseCode(404);
};
}
};
this.server.setDispatcher(dispatcher);
// @formatter:off
return ClientRegistrations.fromIssuerLocation(this.issuer)
.clientId("client-id")
.clientSecret("client-secret");
// @formatter:on
}
private String createIssuerFromServer(String path) {
return this.server.url(path).toString();
}
/**
* Simulates a situation when the ClientRegistration is used with a legacy application
* where the OIDC Discovery Endpoint is "/issuer1/.well-known/openid-configuration"
* instead of "/.well-known/openid-configuration/issuer1" in which case the first
* attempt results in HTTP 404 and the subsequent call results in 200 OK.
*
* @see <a href="https://tools.ietf.org/html/rfc8414#section-5">Section 5</a> for more
* details.
*/
private ClientRegistration.Builder registrationOidcFallback(String path, String body) throws Exception {
this.issuer = createIssuerFromServer(path);
this.response.put("issuer", this.issuer);
String responseBody = (body != null) ? body : this.mapper.writeValueAsString(this.response);
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
return switch (request.getPath()) {
case "/issuer1/.well-known/openid-configuration", "/.well-known/openid-configuration/" ->
buildSuccessMockResponse(responseBody);
default -> new MockResponse().setResponseCode(404);
};
}
};
this.server.setDispatcher(dispatcher);
return ClientRegistrations.fromIssuerLocation(this.issuer).clientId("client-id").clientSecret("client-secret");
}
private MockResponse buildSuccessMockResponse(String body) {
// @formatter:off
return new MockResponse().setResponseCode(200)
.setBody(body)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
}
| 22,733 | 41.414179 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/SupplierClientRegistrationRepositoryTests.java | /*
* Copyright 2002-2023 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
*
* https://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.registration;
import java.util.Collections;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link SupplierClientRegistrationRepository}.
*
* @author Justin Tay
* @since 6.2
*/
@ExtendWith(MockitoExtension.class)
public class SupplierClientRegistrationRepositoryTests {
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private SupplierClientRegistrationRepository clients = new SupplierClientRegistrationRepository(
() -> new InMemoryClientRegistrationRepository(this.registration));
@Mock
Supplier<InMemoryClientRegistrationRepository> clientRegistrationRepositorySupplier;
@Test
public void constructorMapClientRegistrationWhenNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new SupplierClientRegistrationRepository(null));
}
@Test
public void constructorMapClientRegistrationWhenEmptyMapThenRepositoryIsEmpty() {
SupplierClientRegistrationRepository clients = new SupplierClientRegistrationRepository(
() -> new InMemoryClientRegistrationRepository(Collections.emptyMap()));
assertThat(clients).isEmpty();
}
@Test
public void findByRegistrationIdWhenFoundThenFound() {
String id = this.registration.getRegistrationId();
assertThat(this.clients.findByRegistrationId(id)).isEqualTo(this.registration);
}
@Test
public void findByRegistrationIdWhenNotFoundThenNull() {
String id = this.registration.getRegistrationId() + "MISSING";
assertThat(this.clients.findByRegistrationId(id)).isNull();
}
@Test
public void findByRegistrationIdWhenNullIdThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.clients.findByRegistrationId(null));
}
@Test
public void findByRegistrationIdThenSingletonSupplierCached() {
SupplierClientRegistrationRepository test = new SupplierClientRegistrationRepository(
this.clientRegistrationRepositorySupplier);
given(this.clientRegistrationRepositorySupplier.get())
.willReturn(new InMemoryClientRegistrationRepository(this.registration));
String id = this.registration.getRegistrationId();
assertThat(test.findByRegistrationId(id)).isEqualTo(this.registration);
id = this.registration.getRegistrationId();
assertThat(test.findByRegistrationId(id)).isEqualTo(this.registration);
verify(this.clientRegistrationRepositorySupplier, times(1)).get();
}
@Test
public void iteratorWhenRemoveThenThrowsUnsupportedOperationException() {
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(this.clients.iterator()::remove);
}
@Test
public void iteratorWhenGetThenContainsAll() {
assertThat(this.clients).containsOnly(this.registration);
}
}
| 3,882 | 36.336538 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/registration/ClientRegistrationTests.java | /*
* Copyright 2002-2022 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
*
* https://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.registration;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link ClientRegistration}.
*
* @author Joe Grandja
*/
public class ClientRegistrationTests {
private static final String REGISTRATION_ID = "registration-1";
private static final String CLIENT_ID = "client-1";
private static final String CLIENT_SECRET = "secret";
private static final String REDIRECT_URI = "https://example.com";
private static final Set<String> SCOPES = Collections
.unmodifiableSet(Stream.of("openid", "profile", "email").collect(Collectors.toSet()));
private static final String AUTHORIZATION_URI = "https://provider.com/oauth2/authorization";
private static final String TOKEN_URI = "https://provider.com/oauth2/token";
private static final String JWK_SET_URI = "https://provider.com/oauth2/keys";
private static final String ISSUER_URI = "https://provider.com";
private static final String CLIENT_NAME = "Client 1";
private static final Map<String, Object> PROVIDER_CONFIGURATION_METADATA = Collections
.unmodifiableMap(createProviderConfigurationMetadata());
private static Map<String, Object> createProviderConfigurationMetadata() {
Map<String, Object> configurationMetadata = new LinkedHashMap<>();
configurationMetadata.put("config-1", "value-1");
configurationMetadata.put("config-2", "value-2");
return configurationMetadata;
}
@Test
public void buildWhenAuthorizationGrantTypeIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(null)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
@Test
public void buildWhenAuthorizationCodeGrantAllAttributesProvidedThenAllAttributesAreSet() {
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.issuerUri(ISSUER_URI)
.providerConfigurationMetadata(PROVIDER_CONFIGURATION_METADATA)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(registration.getRegistrationId()).isEqualTo(REGISTRATION_ID);
assertThat(registration.getClientId()).isEqualTo(CLIENT_ID);
assertThat(registration.getClientSecret()).isEqualTo(CLIENT_SECRET);
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(registration.getRedirectUri()).isEqualTo(REDIRECT_URI);
assertThat(registration.getScopes()).isEqualTo(SCOPES);
assertThat(registration.getProviderDetails().getAuthorizationUri()).isEqualTo(AUTHORIZATION_URI);
assertThat(registration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
assertThat(registration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())
.isEqualTo(AuthenticationMethod.FORM);
assertThat(registration.getProviderDetails().getJwkSetUri()).isEqualTo(JWK_SET_URI);
assertThat(registration.getProviderDetails().getIssuerUri()).isEqualTo(ISSUER_URI);
assertThat(registration.getProviderDetails().getConfigurationMetadata())
.isEqualTo(PROVIDER_CONFIGURATION_METADATA);
assertThat(registration.getClientName()).isEqualTo(CLIENT_NAME);
}
@Test
public void buildWhenAuthorizationCodeGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(null)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
@Test
public void buildWhenAuthorizationCodeGrantClientIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(null)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
@Test
public void buildWhenAuthorizationCodeGrantClientSecretIsNullThenDefaultToEmpty() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(null)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getClientSecret()).isEqualTo("");
}
@Test
public void buildWhenAuthorizationCodeGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void buildWhenAuthorizationCodeGrantClientAuthenticationMethodNotProvidedAndClientSecretNullThenDefaultToNone() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(null)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE);
}
@Test
public void buildWhenAuthorizationCodeGrantClientAuthenticationMethodNotProvidedAndClientSecretBlankThenDefaultToNone() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(" ")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.NONE);
assertThat(clientRegistration.getClientSecret()).isEqualTo("");
}
@Test
public void buildWhenAuthorizationCodeGrantRedirectUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(null)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
// gh-5494
@Test
public void buildWhenAuthorizationCodeGrantScopeIsNullThenScopeNotRequired() {
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope((String[]) null)
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
}
@Test
public void buildWhenAuthorizationCodeGrantAuthorizationUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(null)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
@Test
public void buildWhenAuthorizationCodeGrantTokenUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() ->
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(null)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build()
// @formatter:on
);
}
@Test
public void buildWhenAuthorizationCodeGrantClientNameNotProvidedThenDefaultToRegistrationId() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.jwkSetUri(JWK_SET_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientName()).isEqualTo(clientRegistration.getRegistrationId());
}
@Test
public void buildWhenAuthorizationCodeGrantScopeDoesNotContainOpenidThenJwkSetUriNotRequired() {
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope("scope1")
.authorizationUri(AUTHORIZATION_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.FORM)
.tokenUri(TOKEN_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
}
// gh-5494
@Test
public void buildWhenAuthorizationCodeGrantScopeIsNullThenJwkSetUriNotRequired() {
// @formatter:off
ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
}
@Test
public void buildWhenAuthorizationCodeGrantProviderConfigurationMetadataIsNullThenDefaultToEmpty() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.providerConfigurationMetadata(null)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).isNotNull();
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).isEmpty();
}
@Test
public void buildWhenAuthorizationCodeGrantProviderConfigurationMetadataEmptyThenIsEmpty() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.userInfoAuthenticationMethod(AuthenticationMethod.HEADER)
.providerConfigurationMetadata(Collections.emptyMap())
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).isNotNull();
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).isEmpty();
}
@Test
public void buildWhenOverrideRegistrationIdThenOverridden() {
String overriddenId = "override";
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.registrationId(overriddenId)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri(REDIRECT_URI)
.scope(SCOPES.toArray(new String[0]))
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.jwkSetUri(JWK_SET_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(registration.getRegistrationId()).isEqualTo(overriddenId);
}
@Test
public void buildWhenClientCredentialsGrantAllAttributesProvidedThenAllAttributesAreSet() {
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.scope(SCOPES.toArray(new String[0]))
.tokenUri(TOKEN_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(registration.getRegistrationId()).isEqualTo(REGISTRATION_ID);
assertThat(registration.getClientId()).isEqualTo(CLIENT_ID);
assertThat(registration.getClientSecret()).isEqualTo(CLIENT_SECRET);
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.CLIENT_CREDENTIALS);
assertThat(registration.getScopes()).isEqualTo(SCOPES);
assertThat(registration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
assertThat(registration.getClientName()).isEqualTo(CLIENT_NAME);
}
@Test
public void buildWhenClientCredentialsGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> ClientRegistration.withRegistrationId(null).clientId(CLIENT_ID).clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build());
}
@Test
public void buildWhenClientCredentialsGrantClientIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> ClientRegistration.withRegistrationId(REGISTRATION_ID).clientId(null).clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(TOKEN_URI).build());
}
@Test
public void buildWhenClientCredentialsGrantClientSecretIsNullThenDefaultToEmpty() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(null)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.tokenUri(TOKEN_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientSecret()).isEqualTo("");
}
@Test
public void buildWhenClientCredentialsGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.tokenUri(TOKEN_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void buildWhenClientCredentialsGrantTokenUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID).clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS).tokenUri(null).build());
}
// gh-6256
@Test
public void buildWhenScopesContainASpaceThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("openid profile email").build());
}
@Test
public void buildWhenScopesContainAnInvalidCharacterThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> TestClientRegistrations.clientCredentials().scope("an\"invalid\"scope").build());
}
@Test
public void buildWhenPasswordGrantAllAttributesProvidedThenAllAttributesAreSet() {
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.scope(SCOPES.toArray(new String[0]))
.tokenUri(TOKEN_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(registration.getRegistrationId()).isEqualTo(REGISTRATION_ID);
assertThat(registration.getClientId()).isEqualTo(CLIENT_ID);
assertThat(registration.getClientSecret()).isEqualTo(CLIENT_SECRET);
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
assertThat(registration.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.PASSWORD);
assertThat(registration.getScopes()).isEqualTo(SCOPES);
assertThat(registration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
assertThat(registration.getClientName()).isEqualTo(CLIENT_NAME);
}
@Test
public void buildWhenPasswordGrantRegistrationIdIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(null)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.tokenUri(TOKEN_URI)
.build()
);
// @formatter:on
}
@Test
public void buildWhenPasswordGrantClientIdIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException().isThrownBy(() -> ClientRegistration
.withRegistrationId(REGISTRATION_ID)
.clientId(null)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.tokenUri(TOKEN_URI)
.build()
);
// @formatter:on
}
@Test
public void buildWhenPasswordGrantClientSecretIsNullThenDefaultToEmpty() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(null)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.tokenUri(TOKEN_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientSecret()).isEqualTo("");
}
@Test
public void buildWhenPasswordGrantClientAuthenticationMethodNotProvidedThenDefaultToBasic() {
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.tokenUri(TOKEN_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
}
@Test
public void buildWhenPasswordGrantTokenUriIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.PASSWORD)
.tokenUri(null)
.build()
);
// @formatter:on
}
@Test
public void buildWhenCustomGrantAllAttributesProvidedThenAllAttributesAreSet() {
AuthorizationGrantType customGrantType = new AuthorizationGrantType("CUSTOM");
// @formatter:off
ClientRegistration registration = ClientRegistration
.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(customGrantType)
.scope(SCOPES.toArray(new String[0]))
.tokenUri(TOKEN_URI)
.clientName(CLIENT_NAME)
.build();
// @formatter:on
assertThat(registration.getRegistrationId()).isEqualTo(REGISTRATION_ID);
assertThat(registration.getClientId()).isEqualTo(CLIENT_ID);
assertThat(registration.getClientSecret()).isEqualTo(CLIENT_SECRET);
assertThat(registration.getClientAuthenticationMethod())
.isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
assertThat(registration.getAuthorizationGrantType()).isEqualTo(customGrantType);
assertThat(registration.getScopes()).isEqualTo(SCOPES);
assertThat(registration.getProviderDetails().getTokenUri()).isEqualTo(TOKEN_URI);
assertThat(registration.getClientName()).isEqualTo(CLIENT_NAME);
}
@Test
public void buildWhenClientRegistrationProvidedThenMakesACopy() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration).build();
assertThat(clientRegistration.getScopes()).isEqualTo(updated.getScopes());
assertThat(clientRegistration.getScopes()).isNotSameAs(updated.getScopes());
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata())
.isEqualTo(updated.getProviderDetails().getConfigurationMetadata());
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata())
.isNotSameAs(updated.getProviderDetails().getConfigurationMetadata());
}
@Test
public void buildWhenClientRegistrationProvidedThenEachPropertyMatches() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration).build();
assertThat(clientRegistration.getRegistrationId()).isEqualTo(updated.getRegistrationId());
assertThat(clientRegistration.getClientId()).isEqualTo(updated.getClientId());
assertThat(clientRegistration.getClientSecret()).isEqualTo(updated.getClientSecret());
assertThat(clientRegistration.getClientAuthenticationMethod())
.isEqualTo(updated.getClientAuthenticationMethod());
assertThat(clientRegistration.getAuthorizationGrantType()).isEqualTo(updated.getAuthorizationGrantType());
assertThat(clientRegistration.getRedirectUri()).isEqualTo(updated.getRedirectUri());
assertThat(clientRegistration.getScopes()).isEqualTo(updated.getScopes());
ClientRegistration.ProviderDetails providerDetails = clientRegistration.getProviderDetails();
ClientRegistration.ProviderDetails updatedProviderDetails = updated.getProviderDetails();
assertThat(providerDetails.getAuthorizationUri()).isEqualTo(updatedProviderDetails.getAuthorizationUri());
assertThat(providerDetails.getTokenUri()).isEqualTo(updatedProviderDetails.getTokenUri());
ClientRegistration.ProviderDetails.UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint();
ClientRegistration.ProviderDetails.UserInfoEndpoint updatedUserInfoEndpoint = updatedProviderDetails
.getUserInfoEndpoint();
assertThat(userInfoEndpoint.getUri()).isEqualTo(updatedUserInfoEndpoint.getUri());
assertThat(userInfoEndpoint.getAuthenticationMethod())
.isEqualTo(updatedUserInfoEndpoint.getAuthenticationMethod());
assertThat(userInfoEndpoint.getUserNameAttributeName())
.isEqualTo(updatedUserInfoEndpoint.getUserNameAttributeName());
assertThat(providerDetails.getJwkSetUri()).isEqualTo(updatedProviderDetails.getJwkSetUri());
assertThat(providerDetails.getIssuerUri()).isEqualTo(updatedProviderDetails.getIssuerUri());
assertThat(providerDetails.getConfigurationMetadata())
.isEqualTo(updatedProviderDetails.getConfigurationMetadata());
assertThat(clientRegistration.getClientName()).isEqualTo(updated.getClientName());
}
@Test
public void buildWhenClientRegistrationValuesOverriddenThenPropagated() {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
// @formatter:off
ClientRegistration updated = ClientRegistration.withClientRegistration(clientRegistration)
.clientSecret("a-new-secret")
.scope("a-new-scope")
.providerConfigurationMetadata(Collections.singletonMap("a-new-config", "a-new-value"))
.build();
// @formatter:on
assertThat(clientRegistration.getClientSecret()).isNotEqualTo(updated.getClientSecret());
assertThat(updated.getClientSecret()).isEqualTo("a-new-secret");
assertThat(clientRegistration.getScopes()).doesNotContain("a-new-scope");
assertThat(updated.getScopes()).containsExactly("a-new-scope");
assertThat(clientRegistration.getProviderDetails().getConfigurationMetadata()).doesNotContainKey("a-new-config")
.doesNotContainValue("a-new-value");
assertThat(updated.getProviderDetails().getConfigurationMetadata()).containsOnlyKeys("a-new-config")
.containsValue("a-new-value");
}
// gh-8903
@Test
public void buildWhenCustomClientAuthenticationMethodProvidedThenSet() {
ClientAuthenticationMethod clientAuthenticationMethod = new ClientAuthenticationMethod("tls_client_auth");
// @formatter:off
ClientRegistration clientRegistration = ClientRegistration.withRegistrationId(REGISTRATION_ID)
.clientId(CLIENT_ID)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.clientAuthenticationMethod(clientAuthenticationMethod)
.redirectUri(REDIRECT_URI)
.authorizationUri(AUTHORIZATION_URI)
.tokenUri(TOKEN_URI)
.build();
// @formatter:on
assertThat(clientRegistration.getClientAuthenticationMethod()).isEqualTo(clientAuthenticationMethod);
}
}
| 31,515 | 41.13369 | 122 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilterTests.java | /*
* Copyright 2002-2021 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
*
* https://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;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests for {@link OAuth2LoginAuthenticationFilter}.
*
* @author Joe Grandja
*/
public class OAuth2LoginAuthenticationFilterTests {
private ClientRegistration registration1;
private ClientRegistration registration2;
private String principalName1 = "principal-1";
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private OAuth2AuthorizedClientService authorizedClientService;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private AuthenticationFailureHandler failureHandler;
private AuthenticationManager authenticationManager;
private AuthenticationDetailsSource authenticationDetailsSource;
private OAuth2LoginAuthenticationToken loginAuthentication;
private OAuth2LoginAuthenticationFilter filter;
@BeforeEach
public void setUp() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.registration2 = TestClientRegistrations.clientRegistration2().build();
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2);
this.authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository);
this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
this.authorizedClientService);
this.authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
this.failureHandler = mock(AuthenticationFailureHandler.class);
this.authenticationManager = mock(AuthenticationManager.class);
this.authenticationDetailsSource = mock(AuthenticationDetailsSource.class);
this.filter = spy(new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository,
this.authorizedClientRepository, OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI));
this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
this.filter.setAuthenticationFailureHandler(this.failureHandler);
this.filter.setAuthenticationManager(this.authenticationManager);
this.filter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationFilter(null, this.authorizedClientService));
}
@Test
public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository, null));
}
@Test
public void constructorWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository,
(OAuth2AuthorizedClientRepository) null,
OAuth2LoginAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI));
}
@Test
public void constructorWhenFilterProcessesUrlIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository,
this.authorizedClientRepository, null));
}
@Test
public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null));
}
// gh-10033
@Test
public void setAuthenticationResultConverterWhenAuthenticationResultConverterIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationResultConverter(null));
}
@Test
public void doFilterWhenNotAuthorizationResponseThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verify(this.filter, never()).attemptAuthentication(any(HttpServletRequest.class),
any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationResponseInvalidThenInvalidRequestError() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
// NOTE:
// A valid Authorization Response contains either a 'code' or 'error' parameter.
// Don't set it to force an invalid Authorization Response.
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor
.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor
.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_REQUEST);
}
@Test
public void doFilterWhenAuthorizationResponseAuthorizationRequestNotFoundThenAuthorizationRequestNotFoundError()
throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor
.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor
.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("authorization_request_not_found");
}
// gh-5251
@Test
public void doFilterWhenAuthorizationResponseClientRegistrationNotFoundThenClientRegistrationNotFoundError()
throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
// @formatter:off
ClientRegistration registrationNotFound = ClientRegistration.withRegistrationId("registration-not-found")
.clientId("client-1")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("user")
.authorizationUri("https://provider.com/oauth2/authorize")
.tokenUri("https://provider.com/oauth2/token")
.userInfoUri("https://provider.com/oauth2/user")
.userNameAttributeName("id")
.clientName("client-1")
.build();
// @formatter:on
this.setUpAuthorizationRequest(request, response, registrationNotFound, state);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<AuthenticationException> authenticationExceptionArgCaptor = ArgumentCaptor
.forClass(AuthenticationException.class);
verify(this.failureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
any(HttpServletResponse.class), authenticationExceptionArgCaptor.capture());
assertThat(authenticationExceptionArgCaptor.getValue()).isInstanceOf(OAuth2AuthenticationException.class);
OAuth2AuthenticationException authenticationException = (OAuth2AuthenticationException) authenticationExceptionArgCaptor
.getValue();
assertThat(authenticationException.getError().getErrorCode()).isEqualTo("client_registration_not_found");
}
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizationRequestRemoved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(request)).isNull();
}
@Test
public void doFilterWhenAuthorizationResponseValidThenAuthorizedClientSaved() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration1, state);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(request, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registration1.getRegistrationId(), this.loginAuthentication, request);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
@Test
public void doFilterWhenCustomFilterProcessesUrlThenFilterProcesses() throws Exception {
String filterProcessesUrl = "/login/oauth2/custom/*";
this.filter = spy(new OAuth2LoginAuthenticationFilter(this.clientRegistrationRepository,
this.authorizedClientRepository, filterProcessesUrl));
this.filter.setAuthenticationManager(this.authenticationManager);
String requestUri = "/login/oauth2/custom/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(this.filter).attemptAuthentication(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort()
throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("http");
request.setServerName("localhost");
request.setServerPort(80);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor
.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange()
.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange()
.getAuthorizationResponse();
String expectedRedirectUri = "http://localhost/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort()
throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(443);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor
.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange()
.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange()
.getAuthorizationResponse();
String expectedRedirectUri = "https://example.com/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
// gh-5890
@Test
public void doFilterWhenAuthorizationResponseHasNonDefaultPortThenRedirectUriMatchingIncludesPort()
throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(9090);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
this.filter.doFilter(request, response, filterChain);
ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class);
verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture());
OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor
.getValue();
OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange()
.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange()
.getAuthorizationResponse();
String expectedRedirectUri = "https://example.com:9090/login/oauth2/code/registration-id-2";
assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri);
assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri);
}
// gh-6866
@Test
public void attemptAuthenticationShouldSetAuthenticationDetailsOnAuthenticationResult() throws Exception {
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
WebAuthenticationDetails webAuthenticationDetails = mock(WebAuthenticationDetails.class);
given(this.authenticationDetailsSource.buildDetails(any())).willReturn(webAuthenticationDetails);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(request, response, this.registration2, state);
this.setUpAuthenticationResult(this.registration2);
Authentication result = this.filter.attemptAuthentication(request, response);
assertThat(result.getDetails()).isEqualTo(webAuthenticationDetails);
}
// gh-10033
@Test
public void attemptAuthenticationWhenAuthenticationResultIsNullThenIllegalArgumentException() throws Exception {
this.filter.setAuthenticationResultConverter((authentication) -> null);
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(request, response, this.registration1, state);
this.setUpAuthenticationResult(this.registration1);
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.attemptAuthentication(request, response));
}
// gh-10033
@Test
public void attemptAuthenticationWhenAuthenticationResultConverterSetThenUsed() {
this.filter.setAuthenticationResultConverter(
(authentication) -> new CustomOAuth2AuthenticationToken(authentication.getPrincipal(),
authentication.getAuthorities(), authentication.getClientRegistration().getRegistrationId()));
String requestUri = "/login/oauth2/code/" + this.registration1.getRegistrationId();
String state = "state";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, state);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(request, response, this.registration1, state);
this.setUpAuthenticationResult(this.registration1);
Authentication authenticationResult = this.filter.attemptAuthentication(request, response);
assertThat(authenticationResult).isInstanceOf(CustomOAuth2AuthenticationToken.class);
}
private void setUpAuthorizationRequest(HttpServletRequest request, HttpServletResponse response,
ClientRegistration registration, String state) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId());
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.authorizationUri(registration.getProviderDetails().getAuthorizationUri())
.clientId(registration.getClientId()).redirectUri(expandRedirectUri(request, registration))
.scopes(registration.getScopes()).state(state).attributes(attributes).build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
}
private String expandRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
String baseUrl = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null)
.replacePath(request.getContextPath()).build().toUriString();
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("baseUrl", baseUrl);
uriVariables.put("action", "login");
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri()).buildAndExpand(uriVariables)
.toUriString();
}
private void setUpAuthenticationResult(ClientRegistration registration) {
OAuth2User user = mock(OAuth2User.class);
given(user.getName()).willReturn(this.principalName1);
this.loginAuthentication = mock(OAuth2LoginAuthenticationToken.class);
given(this.loginAuthentication.getPrincipal()).willReturn(user);
given(this.loginAuthentication.getName()).willReturn(this.principalName1);
given(this.loginAuthentication.getAuthorities()).willReturn(AuthorityUtils.createAuthorityList("ROLE_USER"));
given(this.loginAuthentication.getClientRegistration()).willReturn(registration);
given(this.loginAuthentication.getAuthorizationExchange())
.willReturn(TestOAuth2AuthorizationExchanges.success());
given(this.loginAuthentication.getAccessToken()).willReturn(mock(OAuth2AccessToken.class));
given(this.loginAuthentication.getRefreshToken()).willReturn(mock(OAuth2RefreshToken.class));
given(this.loginAuthentication.isAuthenticated()).willReturn(true);
given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(this.loginAuthentication);
}
private static final class CustomOAuth2AuthenticationToken extends OAuth2AuthenticationToken {
CustomOAuth2AuthenticationToken(OAuth2User principal, Collection<? extends GrantedAuthority> authorities,
String authorizedClientRegistrationId) {
super(principal, authorities, authorizedClientRegistrationId);
}
}
}
| 27,460 | 52.845098 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepositoryTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link HttpSessionOAuth2AuthorizationRequestRepository}.
*
* @author Joe Grandja
* @author Craig Andrews
*/
public class HttpSessionOAuth2AuthorizationRequestRepositoryTests {
private HttpSessionOAuth2AuthorizationRequestRepository authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
@Test
public void loadAuthorizationRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizationRequestRepository.loadAuthorizationRequest(null));
}
@Test
public void loadAuthorizationRequestWhenNotSavedThenReturnNull() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(OAuth2ParameterNames.STATE, "state-1234");
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(authorizationRequest).isNull();
}
@Test
public void loadAuthorizationRequestWhenSavedThenReturnAuthorizationRequest() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(loadedAuthorizationRequest).isEqualTo(authorizationRequest);
}
@Test
public void loadAuthorizationRequestWhenSavedAndStateParameterNullThenReturnNull() {
MockHttpServletRequest request = new MockHttpServletRequest();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request,
new MockHttpServletResponse());
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(request)).isNull();
}
@Test
public void saveAuthorizationRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository
.saveAuthorizationRequest(authorizationRequest, null, new MockHttpServletResponse()));
}
@Test
public void saveAuthorizationRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository
.saveAuthorizationRequest(authorizationRequest, new MockHttpServletRequest(), null));
}
@Test
public void saveAuthorizationRequestWhenStateNullThenThrowIllegalArgumentException() {
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().state(null).build();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest,
new MockHttpServletRequest(), new MockHttpServletResponse()));
}
@Test
public void saveAuthorizationRequestWhenNotNullThenSaved() {
MockHttpServletRequest request = new MockHttpServletRequest();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request,
new MockHttpServletResponse());
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(loadedAuthorizationRequest).isEqualTo(authorizationRequest);
}
@Test
public void saveAuthorizationRequestWhenNoExistingSessionAndDistributedSessionThenSaved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockDistributedHttpSession());
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request,
new MockHttpServletResponse());
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(loadedAuthorizationRequest).isEqualTo(authorizationRequest);
}
@Test
public void saveAuthorizationRequestWhenExistingSessionAndDistributedSessionThenSaved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(new MockDistributedHttpSession());
OAuth2AuthorizationRequest authorizationRequest1 = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest1, request,
new MockHttpServletResponse());
OAuth2AuthorizationRequest authorizationRequest2 = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest2, request,
new MockHttpServletResponse());
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest2.getState());
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(loadedAuthorizationRequest).isEqualTo(authorizationRequest2);
}
@Test
public void saveAuthorizationRequestWhenNullThenRemoved() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
this.authorizationRequestRepository.saveAuthorizationRequest(null, request, response);
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(loadedAuthorizationRequest).isNull();
}
@Test
public void removeAuthorizationRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository
.removeAuthorizationRequest(null, new MockHttpServletResponse()));
}
@Test
public void removeAuthorizationRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizationRequestRepository
.removeAuthorizationRequest(new MockHttpServletRequest(), null));
}
@Test
public void removeAuthorizationRequestWhenSavedThenRemoved() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
OAuth2AuthorizationRequest removedAuthorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
OAuth2AuthorizationRequest loadedAuthorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
assertThat(removedAuthorizationRequest).isNotNull();
assertThat(loadedAuthorizationRequest).isNull();
}
// gh-5263
@Test
public void removeAuthorizationRequestWhenSavedThenRemovedFromSession() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
OAuth2AuthorizationRequest authorizationRequest = createAuthorizationRequest().build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
request.addParameter(OAuth2ParameterNames.STATE, authorizationRequest.getState());
OAuth2AuthorizationRequest removedAuthorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
String sessionAttributeName = HttpSessionOAuth2AuthorizationRequestRepository.class.getName()
+ ".AUTHORIZATION_REQUEST";
assertThat(removedAuthorizationRequest).isNotNull();
assertThat(request.getSession().getAttribute(sessionAttributeName)).isNull();
}
@Test
public void removeAuthorizationRequestWhenNotSavedThenNotRemoved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter(OAuth2ParameterNames.STATE, "state-1234");
MockHttpServletResponse response = new MockHttpServletResponse();
OAuth2AuthorizationRequest removedAuthorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
assertThat(removedAuthorizationRequest).isNull();
}
protected OAuth2AuthorizationRequest.Builder createAuthorizationRequest() {
return OAuth2AuthorizationRequest.authorizationCode().authorizationUri("https://example.com/oauth2/authorize")
.clientId("client-id-1234").state("state-1234");
}
static class MockDistributedHttpSession extends MockHttpSession {
@Override
public Object getAttribute(String name) {
return wrap(super.getAttribute(name));
}
@Override
public void setAttribute(String name, Object value) {
super.setAttribute(name, wrap(value));
}
private Object wrap(Object object) {
if (object instanceof Map) {
object = new HashMap<>((Map<Object, Object>) object);
}
return object;
}
}
}
| 11,232 | 46.8 | 144 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManagerTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link DefaultOAuth2AuthorizedClientManager}.
*
* @author Joe Grandja
*/
public class DefaultOAuth2AuthorizedClientManagerTests {
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private OAuth2AuthorizedClientProvider authorizedClientProvider;
private Function contextAttributesMapper;
private OAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private OAuth2AuthorizationFailureHandler authorizationFailureHandler;
private DefaultOAuth2AuthorizedClientManager authorizedClientManager;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private ArgumentCaptor<OAuth2AuthorizationContext> authorizationContextCaptor;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
this.authorizedClientProvider = mock(OAuth2AuthorizedClientProvider.class);
this.contextAttributesMapper = mock(Function.class);
this.authorizationSuccessHandler = spy(new OAuth2AuthorizationSuccessHandler() {
@Override
public void onAuthorizationSuccess(OAuth2AuthorizedClient authorizedClient, Authentication principal,
Map<String, Object> attributes) {
DefaultOAuth2AuthorizedClientManagerTests.this.authorizedClientRepository.saveAuthorizedClient(
authorizedClient, principal,
(HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
}
});
this.authorizationFailureHandler = spy(
new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler((clientRegistrationId, principal,
attributes) -> this.authorizedClientRepository.removeAuthorizedClient(clientRegistrationId,
principal, (HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName()))));
this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository,
this.authorizedClientRepository);
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
this.authorizedClientManager.setAuthorizationSuccessHandler(this.authorizationSuccessHandler);
this.authorizedClientManager.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(null, this.authorizedClientRepository))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
.withMessage("authorizedClientRepository cannot be null");
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null))
.withMessage("authorizeRequest cannot be null");
}
@Test
public void authorizeWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.withMessage("servletRequest cannot be null");
}
@Test
public void authorizeWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.attribute(HttpServletRequest.class.getName(), this.request).build();
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.withMessage("servletResponse cannot be null");
}
@Test
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId("invalid-registration-id")
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest))
.withMessage("Could not find ClientRegistration with id 'invalid-registration-id'");
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isNull();
verifyNoInteractions(this.authorizationSuccessHandler);
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(this.authorizedClient);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(this.authorizedClient), eq(this.principal),
any());
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal),
eq(this.request), eq(this.response));
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal), eq(this.request))).willReturn(this.authorizedClient);
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(any());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
any());
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal),
eq(this.request), eq(this.response));
}
@Test
public void authorizeWhenRequestParameterUsernamePasswordThenMappedToContext() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(this.clientRegistration);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(this.authorizedClient);
// Set custom contextAttributesMapper
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
Map<String, Object> contextAttributes = new HashMap<>();
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
});
this.request.addParameter(OAuth2ParameterNames.USERNAME, "username");
this.request.addParameter(OAuth2ParameterNames.PASSWORD, "password");
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId())
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
this.authorizedClientManager.authorize(authorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
String username = authorizationContext.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
assertThat(username).isEqualTo("username");
String password = authorizationContext.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
assertThat(password).isEqualTo("password");
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
verifyNoInteractions(this.authorizationSuccessHandler);
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(OAuth2AuthorizedClient.class),
eq(this.principal), eq(this.request), eq(this.response));
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenSupportedProviderThenReauthorized() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizationSuccessHandler).onAuthorizationSuccess(eq(reauthorizedClient), eq(this.principal),
any());
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal),
eq(this.request), eq(this.response));
}
@Test
public void reauthorizeWhenRequestParameterScopeThenMappedToContext() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(reauthorizedClient);
// Override the mock with the default
this.authorizedClientManager
.setContextAttributesMapper(new DefaultOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
this.request.addParameter(OAuth2ParameterNames.SCOPE, "read write");
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
this.authorizedClientManager.authorize(reauthorizeRequest);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
String[] requestScopeAttribute = authorizationContext
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
assertThat(requestScopeAttribute).contains("read", "write");
}
@Test
public void reauthorizeWhenErrorCodeMatchThenRemoveAuthorizedClient() {
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());
verify(this.authorizedClientRepository).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal), eq(this.request), eq(this.response));
}
@Test
public void reauthorizeWhenErrorCodeDoesNotMatchThenDoNotRemoveAuthorizedClient() {
ClientAuthorizationException authorizationException = new ClientAuthorizationException(
new OAuth2Error("non-matching-error-code", null, null), this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willThrow(authorizationException);
// @formatter:off
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal)
.attributes((attrs) -> {
attrs.put(HttpServletRequest.class.getName(), this.request);
attrs.put(HttpServletResponse.class.getName(), this.response);
})
.build();
// @formatter:on
assertThatExceptionOfType(ClientAuthorizationException.class)
.isThrownBy(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(eq(authorizationException), eq(this.principal),
any());
verifyNoInteractions(this.authorizedClientRepository);
}
}
| 24,738 | 50.75523 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilterTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
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.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.CollectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Tests for {@link OAuth2AuthorizationCodeGrantFilter}.
*
* @author Joe Grandja
* @author Parikshit Dutta
*/
public class OAuth2AuthorizationCodeGrantFilterTests {
private ClientRegistration registration1;
private String principalName1 = "principal-1";
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientService authorizedClientService;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private AuthenticationManager authenticationManager;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository;
private OAuth2AuthorizationCodeGrantFilter filter;
@BeforeEach
public void setup() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1);
this.authorizedClientService = new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository);
this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
this.authorizedClientService);
this.authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
this.authenticationManager = mock(AuthenticationManager.class);
this.filter = spy(new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository,
this.authorizedClientRepository, this.authenticationManager));
this.filter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName1, "password");
authentication.setAuthenticated(true);
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(null,
this.authorizedClientRepository, this.authenticationManager));
}
@Test
public void constructorWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository, null,
this.authenticationManager));
}
@Test
public void constructorWhenAuthenticationManagerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizationCodeGrantFilter(this.clientRegistrationRepository,
this.authorizedClientRepository, null));
}
@Test
public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null));
}
@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null));
}
@Test
public void doFilterWhenNotAuthorizationResponseThenNotProcessed() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
// NOTE: A valid Authorization Response contains either a 'code' or 'error'
// parameter.
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationRequestNotFoundThenNotProcessed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/path");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationRequestRedirectUriDoesNotMatchThenNotProcessed() throws Exception {
String requestUri = "/callback/client-1";
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri);
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse.setRequestURI(requestUri + "-no-match");
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
// gh-7963
@Test
public void doFilterWhenAuthorizationRequestRedirectUriParametersMatchThenProcessed() throws Exception {
// 1) redirect_uri with query parameters
String requestUri = "/callback/client-1";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
FilterChain filterChain = mock(FilterChain.class);
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
// 2) redirect_uri with query parameters AND authorization response additional
// parameters
Map<String, String> additionalParameters = new LinkedHashMap<>();
additionalParameters.put("auth-param1", "value1");
additionalParameters.put("auth-param2", "value2");
response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
authorizationResponse = createAuthorizationResponse(authorizationRequest, additionalParameters);
this.filter.doFilter(authorizationResponse, response, filterChain);
verifyNoInteractions(filterChain);
}
// gh-7963
@Test
public void doFilterWhenAuthorizationRequestRedirectUriParametersDoesNotMatchThenNotProcessed() throws Exception {
String requestUri = "/callback/client-1";
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
MockHttpServletRequest authorizationRequest = createAuthorizationRequest(requestUri, parameters);
MockHttpServletResponse response = new MockHttpServletResponse();
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
FilterChain filterChain = mock(FilterChain.class);
// 1) Parameter value
Map<String, String> parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.put("param2", "value8");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(
createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(1)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// 2) Parameter order
parametersNotMatch = new LinkedHashMap<>();
parametersNotMatch.put("param2", "value2");
parametersNotMatch.put("param1", "value1");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(2)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
// 3) Parameter missing
parametersNotMatch = new LinkedHashMap<>(parameters);
parametersNotMatch.remove("param2");
authorizationResponse = createAuthorizationResponse(createAuthorizationRequest(requestUri, parametersNotMatch));
authorizationResponse.setSession(authorizationRequest.getSession());
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(filterChain, times(3)).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationRequestMatchThenAuthorizationRequestRemoved() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(this.authorizationRequestRepository.loadAuthorizationRequest(authorizationResponse)).isNull();
}
@Test
public void doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT);
given(this.authenticationManager.authenticate(any(Authentication.class)))
.willThrow(new OAuth2AuthorizationException(error));
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1?error=invalid_grant");
}
@Test
public void doFilterWhenAuthorizationSucceedsThenAuthorizedClientSavedToService() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientService
.loadAuthorizedClient(this.registration1.getRegistrationId(), this.principalName1);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName1);
assertThat(authorizedClient.getAccessToken()).isNotNull();
assertThat(authorizedClient.getRefreshToken()).isNotNull();
}
@Test
public void doFilterWhenAuthorizationSucceedsThenRedirected() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
@Test
public void doFilterWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext())
.willReturn(new SecurityContextImpl(new TestingAuthenticationToken("user", "password")));
this.filter.setSecurityContextHolderStrategy(strategy);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(strategy).getContext();
assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1");
}
@Test
public void doFilterWhenAuthorizationSucceedsAndHasSavedRequestThenRedirectToSavedRequest() throws Exception {
String requestUri = "/saved-request";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
RequestCache requestCache = new HttpSessionRequestCache();
requestCache.saveRequest(request, response);
request.setRequestURI("/callback/client-1");
request.addParameter(OAuth2ParameterNames.CODE, "code");
request.addParameter(OAuth2ParameterNames.STATE, "state");
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(request, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
String redirectUrl = requestCache.getRequest(request, response).getRedirectUrl();
this.filter.doFilter(request, response, filterChain);
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
}
@Test
public void doFilterWhenAuthorizationSucceedsAndRequestCacheConfiguredThenRequestCacheUsed() throws Exception {
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
RequestCache requestCache = mock(RequestCache.class);
SavedRequest savedRequest = mock(SavedRequest.class);
String redirectUrl = "https://example.com/saved-request?success";
given(savedRequest.getRedirectUrl()).willReturn(redirectUrl);
given(requestCache.getRequest(any(), any())).willReturn(savedRequest);
this.filter.setRequestCache(requestCache);
authorizationRequest.setRequestURI("/saved-request");
requestCache.saveRequest(authorizationRequest, response);
this.filter.doFilter(authorizationResponse, response, filterChain);
verify(requestCache).getRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).isEqualTo(redirectUrl);
}
@Test
public void doFilterWhenAuthorizationSucceedsAndAnonymousAccessThenAuthorizedClientSavedToHttpSession()
throws Exception {
AnonymousAuthenticationToken anonymousPrincipal = new AnonymousAuthenticationToken("key-1234", "anonymousUser",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(anonymousPrincipal);
SecurityContextHolder.setContext(securityContext);
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(
this.registration1.getRegistrationId(), anonymousPrincipal, authorizationResponse);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(anonymousPrincipal.getName());
assertThat(authorizedClient.getAccessToken()).isNotNull();
HttpSession session = authorizationResponse.getSession(false);
assertThat(session).isNotNull();
@SuppressWarnings("unchecked")
Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session
.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
assertThat(authorizedClients).isNotEmpty();
assertThat(authorizedClients).hasSize(1);
assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
@Test
public void doFilterWhenAuthorizationSucceedsAndAnonymousAccessNullAuthenticationThenAuthorizedClientSavedToHttpSession()
throws Exception {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(securityContext); // null Authentication
MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
this.setUpAuthenticationResult(this.registration1);
this.filter.doFilter(authorizationResponse, response, filterChain);
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registration1.getRegistrationId(), null, authorizationResponse);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isEqualTo(this.registration1);
assertThat(authorizedClient.getPrincipalName()).isEqualTo("anonymousUser");
assertThat(authorizedClient.getAccessToken()).isNotNull();
HttpSession session = authorizationResponse.getSession(false);
assertThat(session).isNotNull();
@SuppressWarnings("unchecked")
Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session
.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
assertThat(authorizedClients).isNotEmpty();
assertThat(authorizedClients).hasSize(1);
assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
private static MockHttpServletRequest createAuthorizationRequest(String requestUri) {
return createAuthorizationRequest(requestUri, new LinkedHashMap<>());
}
private static MockHttpServletRequest createAuthorizationRequest(String requestUri,
Map<String, String> parameters) {
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
if (!CollectionUtils.isEmpty(parameters)) {
parameters.forEach(request::addParameter);
request.setQueryString(parameters.entrySet().stream().map((e) -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining("&")));
}
return request;
}
private static MockHttpServletRequest createAuthorizationResponse(MockHttpServletRequest authorizationRequest) {
return createAuthorizationResponse(authorizationRequest, new LinkedHashMap<>());
}
private static MockHttpServletRequest createAuthorizationResponse(MockHttpServletRequest authorizationRequest,
Map<String, String> additionalParameters) {
MockHttpServletRequest authorizationResponse = new MockHttpServletRequest(authorizationRequest.getMethod(),
authorizationRequest.getRequestURI());
authorizationResponse.setServletPath(authorizationRequest.getRequestURI());
authorizationRequest.getParameterMap().forEach(authorizationResponse::addParameter);
authorizationResponse.addParameter(OAuth2ParameterNames.CODE, "code");
authorizationResponse.addParameter(OAuth2ParameterNames.STATE, "state");
additionalParameters.forEach(authorizationResponse::addParameter);
authorizationResponse.setQueryString(authorizationResponse.getParameterMap().entrySet().stream()
.map((e) -> e.getKey() + "=" + e.getValue()[0]).collect(Collectors.joining("&")));
authorizationResponse.setSession(authorizationRequest.getSession());
return authorizationResponse;
}
private void setUpAuthorizationRequest(HttpServletRequest request, HttpServletResponse response,
ClientRegistration registration) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2ParameterNames.REGISTRATION_ID, registration.getRegistrationId());
OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request()
.attributes(attributes).redirectUri(UrlUtils.buildFullRequestUrl(request)).build();
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
}
private void setUpAuthenticationResult(ClientRegistration registration) {
OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
registration, TestOAuth2AuthorizationExchanges.success(), TestOAuth2AccessTokens.noScopes(),
TestOAuth2RefreshTokens.refreshToken());
given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(authentication);
}
}
| 26,518 | 54.363257 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java | /*
* 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
*
* https://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;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link AuthenticatedPrincipalOAuth2AuthorizedClientRepository}.
*
* @author Joe Grandja
*/
public class AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests {
private String registrationId = "registrationId";
private String principalName = "principalName";
private OAuth2AuthorizedClientService authorizedClientService;
private OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository;
private AuthenticatedPrincipalOAuth2AuthorizedClientRepository authorizedClientRepository;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setup() {
this.authorizedClientService = mock(OAuth2AuthorizedClientService.class);
this.anonymousAuthorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
this.authorizedClientService);
this.authorizedClientRepository
.setAnonymousAuthorizedClientRepository(this.anonymousAuthorizedClientRepository);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test
public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null));
}
@Test
public void setAuthorizedClientRepositoryWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null));
}
@Test
public void loadAuthorizedClientWhenAuthenticatedPrincipalThenLoadFromService() {
Authentication authentication = this.createAuthenticatedPrincipal();
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.request);
verify(this.authorizedClientService).loadAuthorizedClient(this.registrationId, this.principalName);
}
@Test
public void loadAuthorizedClientWhenAnonymousPrincipalThenLoadFromAnonymousRepository() {
Authentication authentication = this.createAnonymousPrincipal();
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.request);
verify(this.anonymousAuthorizedClientRepository).loadAuthorizedClient(this.registrationId, authentication,
this.request);
}
@Test
public void saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService() {
Authentication authentication = this.createAuthenticatedPrincipal();
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request,
this.response);
verify(this.authorizedClientService).saveAuthorizedClient(authorizedClient, authentication);
}
@Test
public void saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository() {
Authentication authentication = this.createAnonymousPrincipal();
OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class);
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request,
this.response);
verify(this.anonymousAuthorizedClientRepository).saveAuthorizedClient(authorizedClient, authentication,
this.request, this.response);
}
@Test
public void removeAuthorizedClientWhenAuthenticatedPrincipalThenRemoveFromService() {
Authentication authentication = this.createAuthenticatedPrincipal();
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.request,
this.response);
verify(this.authorizedClientService).removeAuthorizedClient(this.registrationId, this.principalName);
}
@Test
public void removeAuthorizedClientWhenAnonymousPrincipalThenRemoveFromAnonymousRepository() {
Authentication authentication = this.createAnonymousPrincipal();
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.request,
this.response);
verify(this.anonymousAuthorizedClientRepository).removeAuthorizedClient(this.registrationId, authentication,
this.request, this.response);
}
private Authentication createAuthenticatedPrincipal() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName, "password");
authentication.setAuthenticated(true);
return authentication;
}
private Authentication createAnonymousPrincipal() {
return new AnonymousAuthenticationToken("key-1234", "anonymousUser",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
}
}
| 6,174 | 42.181818 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepositoryTests.java | /*
* 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
*
* https://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;
import java.util.Map;
import jakarta.servlet.http.HttpSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link HttpSessionOAuth2AuthorizedClientRepository}.
*
* @author Joe Grandja
*/
public class HttpSessionOAuth2AuthorizedClientRepositoryTests {
private String principalName1 = "principalName-1";
private ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();
private ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();
private String registrationId1 = this.registration1.getRegistrationId();
private String registrationId2 = this.registration2.getRegistrationId();
private HttpSessionOAuth2AuthorizedClientRepository authorizedClientRepository = new HttpSessionOAuth2AuthorizedClientRepository();
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test
public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.request));
}
@Test
public void loadAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, this.request);
}
@Test
public void loadAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null));
}
@Test
public void loadAuthorizedClientWhenClientRegistrationNotFoundThenReturnNull() {
OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository
.loadAuthorizedClient("registration-not-found", null, this.request);
assertThat(authorizedClient).isNull();
}
@Test
public void loadAuthorizedClientWhenSavedThenReturnAuthorizedClient() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.request);
assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
}
@Test
public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.request, this.response));
}
@Test
public void saveAuthorizedClientWhenAuthenticationIsNullThenExceptionNotThrown() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
}
@Test
public void saveAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository
.saveAuthorizedClient(authorizedClient, null, null, this.response));
}
@Test
public void saveAuthorizedClientWhenResponseIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, null));
}
@Test
public void saveAuthorizedClientWhenSavedThenSavedToSession() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
HttpSession session = this.request.getSession(false);
assertThat(session).isNotNull();
@SuppressWarnings("unchecked")
Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session
.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
assertThat(authorizedClients).isNotEmpty();
assertThat(authorizedClients).hasSize(1);
assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
}
@Test
public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.request, this.response));
}
@Test
public void removeAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
}
@Test
public void removeAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository
.removeAuthorizedClient(this.registrationId1, null, null, this.response));
}
@Test
public void removeAuthorizedClientWhenResponseIsNullThenExceptionNotThrown() {
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, null);
}
@Test
public void removeAuthorizedClientWhenNotSavedThenSessionNotCreated() {
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
assertThat(this.request.getSession(false)).isNull();
}
@Test
public void removeAuthorizedClientWhenClient1SavedAndClient2RemovedThenClient1NotRemoved() {
OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.request, this.response);
// Remove registrationId2 (never added so is not removed either)
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
OAuth2AuthorizedClient loadedAuthorizedClient1 = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.request);
assertThat(loadedAuthorizedClient1).isNotNull();
assertThat(loadedAuthorizedClient1).isSameAs(authorizedClient1);
}
@Test
public void removeAuthorizedClientWhenSavedThenRemoved() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.request);
assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
loadedAuthorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registrationId2, null,
this.request);
assertThat(loadedAuthorizedClient).isNull();
}
@Test
public void removeAuthorizedClientWhenSavedThenRemovedFromSession() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId1, null, this.request);
assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
HttpSession session = this.request.getSession(false);
assertThat(session).isNotNull();
assertThat(session
.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS"))
.isNull();
}
@Test
public void removeAuthorizedClientWhenClient1Client2SavedAndClient1RemovedThenClient2NotRemoved() {
OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.request, this.response);
OAuth2AuthorizedClient authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
mock(OAuth2AccessToken.class));
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient2, null, this.request, this.response);
this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
OAuth2AuthorizedClient loadedAuthorizedClient2 = this.authorizedClientRepository
.loadAuthorizedClient(this.registrationId2, null, this.request);
assertThat(loadedAuthorizedClient2).isNotNull();
assertThat(loadedAuthorizedClient2).isSameAs(authorizedClient2);
}
}
| 10,942 | 46.578261 | 132 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilterTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.util.ClassUtils;
import org.springframework.web.util.UriComponentsBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests for {@link OAuth2AuthorizationRequestRedirectFilter}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizationRequestRedirectFilterTests {
private ClientRegistration registration1;
private ClientRegistration registration2;
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizationRequestRedirectFilter filter;
private RequestCache requestCache;
@BeforeEach
public void setUp() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.registration2 = TestClientRegistrations.clientRegistration2().build();
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2);
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository);
this.requestCache = mock(RequestCache.class);
this.filter.setRequestCache(this.requestCache);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
Constructor<OAuth2AuthorizationRequestRedirectFilter> constructor = ClassUtils.getConstructorIfAvailable(
OAuth2AuthorizationRequestRedirectFilter.class, ClientRegistrationRepository.class);
assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null));
}
@Test
public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository, null));
}
@Test
public void constructorWhenAuthorizationRequestResolverIsNullThenThrowIllegalArgumentException() {
Constructor<OAuth2AuthorizationRequestRedirectFilter> constructor = ClassUtils.getConstructorIfAvailable(
OAuth2AuthorizationRequestRedirectFilter.class, OAuth2AuthorizationRequestResolver.class);
assertThatIllegalArgumentException().isThrownBy(() -> constructor.newInstance(null));
}
@Test
public void setAuthorizationRequestRepositoryWhenAuthorizationRequestRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRequestRepository(null));
}
@Test
public void setAuthorizationRedirectStrategyWhenAuthorizationRedirectStrategyIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthorizationRedirectStrategy(null));
}
@Test
public void setRequestCacheWhenRequestCacheIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestCache(null));
}
@Test
public void doFilterWhenNotAuthorizationRequestThenNextFilter() throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenAuthorizationRequestWithInvalidClientThenStatusInternalServerError() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId() + "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenRedirectForAuthorization() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
@Test
public void doFilterWhenAuthorizationRequestOAuth2LoginThenAuthorizationRequestSaved() throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration2.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = mock(
AuthorizationRequestRepository.class);
this.filter.setAuthorizationRequestRepository(authorizationRequestRepository);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
verify(authorizationRequestRepository).saveAuthorizationRequest(any(OAuth2AuthorizationRequest.class),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenCustomAuthorizationRequestBaseUriThenRedirectForAuthorization() throws Exception {
String authorizationRequestBaseUri = "/custom/authorization";
this.filter = new OAuth2AuthorizationRequestRedirectFilter(this.clientRegistrationRepository,
authorizationRequestBaseUri);
String requestUri = authorizationRequestBaseUri + "/" + this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenRedirectForAuthorization()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id");
verify(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownButAuthorizationRequestNotResolvedThenStatusInternalServerError()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class));
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.value());
assertThat(response.getErrorMessage()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
// gh-4911
@Test
public void doFilterWhenAuthorizationRequestAndAdditionalParametersProvidedThenAuthorizationRequestIncludesAdditionalParameters()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.addParameter("idp", "https://other.provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(
this.clientRegistrationRepository,
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest
.from(defaultAuthorizationRequestResolver.resolve(request))
.additionalParameters(Collections.singletonMap("idp", request.getParameter("idp"))).build();
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&"
+ "idp=https://other.provider.com");
}
// gh-4911, gh-5244
@Test
public void doFilterWhenAuthorizationRequestAndCustomAuthorizationRequestUriSetThenCustomAuthorizationRequestUriUsed()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
String loginHintParamName = "login_hint";
request.addParameter(loginHintParamName, "user@provider.com");
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
OAuth2AuthorizationRequestResolver defaultAuthorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(
this.clientRegistrationRepository,
OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
OAuth2AuthorizationRequestResolver resolver = mock(OAuth2AuthorizationRequestResolver.class);
OAuth2AuthorizationRequest defaultAuthorizationRequest = defaultAuthorizationRequestResolver.resolve(request);
Map<String, Object> additionalParameters = new HashMap<>(defaultAuthorizationRequest.getAdditionalParameters());
additionalParameters.put(loginHintParamName, request.getParameter(loginHintParamName));
// @formatter:off
String customAuthorizationRequestUri = UriComponentsBuilder
.fromUriString(defaultAuthorizationRequest.getAuthorizationRequestUri())
.queryParam(loginHintParamName, additionalParameters.get(loginHintParamName))
.build(true)
.toUriString();
OAuth2AuthorizationRequest result = OAuth2AuthorizationRequest
.from(defaultAuthorizationRequestResolver.resolve(request))
.additionalParameters(Collections.singletonMap("idp", request.getParameter("idp")))
.authorizationRequestUri(customAuthorizationRequestUri)
.build();
// @formatter:on
given(resolver.resolve(any())).willReturn(result);
OAuth2AuthorizationRequestRedirectFilter filter = new OAuth2AuthorizationRequestRedirectFilter(resolver);
filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getRedirectedUrl()).matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id&"
+ "login_hint=user@provider\\.com");
}
@Test
public void doFilterWhenCustomAuthorizationRedirectStrategySetThenCustomAuthorizationRedirectStrategyUsed()
throws Exception {
String requestUri = OAuth2AuthorizationRequestRedirectFilter.DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/"
+ this.registration1.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
RedirectStrategy customRedirectStrategy = (httpRequest, httpResponse, url) -> {
String redirectUrl = httpResponse.encodeRedirectURL(url);
httpResponse.setStatus(HttpStatus.OK.value());
httpResponse.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
httpResponse.getWriter().write(redirectUrl);
httpResponse.getWriter().flush();
};
this.filter.setAuthorizationRedirectStrategy(customRedirectStrategy);
this.filter.doFilter(request, response, filterChain);
verifyNoMoreInteractions(filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentType()).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(response.getContentAsString(StandardCharsets.UTF_8))
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
// gh-11602
@Test
public void doFilterWhenNotAuthorizationRequestAndClientAuthorizationRequiredExceptionThrownThenSaveRequestBeforeCommitted()
throws Exception {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = mock(FilterChain.class);
willAnswer((invocation) -> assertThat((invocation.<HttpServletResponse>getArgument(1)).isCommitted()).isFalse())
.given(this.requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class));
willThrow(new ClientAuthorizationRequiredException(this.registration1.getRegistrationId())).given(filterChain)
.doFilter(any(ServletRequest.class), any(ServletResponse.class));
this.filter.doFilter(request, response, filterChain);
assertThat(response.isCommitted()).isTrue();
}
}
| 18,522 | 52.227011 | 158 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolverTests.java | /*
* Copyright 2002-2022 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
*
* https://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;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponseType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;
/**
* Tests for {@link DefaultOAuth2AuthorizationRequestResolver}.
*
* @author Joe Grandja
*/
public class DefaultOAuth2AuthorizationRequestResolverTests {
private ClientRegistration registration1;
private ClientRegistration registration2;
private ClientRegistration fineRedirectUriTemplateRegistration;
private ClientRegistration publicClientRegistration;
private ClientRegistration oidcRegistration;
private ClientRegistrationRepository clientRegistrationRepository;
private final String authorizationRequestBaseUri = "/oauth2/authorization";
private DefaultOAuth2AuthorizationRequestResolver resolver;
@BeforeEach
public void setUp() {
this.registration1 = TestClientRegistrations.clientRegistration().build();
this.registration2 = TestClientRegistrations.clientRegistration2().build();
this.fineRedirectUriTemplateRegistration = fineRedirectUriTemplateClientRegistration().build();
// @formatter:off
this.publicClientRegistration = TestClientRegistrations.clientRegistration()
.registrationId("public-client-registration-id")
.clientId("public-client-id")
.clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
.clientSecret(null)
.build();
this.oidcRegistration = TestClientRegistrations.clientRegistration()
.registrationId("oidc-registration-id")
.scope(OidcScopes.OPENID)
.build();
// @formatter:on
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2, this.fineRedirectUriTemplateRegistration, this.publicClientRegistration,
this.oidcRegistration);
this.resolver = new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository,
this.authorizationRequestBaseUri);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new DefaultOAuth2AuthorizationRequestResolver(null, this.authorizationRequestBaseUri));
}
@Test
public void constructorWhenAuthorizationRequestBaseUriIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new DefaultOAuth2AuthorizationRequestResolver(this.clientRegistrationRepository, null));
}
@Test
public void setAuthorizationRequestCustomizerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.resolver.setAuthorizationRequestCustomizer(null));
}
@Test
public void resolveWhenNotAuthorizationRequestThenDoesNotResolve() {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNull();
}
// gh-8650
@Test
public void resolveWhenNotAuthorizationRequestThenRequestBodyNotConsumed() throws IOException {
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri);
request.setContent("foo".getBytes(StandardCharsets.UTF_8));
request.setCharacterEncoding(StandardCharsets.UTF_8.name());
HttpServletRequest spyRequest = Mockito.spy(request);
this.resolver.resolve(spyRequest);
Mockito.verify(spyRequest, Mockito.never()).getReader();
Mockito.verify(spyRequest, Mockito.never()).getInputStream();
Mockito.verify(spyRequest, Mockito.never()).getParameter(ArgumentMatchers.anyString());
Mockito.verify(spyRequest, Mockito.never()).getParameterMap();
Mockito.verify(spyRequest, Mockito.never()).getParameterNames();
Mockito.verify(spyRequest, Mockito.never()).getParameterValues(ArgumentMatchers.anyString());
}
@Test
public void resolveWhenAuthorizationRequestWithInvalidClientThenThrowIllegalArgumentException() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId()
+ "-invalid";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.resolver.resolve(request))
.withMessage("Invalid Client Registration with Id: " + clientRegistration.getRegistrationId() + "-invalid");
// @formatter:on
}
@Test
public void resolveWhenAuthorizationRequestWithValidClientThenResolves() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAttributes())
.containsExactly(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenClientAuthorizationRequiredExceptionAvailableThenResolves() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request,
clientRegistration.getRegistrationId());
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAttributes())
.containsExactly(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenRedirectUriExpanded() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenHttpRedirectUriWithExtraVarsExpanded() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServerPort(8080);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost:8080/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenHttpsRedirectUriWithExtraVarsExpanded() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerPort(8081);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("https://localhost:8081/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort80ThenExpandedRedirectUriWithExtraVarsExcludesPort() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("http");
request.setServerPort(80);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort443ThenExpandedRedirectUriWithExtraVarsExcludesPort() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerPort(443);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("https://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestHasNoPortThenExpandedRedirectUriWithExtraVarsExcludesPort() {
ClientRegistration clientRegistration = this.fineRedirectUriTemplateRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerPort(-1);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("https://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
// gh-5520
@Test
public void resolveWhenAuthorizationRequestRedirectUriTemplatedThenRedirectUriExpandedExcludesQueryString() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
request.setQueryString("foo=bar");
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getRedirectUri()).isNotEqualTo(clientRegistration.getRedirectUri());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort80ThenExpandedRedirectUriExcludesPort() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("http");
request.setServerName("localhost");
request.setServerPort(80);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenAuthorizationRequestIncludesPort443ThenExpandedRedirectUriExcludesPort() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setScheme("https");
request.setServerName("example.com");
request.setServerPort(443);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=https://example.com/login/oauth2/code/registration-id");
}
@Test
public void resolveWhenClientAuthorizationRequiredExceptionAvailableThenRedirectUriIsAuthorize() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = "/path";
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request,
clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id");
}
@Test
public void resolveWhenAuthorizationRequestOAuth2LoginThenRedirectUriIsLogin() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id-2&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id-2");
}
@Test
public void resolveWhenAuthorizationRequestHasActionParameterAuthorizeThenRedirectUriIsAuthorize() {
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.addParameter("action", "authorize");
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/authorize/oauth2/code/registration-id");
}
@Test
public void resolveWhenAuthorizationRequestHasActionParameterLoginThenRedirectUriIsLogin() {
ClientRegistration clientRegistration = this.registration2;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.addParameter("action", "login");
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id-2&"
+ "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/registration-id-2");
}
@Test
public void resolveWhenAuthorizationRequestWithValidPublicClientThenResolves() {
ClientRegistration clientRegistration = this.publicClientRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.contains(entry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"));
assertThat(authorizationRequest.getAttributes())
.contains(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
assertThat(authorizationRequest.getAttributes()).containsKey(PkceParameterNames.CODE_VERIFIER);
assertThat((String) authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?"
+ "response_type=code&client_id=public-client-id&" + "scope=read:user&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/public-client-registration-id&"
+ "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
// gh-6548
@Test
public void resolveWhenAuthorizationRequestApplyPkceToConfidentialClientsThenApplied() {
this.resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertPkceApplied(authorizationRequest, clientRegistration);
clientRegistration = this.registration2;
requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
authorizationRequest = this.resolver.resolve(request);
assertPkceApplied(authorizationRequest, clientRegistration);
}
// gh-6548
@Test
public void resolveWhenAuthorizationRequestApplyPkceToSpecificConfidentialClientThenApplied() {
this.resolver.setAuthorizationRequestCustomizer((builder) -> {
builder.attributes((attrs) -> {
String registrationId = (String) attrs.get(OAuth2ParameterNames.REGISTRATION_ID);
if (this.registration1.getRegistrationId().equals(registrationId)) {
OAuth2AuthorizationRequestCustomizers.withPkce().accept(builder);
}
});
});
ClientRegistration clientRegistration = this.registration1;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertPkceApplied(authorizationRequest, clientRegistration);
clientRegistration = this.registration2;
requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
authorizationRequest = this.resolver.resolve(request);
assertPkceNotApplied(authorizationRequest, clientRegistration);
}
private void assertPkceApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.contains(entry(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256"));
assertThat(authorizationRequest.getAttributes()).containsKey(PkceParameterNames.CODE_VERIFIER);
assertThat((String) authorizationRequest.getAttribute(PkceParameterNames.CODE_VERIFIER))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId()
+ "&" + "code_challenge=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "code_challenge_method=S256");
}
private void assertPkceNotApplied(OAuth2AuthorizationRequest authorizationRequest,
ClientRegistration clientRegistration) {
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(PkceParameterNames.CODE_CHALLENGE);
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(PkceParameterNames.CODE_CHALLENGE_METHOD);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(PkceParameterNames.CODE_VERIFIER);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "client_id="
+ clientRegistration.getClientId() + "&" + "scope=read:user&" + "state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
}
@Test
public void resolveWhenAuthenticationRequestWithValidOidcClientThenResolves() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest).isNotNull();
assertThat(authorizationRequest.getAuthorizationUri())
.isEqualTo(clientRegistration.getProviderDetails().getAuthorizationUri());
assertThat(authorizationRequest.getGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
assertThat(authorizationRequest.getResponseType()).isEqualTo(OAuth2AuthorizationResponseType.CODE);
assertThat(authorizationRequest.getClientId()).isEqualTo(clientRegistration.getClientId());
assertThat(authorizationRequest.getRedirectUri())
.isEqualTo("http://localhost/login/oauth2/code/" + clientRegistration.getRegistrationId());
assertThat(authorizationRequest.getScopes()).isEqualTo(clientRegistration.getScopes());
assertThat(authorizationRequest.getState()).isNotNull();
assertThat(authorizationRequest.getAdditionalParameters())
.doesNotContainKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAdditionalParameters()).containsKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes())
.contains(entry(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
assertThat(authorizationRequest.getAttributes()).containsKey(OidcParameterNames.NONCE);
assertThat((String) authorizationRequest.getAttribute(OidcParameterNames.NONCE))
.matches("^([a-zA-Z0-9\\-\\.\\_\\~]){128}$");
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}");
}
// gh-7696
@Test
public void resolveWhenAuthorizationRequestCustomizerRemovesNonceThenQueryExcludesNonce() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
this.resolver.setAuthorizationRequestCustomizer(
(builder) -> builder.additionalParameters((params) -> params.remove(OidcParameterNames.NONCE))
.attributes((attrs) -> attrs.remove(OidcParameterNames.NONCE)));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAdditionalParameters()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).doesNotContainKey(OidcParameterNames.NONCE);
assertThat(authorizationRequest.getAttributes()).containsKey(OAuth2ParameterNames.REGISTRATION_ID);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerAddsParameterThenQueryIncludesParameter() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.authorizationRequestUri((uriBuilder) -> {
uriBuilder.queryParam("param1", "value1");
return uriBuilder.build();
}));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri())
.matches("https://example.com/login/oauth/authorize\\?" + "response_type=code&client_id=client-id&"
+ "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "param1=value1");
}
@Test
public void resolveWhenAuthorizationRequestCustomizerOverridesParameterThenQueryIncludesParameter() {
ClientRegistration clientRegistration = this.oidcRegistration;
String requestUri = this.authorizationRequestBaseUri + "/" + clientRegistration.getRegistrationId();
MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri);
request.setServletPath(requestUri);
this.resolver.setAuthorizationRequestCustomizer((builder) -> builder.parameters((params) -> {
params.put("appid", params.get("client_id"));
params.remove("client_id");
}));
OAuth2AuthorizationRequest authorizationRequest = this.resolver.resolve(request);
assertThat(authorizationRequest.getAuthorizationRequestUri()).matches(
"https://example.com/login/oauth/authorize\\?" + "response_type=code&" + "scope=openid&state=.{15,}&"
+ "redirect_uri=http://localhost/login/oauth2/code/oidc-registration-id&"
+ "nonce=([a-zA-Z0-9\\-\\.\\_\\~]){43}&" + "appid=client-id");
}
private static ClientRegistration.Builder fineRedirectUriTemplateClientRegistration() {
// @formatter:off
return ClientRegistration.withRegistrationId("fine-redirect-uri-template-client-registration")
.redirectUri("{baseScheme}://{baseHost}{basePort}{basePath}/{action}/oauth2/code/{registrationId}")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.scope("read:user")
.authorizationUri("https://example.com/login/oauth/authorize")
.tokenUri("https://example.com/login/oauth/access_token")
.userInfoUri("https://api.example.com/user")
.userNameAttributeName("id")
.clientName("Fine Redirect Uri Template Client")
.clientId("fine-redirect-uri-template-client")
.clientSecret("client-secret");
// @formatter:on
}
}
| 32,384 | 54.358974 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManagerTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.core.publisher.Mono;
import reactor.test.publisher.PublisherProbe;
import reactor.util.context.Context;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link DefaultReactiveOAuth2AuthorizedClientManager}.
*
* @author Joe Grandja
*/
public class DefaultReactiveOAuth2AuthorizedClientManagerTests {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider;
private Function contextAttributesMapper;
private DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager;
private ClientRegistration clientRegistration;
private Authentication principal;
private OAuth2AuthorizedClient authorizedClient;
private MockServerWebExchange serverWebExchange;
private Context context;
private ArgumentCaptor<OAuth2AuthorizationContext> authorizationContextCaptor;
private PublisherProbe<OAuth2AuthorizedClient> loadAuthorizedClientProbe;
private PublisherProbe<Void> saveAuthorizedClientProbe;
private PublisherProbe<Void> removeAuthorizedClientProbe;
@SuppressWarnings("unchecked")
@BeforeEach
public void setup() {
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
given(this.clientRegistrationRepository.findByRegistrationId(anyString())).willReturn(Mono.empty());
this.authorizedClientRepository = mock(ServerOAuth2AuthorizedClientRepository.class);
this.loadAuthorizedClientProbe = PublisherProbe.empty();
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(Authentication.class),
any(ServerWebExchange.class))).willReturn(this.loadAuthorizedClientProbe.mono());
this.saveAuthorizedClientProbe = PublisherProbe.empty();
given(this.authorizedClientRepository.saveAuthorizedClient(any(OAuth2AuthorizedClient.class),
any(Authentication.class), any(ServerWebExchange.class)))
.willReturn(this.saveAuthorizedClientProbe.mono());
this.removeAuthorizedClientProbe = PublisherProbe.empty();
given(this.authorizedClientRepository.removeAuthorizedClient(any(String.class), any(Authentication.class),
any(ServerWebExchange.class))).willReturn(this.removeAuthorizedClientProbe.mono());
this.authorizedClientProvider = mock(ReactiveOAuth2AuthorizedClientProvider.class);
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.empty());
this.contextAttributesMapper = mock(Function.class);
given(this.contextAttributesMapper.apply(any())).willReturn(Mono.just(Collections.emptyMap()));
this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
this.authorizedClientManager.setAuthorizedClientProvider(this.authorizedClientProvider);
this.authorizedClientManager.setContextAttributesMapper(this.contextAttributesMapper);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.principal = new TestingAuthenticationToken("principal", "password");
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.principal.getName(),
TestOAuth2AccessTokens.scopes("read", "write"), TestOAuth2RefreshTokens.refreshToken());
this.serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/")).build();
this.context = Context.of(ServerWebExchange.class, this.serverWebExchange);
this.authorizationContextCaptor = ArgumentCaptor.forClass(OAuth2AuthorizationContext.class);
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(
() -> new DefaultReactiveOAuth2AuthorizedClientManager(null, this.authorizedClientRepository))
.withMessage("clientRegistrationRepository cannot be null");
}
@Test
public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(
() -> new DefaultReactiveOAuth2AuthorizedClientManager(this.clientRegistrationRepository, null))
.withMessage("authorizedClientRepository cannot be null");
}
@Test
public void setAuthorizedClientProviderWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizedClientProvider(null))
.withMessage("authorizedClientProvider cannot be null");
}
@Test
public void setAuthorizationSuccessHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationSuccessHandler(null))
.withMessage("authorizationSuccessHandler cannot be null");
}
@Test
public void setAuthorizationFailureHandlerWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setAuthorizationFailureHandler(null))
.withMessage("authorizationFailureHandler cannot be null");
}
@Test
public void setContextAttributesMapperWhenNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.setContextAttributesMapper(null))
.withMessage("contextAttributesMapper cannot be null");
}
@Test
public void authorizeWhenRequestIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientManager.authorize(null).block())
.withMessage("authorizeRequest cannot be null");
}
@Test
public void authorizeWhenExchangeIsNullThenThrowIllegalArgumentException() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block())
.withMessage("serverWebExchange cannot be null");
}
@Test
public void authorizeWhenClientRegistrationNotFoundThenThrowIllegalArgumentException() {
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId("invalid-registration-id").principal(this.principal).build();
assertThatIllegalArgumentException().isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.withMessage("Could not find ClientRegistration with id 'invalid-registration-id'");
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndUnsupportedProviderThenNotAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isNull();
this.loadAuthorizedClientProbe.assertWasSubscribed();
this.saveAuthorizedClientProbe.assertWasNotSubscribed();
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderThenAuthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(this.authorizedClient), eq(this.principal),
eq(this.serverWebExchange));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenNotAuthorizedAndSupportedProviderAndCustomSuccessHandlerThenInvokeCustomSuccessHandler() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
PublisherProbe<Void> authorizationSuccessHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationSuccessHandler(
(client, principal, attributes) -> authorizationSuccessHandlerProbe.mono());
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
authorizationSuccessHandlerProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenInvalidTokenThenRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientRepository).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal), eq(this.serverWebExchange));
this.removeAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenInvalidGrantThenRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientRepository).removeAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal), eq(this.serverWebExchange));
this.removeAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
ClientAuthorizationException exception = new ClientAuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null),
this.clientRegistration.getRegistrationId());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenOAuth2AuthorizationExceptionThenDoNotRemoveAuthorizedClient() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.error(exception));
PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
this.authorizedClientManager.setAuthorizationFailureHandler(
(client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
() -> this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block())
.isEqualTo(exception);
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isNull();
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
authorizationFailureHandlerProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
}
@SuppressWarnings("unchecked")
@Test
public void authorizeWhenAuthorizedAndSupportedProviderThenReauthorized() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
this.loadAuthorizedClientProbe = PublisherProbe.of(Mono.just(this.authorizedClient));
given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.clientRegistration.getRegistrationId()),
eq(this.principal), eq(this.serverWebExchange))).willReturn(this.loadAuthorizedClientProbe.mono());
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(authorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(any());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal),
eq(this.serverWebExchange));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
}
@Test
public void authorizeWhenRequestFormParameterUsernamePasswordThenMappedToContext() {
given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId())))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(this.authorizedClient));
// Set custom contextAttributesMapper capable of mapping the form parameters
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> currentServerWebExchange()
.flatMap(ServerWebExchange::getFormData).map((formData) -> {
Map<String, Object> contextAttributes = new HashMap<>();
String username = formData.getFirst(OAuth2ParameterNames.USERNAME);
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
String password = formData.getFirst(OAuth2ParameterNames.PASSWORD);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
return contextAttributes;
}));
this.serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED).body("username=username&password=password"))
.build();
this.context = Context.of(ServerWebExchange.class, this.serverWebExchange);
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal)
.build();
this.authorizedClientManager.authorize(authorizeRequest).contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
String username = authorizationContext.getAttribute(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME);
assertThat(username).isEqualTo("username");
String password = authorizationContext.getAttribute(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME);
assertThat(password).isEqualTo("password");
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenUnsupportedProviderThenNotReauthorized() {
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(this.authorizedClient);
this.saveAuthorizedClientProbe.assertWasNotSubscribed();
}
@SuppressWarnings("unchecked")
@Test
public void reauthorizeWhenSupportedProviderThenReauthorized() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
OAuth2AuthorizedClient authorizedClient = this.authorizedClientManager.authorize(reauthorizeRequest)
.contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
verify(this.contextAttributesMapper).apply(eq(reauthorizeRequest));
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
assertThat(authorizationContext.getAuthorizedClient()).isSameAs(this.authorizedClient);
assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
assertThat(authorizedClient).isSameAs(reauthorizedClient);
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(reauthorizedClient), eq(this.principal),
eq(this.serverWebExchange));
this.saveAuthorizedClientProbe.assertWasSubscribed();
verify(this.authorizedClientRepository, never()).removeAuthorizedClient(any(), any(), any());
}
@Test
public void reauthorizeWhenRequestParameterScopeThenMappedToContext() {
OAuth2AuthorizedClient reauthorizedClient = new OAuth2AuthorizedClient(this.clientRegistration,
this.principal.getName(), TestOAuth2AccessTokens.noScopes(), TestOAuth2RefreshTokens.refreshToken());
given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class)))
.willReturn(Mono.just(reauthorizedClient));
// Override the mock with the default
this.authorizedClientManager.setContextAttributesMapper(
new DefaultReactiveOAuth2AuthorizedClientManager.DefaultContextAttributesMapper());
this.serverWebExchange = MockServerWebExchange
.builder(MockServerHttpRequest.get("/").queryParam(OAuth2ParameterNames.SCOPE, "read write")).build();
this.context = Context.of(ServerWebExchange.class, this.serverWebExchange);
OAuth2AuthorizeRequest reauthorizeRequest = OAuth2AuthorizeRequest.withAuthorizedClient(this.authorizedClient)
.principal(this.principal).build();
this.authorizedClientManager.authorize(reauthorizeRequest).contextWrite(this.context).block();
verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
String[] requestScopeAttribute = authorizationContext
.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME);
assertThat(requestScopeAttribute).contains("read", "write");
}
private Mono<ServerWebExchange> currentServerWebExchange() {
return Mono.deferContextual(Mono::just).filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class));
}
}
| 31,796 | 57.774492 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionTests.java | /*
* Copyright 2002-2022 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
*
* https://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.reactive.function.client;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.test.publisher.PublisherProbe;
import reactor.util.context.Context;
import org.springframework.core.codec.ByteBufferEncoder;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.FormHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.ServerSentEventHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.multipart.MultipartHttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.ClientCredentialsReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.JwtBearerReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests {
@Mock
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient;
@Mock
private ReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient;
@Mock
private ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
@Captor
private ArgumentCaptor<OAuth2AuthorizationException> authorizationExceptionCaptor;
@Captor
private ArgumentCaptor<Authentication> authenticationCaptor;
@Captor
private ArgumentCaptor<Map<String, Object>> attributesCaptor;
private ServerWebExchange serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/")).build();
@Captor
private ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor;
private ServerOAuth2AuthorizedClientExchangeFilterFunction function;
private MockExchangeFunction exchange = new MockExchangeFunction();
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
private DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager;
@BeforeEach
public void setup() {
// @formatter:off
JwtBearerReactiveOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerReactiveOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(this.jwtBearerTokenResponseClient);
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.authorizationCode()
.refreshToken(
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
.clientCredentials(
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
.provider(jwtBearerAuthorizedClientProvider)
.build();
// @formatter:on
this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.function = new ServerOAuth2AuthorizedClientExchangeFilterFunction(this.authorizedClientManager);
}
private void setupMocks() {
setupMockSaveAuthorizedClient();
setupMockHeaders();
}
private void setupMockSaveAuthorizedClient() {
given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
}
private void setupMockHeaders() {
given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class));
}
@Test
public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ServerOAuth2AuthorizedClientExchangeFilterFunction(null));
}
@Test
public void filterWhenAuthorizedClientNullThenAuthorizationHeaderNull() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthorizedClientThenAuthorizationHeader() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:off
this.function.filter(request, this.exchange).contextWrite(serverWebExchange())
.block();
// @formatter:on
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
@Test
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing")
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}
@Test
public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() {
setupMocks();
// @formatter:off
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse
.withToken("new-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER)
.expiresIn(360)
.build();
// @formatter:on
given(this.clientCredentialsTokenResponseClient.getTokenResponse(any()))
.willReturn(Mono.just(accessTokenResponse));
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
OAuth2AccessToken accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(),
this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName", accessToken,
null);
TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.contextWrite(serverWebExchange())
.block();
// @formatter:on
verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(authentication), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken() {
TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName",
this.accessToken, null);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.contextWrite(serverWebExchange())
.block();
// @formatter:on
verify(this.clientCredentialsTokenResponseClient, never()).getTokenResponse(any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenRefreshRequiredThenRefresh() {
setupMocks();
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
// @formatter:off
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.contextWrite(serverWebExchange())
.block();
// @formatter:on
verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(),
eq(authentication), any());
OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(response.getRefreshToken());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved() {
setupMocks();
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
this.function.filter(request, this.exchange)
.contextWrite(serverWebExchange())
.block();
// @formatter:on
verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
setupMocks();
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId("jwt-bearer")
.clientId("client-id")
.clientSecret("client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.tokenUri("https://example.com/oauth/token")
.build();
// @formatter:on
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId())))
.willReturn(Mono.just(registration));
Jwt jwtAssertion = TestJwts.jwt().build();
Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()),
eq(jwtAuthentication), any())).willReturn(Mono.empty());
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId()))
.build();
// @formatter:on
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(jwtAuthentication))
.contextWrite(serverWebExchange()).block();
verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).loadAuthorizedClient(eq(registration.getRegistrationId()),
eq(jwtAuthentication), any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer exchanged-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenRefreshTokenNullThenShouldRefreshFalse() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
this.function.filter(request, this.exchange)
.contextWrite(serverWebExchange())
.block();
// @formatter:on
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenNotExpiredThenShouldRefreshFalse() {
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
this.function.filter(request, this.exchange)
.contextWrite(serverWebExchange())
.block();
// @formatter:on
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenUnauthorizedThenInvokeFailureHandler() {
setupMockHeaders();
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
given(this.exchange.getResponse().statusCode()).willReturn(HttpStatus.UNAUTHORIZED);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining("[invalid_token]");
});
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler() {
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(),
HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
// @formatter:off
assertThatExceptionOfType(WebClientResponseException.class)
.isThrownBy(() -> this.function
.filter(request, throwingExchangeFunction)
.contextWrite(serverWebExchange())
.block()
)
.isEqualTo(exception);
// @formatter:on
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
// @formatter:off
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token");
assertThat(ex).hasCause(exception);
assertThat(ex).hasMessageContaining("[invalid_token]");
});
// @formatter:on
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenForbiddenThenInvokeFailureHandler() {
setupMockHeaders();
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
given(this.exchange.getResponse().statusCode()).willReturn(HttpStatus.FORBIDDEN);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo("insufficient_scope");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining("[insufficient_scope]");
});
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenForbiddenWithWebClientExceptionThenInvokeFailureHandler() {
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
WebClientResponseException exception = WebClientResponseException.create(HttpStatus.FORBIDDEN.value(),
HttpStatus.FORBIDDEN.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
// @formatter:off
assertThatExceptionOfType(WebClientResponseException.class)
.isThrownBy(() -> this.function
.filter(request, throwingExchangeFunction)
.contextWrite(serverWebExchange())
.block()
)
.isEqualTo(exception);
// @formatter:on
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo("insufficient_scope");
assertThat(ex).hasCause(exception);
assertThat(ex).hasMessageContaining("[insufficient_scope]");
});
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler() {
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", "
+ "error_description=\"The request requires higher privileges than provided by the access token.\", "
+ "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE)))
.willReturn(Collections.singletonList(wwwAuthenticateHeader));
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
assertThat(ex.getError().getDescription())
.isEqualTo("The request requires higher privileges than provided by the access token.");
assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
});
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() {
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any()))
.willReturn(publisherProbe.mono());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
OAuth2AuthorizationException exception = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null));
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(
() -> this.function.filter(request, throwingExchangeFunction).contextWrite(serverWebExchange()).block())
.isEqualTo(exception);
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue()).isSameAs(exception);
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue())
.containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
@Test
public void filterWhenOtherHttpStatusShouldNotInvokeFailureHandler() {
setupMockHeaders();
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.build();
given(this.exchange.getResponse().statusCode()).willReturn(HttpStatus.BAD_REQUEST);
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
verify(this.authorizationFailureHandler, never()).onAuthorizationFailure(any(), any(), any());
}
@Test
public void filterWhenPasswordClientNotAuthorizedThenGetNewToken() {
setupMocks();
TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
ClientRegistration registration = TestClientRegistrations.password().build();
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
given(this.passwordTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId())))
.willReturn(Mono.just(registration));
given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()),
eq(authentication), any())).willReturn(Mono.empty());
// Set custom contextAttributesMapper capable of mapping the form parameters
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
return Mono.just(serverWebExchange).flatMap(ServerWebExchange::getFormData).map((formData) -> {
Map<String, Object> contextAttributes = new HashMap<>();
String username = formData.getFirst(OAuth2ParameterNames.USERNAME);
String password = formData.getFirst(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
});
});
this.serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/")
.contentType(MediaType.APPLICATION_FORM_URLENCODED).body("username=username&password=password"))
.build();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(registration.getRegistrationId()))
.build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.contextWrite(serverWebExchange()).block();
verify(this.passwordTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(authentication), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenClientRegistrationIdThenAuthorizedClientResolved() {
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.just(authorizedClient));
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(this.registration.getRegistrationId()))
.build();
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenDefaultClientRegistrationIdThenAuthorizedClientResolved() {
this.function.setDefaultClientRegistrationId(this.registration.getRegistrationId());
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.just(authorizedClient));
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).contextWrite(serverWebExchange()).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClientResolved() {
this.function.setDefaultOAuth2AuthorizedClient(true);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.just(authorizedClient));
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(),
"client-id");
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.contextWrite(serverWebExchange()).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"),
Collections.singletonMap("user", "rob"), "user");
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(),
"client-id");
// @formatter:off
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
.block();
// @formatter:on
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
verifyNoMoreInteractions(this.clientRegistrationRepository, this.authorizedClientRepository);
}
@Test
public void filterWhenClientRegistrationIdAndServerWebExchangeFromContextThenServerWebExchangeFromContext() {
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any()))
.willReturn(Mono.just(authorizedClient));
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(this.registration.getRegistrationId()))
.build();
this.function.filter(request, this.exchange)
.contextWrite(serverWebExchange())
.block();
// @formatter:on
verify(this.authorizedClientRepository).loadAuthorizedClient(eq(this.registration.getRegistrationId()), any(),
eq(this.serverWebExchange));
}
// gh-7544
@Test
public void filterWhenClientCredentialsClientNotAuthorizedAndOutsideRequestContextThenGetNewToken() {
setupMockHeaders();
ReactiveOAuth2AuthorizedClientService authorizedClientServiceDelegate = new InMemoryReactiveOAuth2AuthorizedClientService(
this.clientRegistrationRepository);
ReactiveOAuth2AuthorizedClientService authorizedClientService = new ReactiveOAuth2AuthorizedClientService() {
@Override
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
String principalName) {
return authorizedClientServiceDelegate.loadAuthorizedClient(clientRegistrationId, principalName);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
return authorizedClientServiceDelegate.saveAuthorizedClient(authorizedClient, principal);
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, String principalName) {
return authorizedClientServiceDelegate.removeAuthorizedClient(clientRegistrationId, principalName);
}
};
authorizedClientService = spy(authorizedClientService);
AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager authorizedClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, authorizedClientService);
ClientCredentialsReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = new ClientCredentialsReactiveOAuth2AuthorizedClientProvider();
authorizedClientProvider.setAccessTokenResponseClient(this.clientCredentialsTokenResponseClient);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.function = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
given(this.clientCredentialsTokenResponseClient.getTokenResponse(any()))
.willReturn(Mono.just(accessTokenResponse));
ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId())))
.willReturn(Mono.just(registration));
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId()))
.build();
// @formatter:on
this.function.filter(request, this.exchange).block();
verify(authorizedClientService).loadAuthorizedClient(any(), any());
verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
verify(authorizedClientService).saveAuthorizedClient(any(), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
private Context serverWebExchange() {
return Context.of(ServerWebExchange.class, this.serverWebExchange);
}
private static String getBody(ClientRequest request) {
final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
messageWriters.add(new ResourceHttpMessageWriter());
Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
messageWriters.add(new ServerSentEventHttpMessageWriter(jsonEncoder));
messageWriters.add(new FormHttpMessageWriter());
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
messageWriters.add(new MultipartHttpMessageWriter(messageWriters));
BodyInserter.Context context = new BodyInserter.Context() {
@Override
public List<HttpMessageWriter<?>> messageWriters() {
return messageWriters;
}
@Override
public Optional<ServerHttpRequest> serverRequest() {
return Optional.empty();
}
@Override
public Map<String, Object> hints() {
return new HashMap<>();
}
};
MockClientHttpRequest body = new MockClientHttpRequest(HttpMethod.GET, "/");
request.body().insert(body, context).block();
return body.getBodyAsString().block();
}
}
| 51,883 | 54.254526 | 154 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunctionITests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.reactive.function.client;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashSet;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.oauth2.client.InMemoryReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.server.AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Phil Clay
*/
public class ServerOAuth2AuthorizedClientExchangeFilterFunctionITests {
private ReactiveClientRegistrationRepository clientRegistrationRepository;
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ServerOAuth2AuthorizedClientExchangeFilterFunction authorizedClientFilter;
private MockWebServer server;
private String serverUrl;
private WebClient webClient;
private Authentication authentication;
private MockServerWebExchange exchange;
@BeforeEach
public void setUp() throws Exception {
this.clientRegistrationRepository = mock(ReactiveClientRegistrationRepository.class);
final ServerOAuth2AuthorizedClientRepository delegate = new AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(
new InMemoryReactiveOAuth2AuthorizedClientService(this.clientRegistrationRepository));
this.authorizedClientRepository = spy(new ServerOAuth2AuthorizedClientRepository() {
@Override
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
return delegate.loadAuthorizedClient(clientRegistrationId, principal, exchange);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
return delegate.saveAuthorizedClient(authorizedClient, principal, exchange);
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
return delegate.removeAuthorizedClient(clientRegistrationId, principal, exchange);
}
});
this.authorizedClientFilter = new ServerOAuth2AuthorizedClientExchangeFilterFunction(
this.clientRegistrationRepository, this.authorizedClientRepository);
this.server = new MockWebServer();
this.server.start();
this.serverUrl = this.server.url("/").toString();
// @formatter:off
this.webClient = WebClient.builder()
.filter(this.authorizedClientFilter)
.build();
// @formatter:on
this.authentication = new TestingAuthenticationToken("principal", "password");
this.exchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/").build()).build();
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void requestWhenNotAuthorizedThenAuthorizeAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl)
.build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId())))
.willReturn(Mono.just(clientRegistration));
// @formatter:off
this.webClient.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
.contextWrite(Context.of(ServerWebExchange.class, this.exchange))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication))
.block();
// @formatter:on
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.exchange));
assertThat(authorizedClientCaptor.getValue().getClientRegistration()).isSameAs(clientRegistration);
}
@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"refreshed-access-token\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl)
.build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId())))
.willReturn(Mono.just(clientRegistration));
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
this.authentication.getName(), accessToken, refreshToken);
doReturn(Mono.just(authorizedClient)).when(this.authorizedClientRepository).loadAuthorizedClient(
eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.exchange));
this.webClient.get().uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration.getRegistrationId()))
.retrieve().bodyToMono(String.class).contextWrite(Context.of(ServerWebExchange.class, this.exchange))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.exchange));
OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
@Test
public void requestMultipleWhenNoneAuthorizedThenAuthorizeAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
// Client 1
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration1 = TestClientRegistrations.clientCredentials().registrationId("client-1")
.tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId())))
.willReturn(Mono.just(clientRegistration1));
// Client 2
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration2 = TestClientRegistrations.clientCredentials().registrationId("client-2")
.tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId())))
.willReturn(Mono.just(clientRegistration2));
// @formatter:off
this.webClient.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration1.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
.flatMap((response) -> this.webClient.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration2.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
)
.contextWrite(Context.of(ServerWebExchange.class, this.exchange))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication))
.block();
// @formatter:on
assertThat(this.server.getRequestCount()).isEqualTo(4);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository, times(2)).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.exchange));
assertThat(authorizedClientCaptor.getAllValues().get(0).getClientRegistration()).isSameAs(clientRegistration1);
assertThat(authorizedClientCaptor.getAllValues().get(1).getClientRegistration()).isSameAs(clientRegistration2);
}
/**
* When a non-expired {@link OAuth2AuthorizedClient} exists but the resource server
* returns 401, then remove the {@link OAuth2AuthorizedClient} from the repository.
*/
@Test
public void requestWhenUnauthorizedThenReAuthorize() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(new MockResponse().setResponseCode(HttpStatus.UNAUTHORIZED.value()));
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl)
.build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId())))
.willReturn(Mono.just(clientRegistration));
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.scopes("read", "write");
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
this.authentication.getName(), accessToken, refreshToken);
doReturn(Mono.just(authorizedClient)).doReturn(Mono.empty()).when(this.authorizedClientRepository)
.loadAuthorizedClient(eq(clientRegistration.getRegistrationId()), eq(this.authentication),
eq(this.exchange));
// @formatter:off
Mono<String> requestMono = this.webClient.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
.contextWrite(Context.of(ServerWebExchange.class, this.exchange))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication));
// @formatter:on
// first try should fail, and remove the cached authorized client
// @formatter:off
assertThatExceptionOfType(WebClientResponseException.class)
.isThrownBy(requestMono::block)
.satisfies((ex) -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
// @formatter:on
assertThat(this.server.getRequestCount()).isEqualTo(1);
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), any(), any());
verify(this.authorizedClientRepository).removeAuthorizedClient(eq(clientRegistration.getRegistrationId()),
eq(this.authentication), eq(this.exchange));
// second try should retrieve the authorized client and succeed
requestMono.block();
assertThat(this.server.getRequestCount()).isEqualTo(3);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.exchange));
assertThat(authorizedClientCaptor.getValue().getClientRegistration()).isSameAs(clientRegistration);
}
private MockResponse jsonResponse(String json) {
// @formatter:off
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(json);
// @formatter:on
}
}
| 16,029 | 46.147059 | 123 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionITests.java | /*
* Copyright 2002-2019 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
*
* https://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.reactive.function.client;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import reactor.util.context.Context;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.InMemoryOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.AuthenticatedPrincipalOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.TestOAuth2RefreshTokens;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.function.client.WebClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author Joe Grandja
*/
public class ServletOAuth2AuthorizedClientExchangeFilterFunctionITests {
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private ServletOAuth2AuthorizedClientExchangeFilterFunction authorizedClientFilter;
private MockWebServer server;
private String serverUrl;
private WebClient webClient;
private Authentication authentication;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setUp() throws Exception {
this.clientRegistrationRepository = mock(ClientRegistrationRepository.class);
final OAuth2AuthorizedClientRepository delegate = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
new InMemoryOAuth2AuthorizedClientService(this.clientRegistrationRepository));
this.authorizedClientRepository = spy(new OAuth2AuthorizedClientRepository() {
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
return delegate.loadAuthorizedClient(clientRegistrationId, principal, request);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
delegate.saveAuthorizedClient(authorizedClient, principal, request, response);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
delegate.removeAuthorizedClient(clientRegistrationId, principal, request, response);
}
});
this.authorizedClientFilter = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
this.clientRegistrationRepository, this.authorizedClientRepository);
this.server = new MockWebServer();
this.server.start();
this.serverUrl = this.server.url("/").toString();
this.webClient = WebClient.builder().apply(this.authorizedClientFilter.oauth2Configuration()).build();
this.authentication = new TestingAuthenticationToken("principal", "password");
SecurityContextHolder.getContext().setAuthentication(this.authentication);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request, this.response));
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
SecurityContextHolder.clearContext();
RequestContextHolder.resetRequestAttributes();
}
@Test
public void requestWhenNotAuthorizedThenAuthorizeAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientCredentials().tokenUri(this.serverUrl)
.build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId())))
.willReturn(clientRegistration);
this.webClient.get().uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration.getRegistrationId()))
.retrieve().bodyToMono(String.class).block();
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.request), eq(this.response));
assertThat(authorizedClientCaptor.getValue().getClientRegistration()).isSameAs(clientRegistration);
}
@Test
public void requestWhenAuthorizedButExpiredThenRefreshAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"refreshed-access-token\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().tokenUri(this.serverUrl)
.build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration.getRegistrationId())))
.willReturn(clientRegistration);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant expiresAt = issuedAt.plus(Duration.ofHours(1));
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"expired-access-token", issuedAt, expiresAt, new HashSet<>(Arrays.asList("read", "write")));
OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(clientRegistration,
this.authentication.getName(), accessToken, refreshToken);
doReturn(authorizedClient).when(this.authorizedClientRepository).loadAuthorizedClient(
eq(clientRegistration.getRegistrationId()), eq(this.authentication), eq(this.request));
this.webClient.get().uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(clientRegistration.getRegistrationId()))
.retrieve().bodyToMono(String.class).block();
assertThat(this.server.getRequestCount()).isEqualTo(2);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.request), eq(this.response));
OAuth2AuthorizedClient refreshedAuthorizedClient = authorizedClientCaptor.getValue();
assertThat(refreshedAuthorizedClient.getClientRegistration()).isSameAs(clientRegistration);
assertThat(refreshedAuthorizedClient.getAccessToken().getTokenValue()).isEqualTo("refreshed-access-token");
}
@Test
public void requestMultipleWhenNoneAuthorizedThenAuthorizeAndSendRequest() {
// @formatter:off
String accessTokenResponse = "{\n"
+ " \"access_token\": \"access-token-1234\",\n"
+ " \"token_type\": \"bearer\",\n"
+ " \"expires_in\": \"3600\",\n"
+ " \"scope\": \"read write\"\n"
+ "}\n";
String clientResponse = "{\n"
+ " \"attribute1\": \"value1\",\n"
+ " \"attribute2\": \"value2\"\n"
+ "}\n";
// @formatter:on
// Client 1
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration1 = TestClientRegistrations.clientCredentials().registrationId("client-1")
.tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration1.getRegistrationId())))
.willReturn(clientRegistration1);
// Client 2
this.server.enqueue(jsonResponse(accessTokenResponse));
this.server.enqueue(jsonResponse(clientResponse));
ClientRegistration clientRegistration2 = TestClientRegistrations.clientCredentials().registrationId("client-2")
.tokenUri(this.serverUrl).build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(clientRegistration2.getRegistrationId())))
.willReturn(clientRegistration2);
// @formatter:off
this.webClient.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration1.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
.flatMap((response) -> this.webClient
.get()
.uri(this.serverUrl)
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(clientRegistration2.getRegistrationId()))
.retrieve()
.bodyToMono(String.class)
)
.contextWrite(context())
.block();
// @formatter:on
assertThat(this.server.getRequestCount()).isEqualTo(4);
ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor = ArgumentCaptor
.forClass(OAuth2AuthorizedClient.class);
verify(this.authorizedClientRepository, times(2)).saveAuthorizedClient(authorizedClientCaptor.capture(),
eq(this.authentication), eq(this.request), eq(this.response));
assertThat(authorizedClientCaptor.getAllValues().get(0).getClientRegistration()).isSameAs(clientRegistration1);
assertThat(authorizedClientCaptor.getAllValues().get(1).getClientRegistration()).isSameAs(clientRegistration2);
}
private Context context() {
Map<Object, Object> contextAttributes = new HashMap<>();
contextAttributes.put(HttpServletRequest.class, this.request);
contextAttributes.put(HttpServletResponse.class, this.response);
contextAttributes.put(Authentication.class, this.authentication);
return Context.of(ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY,
contextAttributes);
}
private MockResponse jsonResponse(String json) {
// @formatter:off
return new MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(json);
// @formatter:on
}
}
| 12,762 | 44.910072 | 131 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunctionTests.java | /*
* Copyright 2002-2022 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
*
* https://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.reactive.function.client;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.core.codec.ByteBufferEncoder;
import org.springframework.core.codec.CharSequenceEncoder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.EncoderHttpMessageWriter;
import org.springframework.http.codec.FormHttpMessageWriter;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ResourceHttpMessageWriter;
import org.springframework.http.codec.ServerSentEventHttpMessageWriter;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.codec.multipart.MultipartHttpMessageWriter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.mock.http.client.reactive.MockClientHttpRequest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.JwtBearerOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestOperations;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests {
@Mock
private OAuth2AuthorizedClientRepository authorizedClientRepository;
@Mock
private ClientRegistrationRepository clientRegistrationRepository;
@Mock
private OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient;
@Mock
private OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> refreshTokenTokenResponseClient;
@Mock
private OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient;
@Mock
private OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> jwtBearerTokenResponseClient;
@Mock
private OAuth2AuthorizationFailureHandler authorizationFailureHandler;
@Captor
private ArgumentCaptor<OAuth2AuthorizationException> authorizationExceptionCaptor;
@Captor
private ArgumentCaptor<Authentication> authenticationCaptor;
@Captor
private ArgumentCaptor<Map<String, Object>> attributesCaptor;
@Mock
private WebClient.RequestHeadersSpec<?> spec;
@Captor
private ArgumentCaptor<Consumer<Map<String, Object>>> attrs;
@Captor
private ArgumentCaptor<OAuth2AuthorizedClient> authorizedClientCaptor;
private DefaultOAuth2AuthorizedClientManager authorizedClientManager;
/**
* Used for get the attributes from defaultRequest.
*/
private Map<String, Object> result = new HashMap<>();
private ServletOAuth2AuthorizedClientExchangeFilterFunction function;
private MockExchangeFunction exchange = new MockExchangeFunction();
private Authentication authentication;
private ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
@BeforeEach
public void setup() {
this.authentication = new TestingAuthenticationToken("test", "this");
JwtBearerOAuth2AuthorizedClientProvider jwtBearerAuthorizedClientProvider = new JwtBearerOAuth2AuthorizedClientProvider();
jwtBearerAuthorizedClientProvider.setAccessTokenResponseClient(this.jwtBearerTokenResponseClient);
// @formatter:off
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken(
(configurer) -> configurer.accessTokenResponseClient(this.refreshTokenTokenResponseClient))
.clientCredentials(
(configurer) -> configurer.accessTokenResponseClient(this.clientCredentialsTokenResponseClient))
.password((configurer) -> configurer.accessTokenResponseClient(this.passwordTokenResponseClient))
.provider(jwtBearerAuthorizedClientProvider)
.build();
// @formatter:on
this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository,
this.authorizedClientRepository);
this.authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(this.authorizedClientManager);
}
@AfterEach
public void cleanup() throws Exception {
SecurityContextHolder.clearContext();
RequestContextHolder.resetRequestAttributes();
}
@Test
public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new ServletOAuth2AuthorizedClientExchangeFilterFunction(null));
}
@Test
public void defaultRequestRequestResponseWhenNullRequestContextThenRequestAndResponseNull() {
Map<String, Object> attrs = getDefaultRequestAttributes();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getRequest(attrs)).isNull();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getResponse(attrs)).isNull();
}
@Test
public void defaultRequestRequestResponseWhenRequestContextThenRequestAndResponseSet() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, response));
Map<String, Object> attrs = getDefaultRequestAttributes();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getRequest(attrs)).isEqualTo(request);
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getResponse(attrs)).isEqualTo(response);
}
@Test
public void defaultRequestAuthenticationWhenSecurityContextEmptyThenAuthenticationNull() {
Map<String, Object> attrs = getDefaultRequestAttributes();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication(attrs)).isNull();
}
@Test
public void defaultRequestAuthenticationWhenAuthenticationSetThenAuthenticationSet() {
SecurityContextHolder.getContext().setAuthentication(this.authentication);
Map<String, Object> attrs = getDefaultRequestAttributes();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication(attrs))
.isEqualTo(this.authentication);
verifyNoInteractions(this.authorizedClientRepository);
}
@Test
public void defaultRequestAuthenticationWhenCustomSecurityContextHolderStrategyThenAuthenticationSet() {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(this.authentication));
this.function.setSecurityContextHolderStrategy(strategy);
Map<String, Object> attrs = getDefaultRequestAttributes();
assertThat(ServletOAuth2AuthorizedClientExchangeFilterFunction.getAuthentication(attrs))
.isEqualTo(this.authentication);
verify(strategy).getContext();
verifyNoInteractions(this.authorizedClientRepository);
}
private Map<String, Object> getDefaultRequestAttributes() {
this.function.defaultRequest().accept(this.spec);
verify(this.spec).attributes(this.attrs.capture());
this.attrs.getValue().accept(this.result);
return this.result;
}
@Test
public void filterWhenAuthorizedClientNullThenAuthorizationHeaderNull() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthorizedClientThenAuthorizationHeader() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
@Test
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing")
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}
@Test
public void filterWhenRefreshRequiredThenRefresh() {
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(response);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(),
eq(this.authentication), any(), any());
OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken()).isEqualTo(response.getRefreshToken());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600)
// .refreshToken(xxx) // No refreshToken in response
.build();
RestOperations refreshTokenClient = mock(RestOperations.class);
given(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class)))
.willReturn(new ResponseEntity(response, HttpStatus.OK));
DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
refreshTokenTokenResponseClient.setRestOperations(refreshTokenClient);
RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
authorizedClientProvider.setAccessTokenResponseClient(refreshTokenTokenResponseClient);
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
verify(refreshTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(),
eq(this.authentication), any(), any());
OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken() {
this.registration = TestClientRegistrations.clientCredentials().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, null);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), eq(this.authentication), any(),
any());
verify(this.clientCredentialsTokenResponseClient, never()).getTokenResponse(any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() {
this.registration = TestClientRegistrations.clientCredentials().build();
OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, null);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(this.authentication), any(), any());
verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenPasswordClientNotAuthorizedThenGetNewToken() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
given(this.passwordTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
ClientRegistration registration = TestClientRegistrations.password().build();
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId())))
.willReturn(registration);
// Set custom contextAttributesMapper
this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
Map<String, Object> contextAttributes = new HashMap<>();
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
});
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.setParameter(OAuth2ParameterNames.USERNAME, "username");
servletRequest.setParameter(OAuth2ParameterNames.PASSWORD, "password");
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(registration.getRegistrationId()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
this.function.filter(request, this.exchange).block();
verify(this.passwordTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(this.authentication), any(), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
// @formatter:off
ClientRegistration registration = ClientRegistration.withRegistrationId("jwt-bearer")
.clientId("client-id")
.clientSecret("client-secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.JWT_BEARER)
.scope("read", "write")
.tokenUri("https://example.com/oauth/token")
.build();
// @formatter:on
given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId())))
.willReturn(registration);
Jwt jwtAssertion = TestJwts.jwt().build();
Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.clientRegistrationId(registration.getRegistrationId()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(jwtAuthentication))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
this.function.filter(request, this.exchange).block();
verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), any(), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer exchanged-token");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
@Test
public void filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved() {
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(response);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(),
issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(), any(), any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenRefreshTokenNullThenShouldRefreshFalse() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
@Test
public void filterWhenNotExpiredThenShouldRefreshFalse() {
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletRequest(new MockHttpServletRequest()))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction
.httpServletResponse(new MockHttpServletResponse()))
.build();
this.function.filter(request, this.exchange).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
// gh-6483
@Test
public void filterWhenChainedThenDefaultsStillAvailable() throws Exception {
this.function.setDefaultOAuth2AuthorizedClient(true);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
OAuth2User user = mock(OAuth2User.class);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, authorities,
this.registration.getRegistrationId());
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
given(this.authorizedClientRepository.loadAuthorizedClient(
eq(authentication.getAuthorizedClientRegistrationId()), eq(authentication), eq(servletRequest)))
.willReturn(authorizedClient);
// Default request attributes set
final ClientRequest request1 = ClientRequest.create(HttpMethod.GET, URI.create("https://example1.com"))
.attributes((attrs) -> attrs.putAll(getDefaultRequestAttributes())).build();
// Default request attributes NOT set
final ClientRequest request2 = ClientRequest.create(HttpMethod.GET, URI.create("https://example2.com")).build();
Context context = context(servletRequest, servletResponse, authentication);
this.function.filter(request1, this.exchange)
.flatMap((response) -> this.function.filter(request2, this.exchange)).contextWrite(context).block();
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(2);
ClientRequest request = requests.get(0);
assertThat(request.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request.url().toASCIIString()).isEqualTo("https://example1.com");
assertThat(request.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request)).isEmpty();
request = requests.get(1);
assertThat(request.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request.url().toASCIIString()).isEqualTo("https://example2.com");
assertThat(request.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request)).isEmpty();
}
@Test
public void filterWhenUnauthorizedThenInvokeFailureHandler() {
assertHttpStatusInvokesFailureHandler(HttpStatus.UNAUTHORIZED, OAuth2ErrorCodes.INVALID_TOKEN);
}
@Test
public void filterWhenForbiddenThenInvokeFailureHandler() {
assertHttpStatusInvokesFailureHandler(HttpStatus.FORBIDDEN, OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
}
private void assertHttpStatusInvokesFailureHandler(HttpStatus httpStatus, String expectedErrorCode) {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
given(this.exchange.getResponse().statusCode()).willReturn(httpStatus);
given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class));
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(expectedErrorCode);
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(expectedErrorCode);
});
assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
assertThat(this.attributesCaptor.getValue()).containsExactly(
entry(HttpServletRequest.class.getName(), servletRequest),
entry(HttpServletResponse.class.getName(), servletResponse));
}
@Test
public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", "
+ "error_description=\"The request requires higher privileges than provided by the access token.\", "
+ "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE)))
.willReturn(Collections.singletonList(wwwAuthenticateHeader));
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
assertThat(ex.getError().getDescription())
.isEqualTo("The request requires higher privileges than provided by the access token.");
assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
});
assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
assertThat(this.attributesCaptor.getValue()).containsExactly(
entry(HttpServletRequest.class.getName(), servletRequest),
entry(HttpServletResponse.class.getName(), servletResponse));
}
@Test
public void filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler() {
assertHttpStatusWithWebClientExceptionInvokesFailureHandler(HttpStatus.UNAUTHORIZED,
OAuth2ErrorCodes.INVALID_TOKEN);
}
@Test
public void filterWhenForbiddenWithWebClientExceptionThenInvokeFailureHandler() {
assertHttpStatusWithWebClientExceptionInvokesFailureHandler(HttpStatus.FORBIDDEN,
OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
}
private void assertHttpStatusWithWebClientExceptionInvokesFailureHandler(HttpStatus httpStatus,
String expectedErrorCode) {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
WebClientResponseException exception = WebClientResponseException.create(httpStatus.value(),
httpStatus.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
assertThatExceptionOfType(WebClientResponseException.class)
.isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(exception);
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(expectedErrorCode);
assertThat(ex).hasCause(exception);
assertThat(ex).hasMessageContaining(expectedErrorCode);
});
assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
assertThat(this.attributesCaptor.getValue()).containsExactly(
entry(HttpServletRequest.class.getName(), servletRequest),
entry(HttpServletResponse.class.getName(), servletResponse));
}
@Test
public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
OAuth2AuthorizationException authorizationException = new OAuth2AuthorizationException(
new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN));
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(authorizationException);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block())
.isEqualTo(authorizationException);
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(),
this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue())
.isInstanceOfSatisfying(OAuth2AuthorizationException.class, (ex) -> {
assertThat(ex.getError().getErrorCode())
.isEqualTo(authorizationException.getError().getErrorCode());
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INVALID_TOKEN);
});
assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
assertThat(this.attributesCaptor.getValue()).containsExactly(
entry(HttpServletRequest.class.getName(), servletRequest),
entry(HttpServletResponse.class.getName(), servletResponse));
}
@Test
public void filterWhenOtherHttpStatusThenDoesNotInvokeFailureHandler() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName",
this.accessToken);
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.attributes(
ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest))
.attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse))
.build();
given(this.exchange.getResponse().statusCode()).willReturn(HttpStatus.BAD_REQUEST);
given(this.exchange.getResponse().headers()).willReturn(mock(ClientResponse.Headers.class));
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
verifyNoInteractions(this.authorizationFailureHandler);
}
private Context context(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
Authentication authentication) {
Map<Object, Object> contextAttributes = new HashMap<>();
contextAttributes.put(HttpServletRequest.class, servletRequest);
contextAttributes.put(HttpServletResponse.class, servletResponse);
contextAttributes.put(Authentication.class, authentication);
return Context.of(ServletOAuth2AuthorizedClientExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY,
contextAttributes);
}
private static String getBody(ClientRequest request) {
final List<HttpMessageWriter<?>> messageWriters = new ArrayList<>();
messageWriters.add(new EncoderHttpMessageWriter<>(new ByteBufferEncoder()));
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.textPlainOnly()));
messageWriters.add(new ResourceHttpMessageWriter());
Jackson2JsonEncoder jsonEncoder = new Jackson2JsonEncoder();
messageWriters.add(new EncoderHttpMessageWriter<>(jsonEncoder));
messageWriters.add(new ServerSentEventHttpMessageWriter(jsonEncoder));
messageWriters.add(new FormHttpMessageWriter());
messageWriters.add(new EncoderHttpMessageWriter<>(CharSequenceEncoder.allMimeTypes()));
messageWriters.add(new MultipartHttpMessageWriter(messageWriters));
BodyInserter.Context context = new BodyInserter.Context() {
@Override
public List<HttpMessageWriter<?>> messageWriters() {
return messageWriters;
}
@Override
public Optional<ServerHttpRequest> serverRequest() {
return Optional.empty();
}
@Override
public Map<String, Object> hints() {
return new HashMap<>();
}
};
MockClientHttpRequest body = new MockClientHttpRequest(HttpMethod.GET, "/");
request.body().insert(body, context).block();
return body.getBodyAsString().block();
}
}
| 49,511 | 55.3918 | 124 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/function/client/MockExchangeFunction.java | /*
* 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
*
* https://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.reactive.function.client;
import java.util.ArrayList;
import java.util.List;
import reactor.core.publisher.Mono;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
* @since 5.1
*/
public class MockExchangeFunction implements ExchangeFunction {
private List<ClientRequest> requests = new ArrayList<>();
private ClientResponse response = mock(ClientResponse.class);
public ClientRequest getRequest() {
return this.requests.get(this.requests.size() - 1);
}
public List<ClientRequest> getRequests() {
return this.requests;
}
public ClientResponse getResponse() {
return this.response;
}
@Override
public Mono<ClientResponse> exchange(ClientRequest request) {
return Mono.defer(() -> {
this.requests.add(request);
return Mono.just(this.response);
});
}
}
| 1,700 | 26.885246 | 80 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java | /*
* Copyright 2002-2019 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
*
* https://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.reactive.result.method.annotation;
import java.lang.reflect.Method;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
import org.springframework.core.MethodParameter;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class OAuth2AuthorizedClientArgumentResolverTests {
@Mock
private ReactiveClientRegistrationRepository clientRegistrationRepository;
@Mock
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ServerWebExchange serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.get("/")).build();
private OAuth2AuthorizedClientArgumentResolver argumentResolver;
private ClientRegistration clientRegistration;
private OAuth2AuthorizedClient authorizedClient;
private Authentication authentication = new TestingAuthenticationToken("test", "this");
@BeforeEach
public void setUp() {
// @formatter:off
ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = ReactiveOAuth2AuthorizedClientProviderBuilder
.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.build();
// @formatter:on
DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
this.clientRegistration = TestClientRegistrations.clientRegistration().build();
this.authorizedClient = new OAuth2AuthorizedClient(this.clientRegistration, this.authentication.getName(),
TestOAuth2AccessTokens.noScopes());
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository));
}
@Test
public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null));
}
@Test
public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null));
}
@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 supportsParameterWhenParameterTypeUnsupportedWithoutAnnotationThenFalse() {
MethodParameter methodParameter = this.getMethodParameter("paramTypeUnsupportedWithoutAnnotation",
String.class);
assertThat(this.argumentResolver.supportsParameter(methodParameter)).isFalse();
}
@Test
public void resolveArgumentWhenRegistrationIdEmptyAndNotOAuth2AuthenticationThenThrowIllegalArgumentException() {
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
assertThatIllegalArgumentException().isThrownBy(() -> resolveArgument(methodParameter))
.withMessage("The clientRegistrationId could not be resolved. Please provide one");
}
@Test
public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() {
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any()))
.willReturn(Mono.just(this.authorizedClient));
this.authentication = mock(OAuth2AuthenticationToken.class);
given(((OAuth2AuthenticationToken) this.authentication).getAuthorizedClientRegistrationId())
.willReturn("client1");
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
resolveArgument(methodParameter);
}
@Test
public void resolveArgumentWhenParameterTypeOAuth2AuthorizedClientAndCurrentAuthenticationNullThenResolves() {
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any()))
.willReturn(Mono.just(this.authorizedClient));
this.authentication = null;
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThat(resolveArgument(methodParameter)).isSameAs(this.authorizedClient);
}
@Test
public void resolveArgumentWhenOAuth2AuthorizedClientFoundThenResolves() {
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any()))
.willReturn(Mono.just(this.authorizedClient));
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any()))
.willReturn(Mono.just(this.authorizedClient));
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThat(resolveArgument(methodParameter)).isSameAs(this.authorizedClient);
}
@Test
public void resolveArgumentWhenOAuth2AuthorizedClientNotFoundThenThrowClientAuthorizationRequiredException() {
given(this.clientRegistrationRepository.findByRegistrationId(any()))
.willReturn(Mono.just(this.clientRegistration));
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())).willReturn(Mono.empty());
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class)
.isThrownBy(() -> resolveArgument(methodParameter));
}
private Object resolveArgument(MethodParameter methodParameter) {
return this.argumentResolver.resolveArgument(methodParameter, null, null)
.contextWrite((this.authentication != null)
? ReactiveSecurityContextHolder.withAuthentication(this.authentication) : Context.empty())
.contextWrite(serverWebExchange()).block();
}
private Context serverWebExchange() {
return Context.of(ServerWebExchange.class, this.serverWebExchange);
}
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes);
return new MethodParameter(method, 0);
}
static class TestController {
void paramTypeAuthorizedClient(
@RegisteredOAuth2AuthorizedClient("client1") OAuth2AuthorizedClient authorizedClient) {
}
void paramTypeAuthorizedClientWithoutAnnotation(OAuth2AuthorizedClient authorizedClient) {
}
void paramTypeUnsupported(@RegisteredOAuth2AuthorizedClient("client1") String param) {
}
void paramTypeUnsupportedWithoutAnnotation(String param) {
}
void registrationIdEmpty(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
}
}
}
| 10,157 | 44.146667 | 122 | java |
null | spring-security-main/oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolverTests.java | /*
* Copyright 2002-2022 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
*
* https://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 java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.PasswordOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.ServletWebRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link OAuth2AuthorizedClientArgumentResolver}.
*
* @author Joe Grandja
*/
public class OAuth2AuthorizedClientArgumentResolverTests {
private TestingAuthenticationToken authentication;
private String principalName = "principal-1";
private ClientRegistration registration1;
private ClientRegistration registration2;
private ClientRegistration registration3;
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClient authorizedClient1;
private OAuth2AuthorizedClient authorizedClient2;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private OAuth2AuthorizedClientArgumentResolver argumentResolver;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setup() {
this.authentication = new TestingAuthenticationToken(this.principalName, "password");
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(this.authentication);
SecurityContextHolder.setContext(securityContext);
// @formatter:off
this.registration1 = ClientRegistration.withRegistrationId("client1")
.clientId("client-1")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("user")
.authorizationUri("https://provider.com/oauth2/authorize")
.tokenUri("https://provider.com/oauth2/token")
.userInfoUri("https://provider.com/oauth2/user")
.userNameAttributeName("id")
.clientName("client-1")
.build();
this.registration2 = ClientRegistration.withRegistrationId("client2")
.clientId("client-2")
.clientSecret("secret")
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.scope("read", "write")
.tokenUri("https://provider.com/oauth2/token")
.build();
this.registration3 = TestClientRegistrations.password()
.registrationId("client3")
.build();
// @formatter:on
this.clientRegistrationRepository = new InMemoryClientRegistrationRepository(this.registration1,
this.registration2, this.registration3);
this.authorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class);
OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode().refreshToken().clientCredentials().build();
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
this.authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName,
mock(OAuth2AccessToken.class));
given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration1.getRegistrationId()),
any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient1);
this.authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName,
mock(OAuth2AccessToken.class));
given(this.authorizedClientRepository.loadAuthorizedClient(eq(this.registration2.getRegistrationId()),
any(Authentication.class), any(HttpServletRequest.class))).willReturn(this.authorizedClient2);
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void constructorWhenClientRegistrationRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null, this.authorizedClientRepository));
}
@Test
public void constructorWhenOAuth2AuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(this.clientRegistrationRepository, null));
}
@Test
public void constructorWhenAuthorizedClientManagerIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new OAuth2AuthorizedClientArgumentResolver(null));
}
@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 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() {
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null, null, null))
.withMessage("Unable to resolve the Client Registration Identifier. It must be provided via "
+ "@RegisteredOAuth2AuthorizedClient(\"client1\") or "
+ "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\").");
}
@Test
public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception {
OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class);
given(authentication.getAuthorizedClientRegistrationId()).willReturn("client1");
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(authentication);
SecurityContextHolder.setContext(securityContext);
MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
assertThat(this.argumentResolver.resolveArgument(methodParameter, null,
new ServletWebRequest(this.request, this.response), null)).isSameAs(this.authorizedClient1);
}
@Test
public void resolveArgumentWhenAuthorizedClientFoundThenResolves() throws Exception {
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThat(this.argumentResolver.resolveArgument(methodParameter, null,
new ServletWebRequest(this.request, this.response), null)).isSameAs(this.authorizedClient1);
}
@Test
public void resolveArgumentWhenCustomSecurityContextHolderStrategyThenUses() throws Exception {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(this.authentication));
this.argumentResolver.setSecurityContextHolderStrategy(strategy);
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThat(this.argumentResolver.resolveArgument(methodParameter, null,
new ServletWebRequest(this.request, this.response), null)).isSameAs(this.authorizedClient1);
verify(strategy, atLeastOnce()).getContext();
}
@Test
public void resolveArgumentWhenRegistrationIdInvalidThenThrowIllegalArgumentException() {
MethodParameter methodParameter = this.getMethodParameter("registrationIdInvalid",
OAuth2AuthorizedClient.class);
assertThatIllegalArgumentException()
.isThrownBy(() -> this.argumentResolver.resolveArgument(methodParameter, null,
new ServletWebRequest(this.request, this.response), null))
.withMessage("Could not find ClientRegistration with id 'invalid'");
}
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForAuthorizationCodeClientThenThrowClientAuthorizationRequiredException() {
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class)))
.willReturn(null);
MethodParameter methodParameter = this.getMethodParameter("paramTypeAuthorizedClient",
OAuth2AuthorizedClient.class);
assertThatExceptionOfType(ClientAuthorizationRequiredException.class).isThrownBy(() -> this.argumentResolver
.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null));
}
@SuppressWarnings("unchecked")
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForClientCredentialsClientThenResolvesFromTokenResponseClient()
throws Exception {
OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> clientCredentialsTokenResponseClient = mock(
OAuth2AccessTokenResponseClient.class);
ClientCredentialsOAuth2AuthorizedClientProvider clientCredentialsAuthorizedClientProvider = new ClientCredentialsOAuth2AuthorizedClientProvider();
clientCredentialsAuthorizedClientProvider.setAccessTokenResponseClient(clientCredentialsTokenResponseClient);
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(clientCredentialsAuthorizedClientProvider);
this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
given(clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class)))
.willReturn(null);
MethodParameter methodParameter = this.getMethodParameter("clientCredentialsClient",
OAuth2AuthorizedClient.class);
OAuth2AuthorizedClient authorizedClient = (OAuth2AuthorizedClient) this.argumentResolver
.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.registration2);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
assertThat(authorizedClient.getAccessToken()).isSameAs(accessTokenResponse.getAccessToken());
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(authorizedClient), eq(this.authentication),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
@SuppressWarnings("unchecked")
@Test
public void resolveArgumentWhenAuthorizedClientNotFoundForPasswordClientThenResolvesFromTokenResponseClient()
throws Exception {
OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> passwordTokenResponseClient = mock(
OAuth2AccessTokenResponseClient.class);
PasswordOAuth2AuthorizedClientProvider passwordAuthorizedClientProvider = new PasswordOAuth2AuthorizedClientProvider();
passwordAuthorizedClientProvider.setAccessTokenResponseClient(passwordTokenResponseClient);
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(passwordAuthorizedClientProvider);
// Set custom contextAttributesMapper
authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
Map<String, Object> contextAttributes = new HashMap<>();
HttpServletRequest servletRequest = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
String username = servletRequest.getParameter(OAuth2ParameterNames.USERNAME);
String password = servletRequest.getParameter(OAuth2ParameterNames.PASSWORD);
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
}
return contextAttributes;
});
this.argumentResolver = new OAuth2AuthorizedClientArgumentResolver(authorizedClientManager);
OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("access-token-1234")
.tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
given(passwordTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any(HttpServletRequest.class)))
.willReturn(null);
MethodParameter methodParameter = this.getMethodParameter("passwordClient", OAuth2AuthorizedClient.class);
this.request.setParameter(OAuth2ParameterNames.USERNAME, "username");
this.request.setParameter(OAuth2ParameterNames.PASSWORD, "password");
OAuth2AuthorizedClient authorizedClient = (OAuth2AuthorizedClient) this.argumentResolver
.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null);
assertThat(authorizedClient).isNotNull();
assertThat(authorizedClient.getClientRegistration()).isSameAs(this.registration3);
assertThat(authorizedClient.getPrincipalName()).isEqualTo(this.principalName);
assertThat(authorizedClient.getAccessToken()).isSameAs(accessTokenResponse.getAccessToken());
verify(this.authorizedClientRepository).saveAuthorizedClient(eq(authorizedClient), eq(this.authentication),
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
private MethodParameter getMethodParameter(String methodName, Class<?>... paramTypes) {
Method method = ReflectionUtils.findMethod(TestController.class, methodName, paramTypes);
return new MethodParameter(method, 0);
}
static class TestController {
void paramTypeAuthorizedClient(
@RegisteredOAuth2AuthorizedClient("client1") OAuth2AuthorizedClient authorizedClient) {
}
void paramTypeAuthorizedClientWithoutAnnotation(OAuth2AuthorizedClient authorizedClient) {
}
void paramTypeUnsupported(@RegisteredOAuth2AuthorizedClient("client1") String param) {
}
void paramTypeUnsupportedWithoutAnnotation(String param) {
}
void registrationIdEmpty(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
}
void registrationIdInvalid(
@RegisteredOAuth2AuthorizedClient("invalid") OAuth2AuthorizedClient authorizedClient) {
}
void clientCredentialsClient(
@RegisteredOAuth2AuthorizedClient("client2") OAuth2AuthorizedClient authorizedClient) {
}
void passwordClient(@RegisteredOAuth2AuthorizedClient("client3") OAuth2AuthorizedClient authorizedClient) {
}
}
}
| 19,889 | 51.480211 | 148 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.