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-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequestEntityConverter.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.endpoint;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* An implementation of an {@link AbstractOAuth2AuthorizationGrantRequestEntityConverter}
* that converts the provided {@link OAuth2AuthorizationCodeGrantRequest} to a
* {@link RequestEntity} representation of an OAuth 2.0 Access Token Request for the
* Authorization Code Grant.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractOAuth2AuthorizationGrantRequestEntityConverter
* @see OAuth2AuthorizationCodeGrantRequest
* @see RequestEntity
*/
public class OAuth2AuthorizationCodeGrantRequestEntityConverter
extends AbstractOAuth2AuthorizationGrantRequestEntityConverter<OAuth2AuthorizationCodeGrantRequest> {
@Override
protected MultiValueMap<String, String> createParameters(
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest) {
ClientRegistration clientRegistration = authorizationCodeGrantRequest.getClientRegistration();
OAuth2AuthorizationExchange authorizationExchange = authorizationCodeGrantRequest.getAuthorizationExchange();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, authorizationCodeGrantRequest.getGrantType().getValue());
parameters.add(OAuth2ParameterNames.CODE, authorizationExchange.getAuthorizationResponse().getCode());
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
String codeVerifier = authorizationExchange.getAuthorizationRequest()
.getAttribute(PkceParameterNames.CODE_VERIFIER);
if (redirectUri != null) {
parameters.add(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
}
if (!ClientAuthenticationMethod.CLIENT_SECRET_BASIC
.equals(clientRegistration.getClientAuthenticationMethod())) {
parameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod())) {
parameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
}
if (codeVerifier != null) {
parameters.add(PkceParameterNames.CODE_VERIFIER, codeVerifier);
}
return parameters;
}
}
| 3,364 | 46.394366 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveRefreshTokenTokenResponseClient.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.endpoint;
import java.util.Set;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
/**
* An implementation of a {@link ReactiveOAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#REFRESH_TOKEN refresh_token} grant. This implementation
* uses {@link WebClient} when requesting an access token credential at the Authorization
* Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.2
* @see ReactiveOAuth2AccessTokenResponseClient
* @see OAuth2RefreshTokenGrantRequest
* @see OAuth2AccessTokenResponse
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-6">Section 6
* Refreshing an Access Token</a>
*/
public final class WebClientReactiveRefreshTokenTokenResponseClient
extends AbstractWebClientReactiveOAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> {
@Override
ClientRegistration clientRegistration(OAuth2RefreshTokenGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
@Override
Set<String> scopes(OAuth2RefreshTokenGrantRequest grantRequest) {
return grantRequest.getScopes();
}
@Override
Set<String> defaultScopes(OAuth2RefreshTokenGrantRequest grantRequest) {
return grantRequest.getAccessToken().getScopes();
}
@Override
BodyInserters.FormInserter<String> populateTokenRequestBody(OAuth2RefreshTokenGrantRequest grantRequest,
BodyInserters.FormInserter<String> body) {
return super.populateTokenRequestBody(grantRequest, body).with(OAuth2ParameterNames.REFRESH_TOKEN,
grantRequest.getRefreshToken().getTokenValue());
}
@Override
OAuth2AccessTokenResponse populateTokenResponse(OAuth2RefreshTokenGrantRequest grantRequest,
OAuth2AccessTokenResponse accessTokenResponse) {
if (!CollectionUtils.isEmpty(accessTokenResponse.getAccessToken().getScopes())
&& accessTokenResponse.getRefreshToken() != null) {
return accessTokenResponse;
}
OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse
.withResponse(accessTokenResponse);
if (CollectionUtils.isEmpty(accessTokenResponse.getAccessToken().getScopes())) {
tokenResponseBuilder.scopes(defaultScopes(grantRequest));
}
if (accessTokenResponse.getRefreshToken() == null) {
// Reuse existing refresh token
tokenResponseBuilder.refreshToken(grantRequest.getRefreshToken().getTokenValue());
}
return tokenResponseBuilder.build();
}
}
| 3,513 | 38.931818 | 105 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/ClientAuthenticationMethodValidatingRequestEntityConverter.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.endpoint;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.util.Assert;
class ClientAuthenticationMethodValidatingRequestEntityConverter<T extends AbstractOAuth2AuthorizationGrantRequest>
implements Converter<T, RequestEntity<?>> {
private final Converter<T, RequestEntity<?>> delegate;
ClientAuthenticationMethodValidatingRequestEntityConverter(Converter<T, RequestEntity<?>> delegate) {
this.delegate = delegate;
}
@Override
public RequestEntity<?> convert(T grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
ClientAuthenticationMethod clientAuthenticationMethod = clientRegistration.getClientAuthenticationMethod();
String registrationId = clientRegistration.getRegistrationId();
boolean supportedClientAuthenticationMethod = clientAuthenticationMethod.equals(ClientAuthenticationMethod.NONE)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_POST);
Assert.isTrue(supportedClientAuthenticationMethod, () -> String.format(
"This class supports `client_secret_basic`, `client_secret_post`, and `none` by default. Client [%s] is using [%s] instead. Please use a supported client authentication method, or use `setRequestEntityConverter` to supply an instance that supports [%s].",
registrationId, clientAuthenticationMethod, clientAuthenticationMethod));
return this.delegate.convert(grantRequest);
}
}
| 2,423 | 48.469388 | 259 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractOAuth2AuthorizationGrantRequest.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.endpoint;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.Assert;
/**
* Base implementation of an OAuth 2.0 Authorization Grant request that holds an
* authorization grant credential and is used when initiating a request to the
* Authorization Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see AuthorizationGrantType
* @see ClientRegistration
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section
* 1.3 Authorization Grant</a>
*/
public abstract class AbstractOAuth2AuthorizationGrantRequest {
private final AuthorizationGrantType authorizationGrantType;
private final ClientRegistration clientRegistration;
/**
* Sub-class constructor.
* @param authorizationGrantType the authorization grant type
* @param clientRegistration the client registration
* @since 5.5
*/
protected AbstractOAuth2AuthorizationGrantRequest(AuthorizationGrantType authorizationGrantType,
ClientRegistration clientRegistration) {
Assert.notNull(authorizationGrantType, "authorizationGrantType cannot be null");
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.authorizationGrantType = authorizationGrantType;
this.clientRegistration = clientRegistration;
}
/**
* Returns the authorization grant type.
* @return the authorization grant type
*/
public AuthorizationGrantType getGrantType() {
return this.authorizationGrantType;
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
* @since 5.5
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
}
| 2,478 | 32.958904 | 97 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/JwtBearerGrantRequest.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.endpoint;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.Assert;
/**
* A JWT Bearer Grant request that holds a {@link Jwt} assertion.
*
* @author Joe Grandja
* @since 5.5
* @see AbstractOAuth2AuthorizationGrantRequest
* @see ClientRegistration
* @see Jwt
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7523#section-2.1">Section
* 2.1 Using JWTs as Authorization Grants</a>
*/
public class JwtBearerGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final Jwt jwt;
/**
* Constructs a {@code JwtBearerGrantRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param jwt the JWT assertion
*/
public JwtBearerGrantRequest(ClientRegistration clientRegistration, Jwt jwt) {
super(AuthorizationGrantType.JWT_BEARER, clientRegistration);
Assert.isTrue(AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType()),
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
Assert.notNull(jwt, "jwt cannot be null");
this.jwt = jwt;
}
/**
* Returns the {@link Jwt JWT} assertion.
* @return the {@link Jwt} assertion
*/
public Jwt getJwt() {
return this.jwt;
}
}
| 2,104 | 33.508197 | 105 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveAuthorizationCodeTokenResponseClient.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.endpoint;
import java.util.Collections;
import java.util.Set;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.web.reactive.function.BodyInserters;
/**
* An implementation of a {@link ReactiveOAuth2AccessTokenResponseClient} that
* "exchanges" an authorization code credential for an access token credential
* at the Authorization Server's Token Endpoint.
*
* <p>
* <b>NOTE:</b> This implementation uses the Nimbus OAuth 2.0 SDK internally.
*
* @author Rob Winch
* @since 5.1
* @see ReactiveOAuth2AccessTokenResponseClient
* @see OAuth2AuthorizationCodeGrantRequest
* @see OAuth2AccessTokenResponse
* @see <a target="_blank" href=
* "https://connect2id.com/products/nimbus-oauth-openid-connect-sdk">Nimbus OAuth 2.0
* SDK</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request
* (Authorization Code Grant)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token Response
* (Authorization Code Grant)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7636#section-4.2">Section
* 4.2 Client Creates the Code Challenge</a>
*/
public class WebClientReactiveAuthorizationCodeTokenResponseClient
extends AbstractWebClientReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
@Override
ClientRegistration clientRegistration(OAuth2AuthorizationCodeGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
@Override
Set<String> scopes(OAuth2AuthorizationCodeGrantRequest grantRequest) {
return Collections.emptySet();
}
@Override
BodyInserters.FormInserter<String> populateTokenRequestBody(OAuth2AuthorizationCodeGrantRequest grantRequest,
BodyInserters.FormInserter<String> body) {
super.populateTokenRequestBody(grantRequest, body);
OAuth2AuthorizationExchange authorizationExchange = grantRequest.getAuthorizationExchange();
OAuth2AuthorizationResponse authorizationResponse = authorizationExchange.getAuthorizationResponse();
body.with(OAuth2ParameterNames.CODE, authorizationResponse.getCode());
String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
if (redirectUri != null) {
body.with(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
}
String codeVerifier = authorizationExchange.getAuthorizationRequest()
.getAttribute(PkceParameterNames.CODE_VERIFIER);
if (codeVerifier != null) {
body.with(PkceParameterNames.CODE_VERIFIER, codeVerifier);
}
return body;
}
}
| 3,722 | 41.306818 | 110 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractOAuth2AuthorizationGrantRequestEntityConverter.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.endpoint;
import java.net.URI;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Base implementation of a {@link Converter} that converts the provided
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link RequestEntity}
* representation of an OAuth 2.0 Access Token Request for the Authorization Grant.
*
* @param <T> the type of {@link AbstractOAuth2AuthorizationGrantRequest}
* @author Joe Grandja
* @since 5.5
* @see Converter
* @see AbstractOAuth2AuthorizationGrantRequest
* @see RequestEntity
*/
abstract class AbstractOAuth2AuthorizationGrantRequestEntityConverter<T extends AbstractOAuth2AuthorizationGrantRequest>
implements Converter<T, RequestEntity<?>> {
// @formatter:off
private Converter<T, HttpHeaders> headersConverter =
(authorizationGrantRequest) -> OAuth2AuthorizationGrantRequestEntityUtils
.getTokenRequestHeaders(authorizationGrantRequest.getClientRegistration());
// @formatter:on
private Converter<T, MultiValueMap<String, String>> parametersConverter = this::createParameters;
@Override
public RequestEntity<?> convert(T authorizationGrantRequest) {
HttpHeaders headers = getHeadersConverter().convert(authorizationGrantRequest);
MultiValueMap<String, String> parameters = getParametersConverter().convert(authorizationGrantRequest);
URI uri = UriComponentsBuilder
.fromUriString(authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri())
.build().toUri();
return new RequestEntity<>(parameters, headers, HttpMethod.POST, uri);
}
/**
* Returns a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body.
* @param authorizationGrantRequest the authorization grant request
* @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body
*/
abstract MultiValueMap<String, String> createParameters(T authorizationGrantRequest);
/**
* Returns the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @return the {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to {@link HttpHeaders}
*/
final Converter<T, HttpHeaders> getHeadersConverter() {
return this.headersConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @param headersConverter the {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to {@link HttpHeaders}
*/
public final void setHeadersConverter(Converter<T, HttpHeaders> headersConverter) {
Assert.notNull(headersConverter, "headersConverter cannot be null");
this.headersConverter = headersConverter;
}
/**
* Add (compose) the provided {@code headersConverter} to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @param headersConverter the {@link Converter} to add (compose) to the current
* {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to a {@link HttpHeaders}
*/
public final void addHeadersConverter(Converter<T, HttpHeaders> headersConverter) {
Assert.notNull(headersConverter, "headersConverter cannot be null");
Converter<T, HttpHeaders> currentHeadersConverter = this.headersConverter;
this.headersConverter = (authorizationGrantRequest) -> {
// Append headers using a Composite Converter
HttpHeaders headers = currentHeadersConverter.convert(authorizationGrantRequest);
if (headers == null) {
headers = new HttpHeaders();
}
HttpHeaders headersToAdd = headersConverter.convert(authorizationGrantRequest);
if (headersToAdd != null) {
headers.addAll(headersToAdd);
}
return headers;
};
}
/**
* Returns the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* of the parameters used in the OAuth 2.0 Access Token Request body.
* @return the {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to a {@link MultiValueMap} of the
* parameters
*/
final Converter<T, MultiValueMap<String, String>> getParametersConverter() {
return this.parametersConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* of the parameters used in the OAuth 2.0 Access Token Request body.
* @param parametersConverter the {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to a {@link MultiValueMap} of the
* parameters
*/
public final void setParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
this.parametersConverter = parametersConverter;
}
/**
* Add (compose) the provided {@code parametersConverter} to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* of the parameters used in the OAuth 2.0 Access Token Request body.
* @param parametersConverter the {@link Converter} to add (compose) to the current
* {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to a {@link MultiValueMap} of the
* parameters
*/
public final void addParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
Converter<T, MultiValueMap<String, String>> currentParametersConverter = this.parametersConverter;
this.parametersConverter = (authorizationGrantRequest) -> {
// Append parameters using a Composite Converter
MultiValueMap<String, String> parameters = currentParametersConverter.convert(authorizationGrantRequest);
if (parameters == null) {
parameters = new LinkedMultiValueMap<>();
}
MultiValueMap<String, String> parametersToAdd = parametersConverter.convert(authorizationGrantRequest);
if (parametersToAdd != null) {
parameters.addAll(parametersToAdd);
}
return parameters;
};
}
}
| 7,547 | 42.37931 | 120 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveJwtBearerTokenResponseClient.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.endpoint;
import java.util.Set;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
/**
* The default implementation of an {@link ReactiveOAuth2AccessTokenResponseClient} for
* the {@link AuthorizationGrantType#JWT_BEARER jwt-bearer} grant. This implementation
* uses {@link WebClient} when requesting an access token credential at the Authorization
* Server's Token Endpoint.
*
* @author Steve Riesenberg
* @since 5.6
* @see ReactiveOAuth2AccessTokenResponseClient
* @see JwtBearerGrantRequest
* @see OAuth2AccessToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7523#section-2.1">Section
* 2.1 Using JWTs as Authorization Grants</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7521#section-4.1">Section
* 4.1 Using Assertions as Authorization Grants</a>
*/
public final class WebClientReactiveJwtBearerTokenResponseClient
extends AbstractWebClientReactiveOAuth2AccessTokenResponseClient<JwtBearerGrantRequest> {
@Override
ClientRegistration clientRegistration(JwtBearerGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
@Override
Set<String> scopes(JwtBearerGrantRequest grantRequest) {
return grantRequest.getClientRegistration().getScopes();
}
@Override
BodyInserters.FormInserter<String> populateTokenRequestBody(JwtBearerGrantRequest grantRequest,
BodyInserters.FormInserter<String> body) {
return super.populateTokenRequestBody(grantRequest, body).with(OAuth2ParameterNames.ASSERTION,
grantRequest.getJwt().getTokenValue());
}
}
| 2,599 | 39 | 96 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequestEntityConverter.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.endpoint;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link AbstractOAuth2AuthorizationGrantRequestEntityConverter}
* that converts the provided {@link OAuth2ClientCredentialsGrantRequest} to a
* {@link RequestEntity} representation of an OAuth 2.0 Access Token Request for the
* Client Credentials Grant.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractOAuth2AuthorizationGrantRequestEntityConverter
* @see OAuth2ClientCredentialsGrantRequest
* @see RequestEntity
*/
public class OAuth2ClientCredentialsGrantRequestEntityConverter
extends AbstractOAuth2AuthorizationGrantRequestEntityConverter<OAuth2ClientCredentialsGrantRequest> {
@Override
protected MultiValueMap<String, String> createParameters(
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
ClientRegistration clientRegistration = clientCredentialsGrantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, clientCredentialsGrantRequest.getGrantType().getValue());
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
parameters.add(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod())) {
parameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
parameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
}
return parameters;
}
}
| 2,738 | 43.901639 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AccessTokenResponseClient.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.endpoint;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
/**
* A strategy for "exchanging" an authorization grant credential (e.g. an
* Authorization Code) for an access token credential at the Authorization Server's Token
* Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractOAuth2AuthorizationGrantRequest
* @see OAuth2AccessTokenResponse
* @see AuthorizationGrantType
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-1.3">Section
* 1.3 Authorization Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token Request
* (Authorization Code Grant)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token Response
* (Authorization Code Grant)</a>
*/
@FunctionalInterface
public interface OAuth2AccessTokenResponseClient<T extends AbstractOAuth2AuthorizationGrantRequest> {
/**
* Exchanges the authorization grant credential, provided in the authorization grant
* request, for an access token credential at the Authorization Server's Token
* Endpoint.
* @param authorizationGrantRequest the authorization grant request that contains the
* authorization grant credential
* @return an {@link OAuth2AccessTokenResponse} that contains the
* {@link OAuth2AccessTokenResponse#getAccessToken() access token} credential
* @throws OAuth2AuthorizationException if an error occurs while attempting to
* exchange for the access token credential
*/
OAuth2AccessTokenResponse getTokenResponse(T authorizationGrantRequest);
}
| 2,488 | 41.186441 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequestEntityConverter.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.endpoint;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link AbstractOAuth2AuthorizationGrantRequestEntityConverter}
* that converts the provided {@link OAuth2PasswordGrantRequest} to a
* {@link RequestEntity} representation of an OAuth 2.0 Access Token Request for the
* Resource Owner Password Credentials Grant.
*
* @author Joe Grandja
* @since 5.2
* @see AbstractOAuth2AuthorizationGrantRequestEntityConverter
* @see OAuth2PasswordGrantRequest
* @see RequestEntity
*/
public class OAuth2PasswordGrantRequestEntityConverter
extends AbstractOAuth2AuthorizationGrantRequestEntityConverter<OAuth2PasswordGrantRequest> {
@Override
protected MultiValueMap<String, String> createParameters(OAuth2PasswordGrantRequest passwordGrantRequest) {
ClientRegistration clientRegistration = passwordGrantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, passwordGrantRequest.getGrantType().getValue());
parameters.add(OAuth2ParameterNames.USERNAME, passwordGrantRequest.getUsername());
parameters.add(OAuth2ParameterNames.PASSWORD, passwordGrantRequest.getPassword());
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
parameters.add(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod())) {
parameters.add(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
parameters.add(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
}
return parameters;
}
}
| 2,849 | 44.967742 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/AbstractWebClientReactiveOAuth2AccessTokenResponseClient.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.endpoint;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Set;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpInputMessage;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors;
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.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersSpec;
/**
* Abstract base class for all of the {@code WebClientReactive*TokenResponseClient}s that
* communicate to the Authorization Server's Token Endpoint.
*
* <p>
* Submits a form request body specific to the type of grant request.
* </p>
*
* <p>
* Accepts a JSON response body containing an OAuth 2.0 Access token or error.
* </p>
*
* @param <T> type of grant request
* @author Phil Clay
* @since 5.3
* @see <a href="https://tools.ietf.org/html/rfc6749#section-3.2">RFC-6749 Token
* Endpoint</a>
* @see WebClientReactiveAuthorizationCodeTokenResponseClient
* @see WebClientReactiveClientCredentialsTokenResponseClient
* @see WebClientReactivePasswordTokenResponseClient
* @see WebClientReactiveRefreshTokenTokenResponseClient
*/
public abstract class AbstractWebClientReactiveOAuth2AccessTokenResponseClient<T extends AbstractOAuth2AuthorizationGrantRequest>
implements ReactiveOAuth2AccessTokenResponseClient<T> {
private WebClient webClient = WebClient.builder().build();
private Converter<T, RequestHeadersSpec<?>> requestEntityConverter = this::validatingPopulateRequest;
private Converter<T, HttpHeaders> headersConverter = this::populateTokenRequestHeaders;
private Converter<T, MultiValueMap<String, String>> parametersConverter = this::populateTokenRequestParameters;
private BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor = OAuth2BodyExtractors
.oauth2AccessTokenResponse();
AbstractWebClientReactiveOAuth2AccessTokenResponseClient() {
}
@Override
public Mono<OAuth2AccessTokenResponse> getTokenResponse(T grantRequest) {
Assert.notNull(grantRequest, "grantRequest cannot be null");
// @formatter:off
return Mono.defer(() -> this.requestEntityConverter.convert(grantRequest)
.exchange()
.flatMap((response) -> readTokenResponse(grantRequest, response))
);
// @formatter:on
}
/**
* Returns the {@link ClientRegistration} for the given {@code grantRequest}.
* @param grantRequest the grant request
* @return the {@link ClientRegistration} for the given {@code grantRequest}.
*/
abstract ClientRegistration clientRegistration(T grantRequest);
private RequestHeadersSpec<?> validatingPopulateRequest(T grantRequest) {
validateClientAuthenticationMethod(grantRequest);
return populateRequest(grantRequest);
}
private void validateClientAuthenticationMethod(T grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
ClientAuthenticationMethod clientAuthenticationMethod = clientRegistration.getClientAuthenticationMethod();
boolean supportedClientAuthenticationMethod = clientAuthenticationMethod.equals(ClientAuthenticationMethod.NONE)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
|| clientAuthenticationMethod.equals(ClientAuthenticationMethod.CLIENT_SECRET_POST);
if (!supportedClientAuthenticationMethod) {
throw new IllegalArgumentException(String.format(
"This class supports `client_secret_basic`, `client_secret_post`, and `none` by default. Client [%s] is using [%s] instead. Please use a supported client authentication method, or use `set/addParametersConverter` or `set/addHeadersConverter` to supply an instance that supports [%s].",
clientRegistration.getRegistrationId(), clientAuthenticationMethod, clientAuthenticationMethod));
}
}
private RequestHeadersSpec<?> populateRequest(T grantRequest) {
return this.webClient.post().uri(clientRegistration(grantRequest).getProviderDetails().getTokenUri())
.headers((headers) -> {
HttpHeaders headersToAdd = getHeadersConverter().convert(grantRequest);
if (headersToAdd != null) {
headers.addAll(headersToAdd);
}
}).body(createTokenRequestBody(grantRequest));
}
/**
* Populates the headers for the token request.
* @param grantRequest the grant request
* @return the headers populated for the token request
*/
private HttpHeaders populateTokenRequestHeaders(T grantRequest) {
HttpHeaders headers = new HttpHeaders();
ClientRegistration clientRegistration = clientRegistration(grantRequest);
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientRegistration.getClientAuthenticationMethod())) {
String clientId = encodeClientCredential(clientRegistration.getClientId());
String clientSecret = encodeClientCredential(clientRegistration.getClientSecret());
headers.setBasicAuth(clientId, clientSecret);
}
return headers;
}
private static String encodeClientCredential(String clientCredential) {
try {
return URLEncoder.encode(clientCredential, StandardCharsets.UTF_8.toString());
}
catch (UnsupportedEncodingException ex) {
// Will not happen since UTF-8 is a standard charset
throw new IllegalArgumentException(ex);
}
}
/**
* Populates default parameters for the token request.
* @param grantRequest the grant request
* @return the parameters populated for the token request.
*/
private MultiValueMap<String, String> populateTokenRequestParameters(T grantRequest) {
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, grantRequest.getGrantType().getValue());
return parameters;
}
/**
* Combine the results of {@code parametersConverter} and
* {@link #populateTokenRequestBody}.
*
* <p>
* This method pre-populates the body with some standard properties, and then
* delegates to
* {@link #populateTokenRequestBody(AbstractOAuth2AuthorizationGrantRequest, BodyInserters.FormInserter)}
* for subclasses to further populate the body before returning.
* </p>
* @param grantRequest the grant request
* @return the body for the token request.
*/
private BodyInserters.FormInserter<String> createTokenRequestBody(T grantRequest) {
MultiValueMap<String, String> parameters = getParametersConverter().convert(grantRequest);
return populateTokenRequestBody(grantRequest, BodyInserters.fromFormData(parameters));
}
/**
* Populates the body of the token request.
*
* <p>
* By default, populates properties that are common to all grant types. Subclasses can
* extend this method to populate grant type specific properties.
* </p>
* @param grantRequest the grant request
* @param body the body to populate
* @return the populated body
*/
BodyInserters.FormInserter<String> populateTokenRequestBody(T grantRequest,
BodyInserters.FormInserter<String> body) {
ClientRegistration clientRegistration = clientRegistration(grantRequest);
if (!ClientAuthenticationMethod.CLIENT_SECRET_BASIC
.equals(clientRegistration.getClientAuthenticationMethod())) {
body.with(OAuth2ParameterNames.CLIENT_ID, clientRegistration.getClientId());
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientRegistration.getClientAuthenticationMethod())) {
body.with(OAuth2ParameterNames.CLIENT_SECRET, clientRegistration.getClientSecret());
}
Set<String> scopes = scopes(grantRequest);
if (!CollectionUtils.isEmpty(scopes)) {
body.with(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(scopes, " "));
}
return body;
}
/**
* Returns the scopes to include as a property in the token request.
* @param grantRequest the grant request
* @return the scopes to include as a property in the token request.
*/
abstract Set<String> scopes(T grantRequest);
/**
* Returns the scopes to include in the response if the authorization server returned
* no scopes in the response.
*
* <p>
* As per <a href="https://tools.ietf.org/html/rfc6749#section-5.1">RFC-6749 Section
* 5.1 Successful Access Token Response</a>, if AccessTokenResponse.scope is empty,
* then default to the scope originally requested by the client in the Token Request.
* </p>
* @param grantRequest the grant request
* @return the scopes to include in the response if the authorization server returned
* no scopes.
*/
Set<String> defaultScopes(T grantRequest) {
return Collections.emptySet();
}
/**
* Reads the token response from the response body.
* @param grantRequest the request for which the response was received.
* @param response the client response from which to read
* @return the token response from the response body.
*/
private Mono<OAuth2AccessTokenResponse> readTokenResponse(T grantRequest, ClientResponse response) {
return response.body(this.bodyExtractor)
.map((tokenResponse) -> populateTokenResponse(grantRequest, tokenResponse));
}
/**
* Populates the given {@link OAuth2AccessTokenResponse} with additional details from
* the grant request.
* @param grantRequest the request for which the response was received.
* @param tokenResponse the original token response
* @return a token response optionally populated with additional details from the
* request.
*/
OAuth2AccessTokenResponse populateTokenResponse(T grantRequest, OAuth2AccessTokenResponse tokenResponse) {
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
Set<String> defaultScopes = defaultScopes(grantRequest);
// @formatter:off
tokenResponse = OAuth2AccessTokenResponse
.withResponse(tokenResponse)
.scopes(defaultScopes)
.build();
// @formatter:on
}
return tokenResponse;
}
/**
* Sets the {@link WebClient} used when requesting the OAuth 2.0 Access Token
* Response.
* @param webClient the {@link WebClient} used when requesting the Access Token
* Response
*/
public void setWebClient(WebClient webClient) {
Assert.notNull(webClient, "webClient cannot be null");
this.webClient = webClient;
}
/**
* Returns the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @return the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to {@link HttpHeaders}
*/
final Converter<T, HttpHeaders> getHeadersConverter() {
return this.headersConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @param headersConverter the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to {@link HttpHeaders}
* @since 5.6
*/
public final void setHeadersConverter(Converter<T, HttpHeaders> headersConverter) {
Assert.notNull(headersConverter, "headersConverter cannot be null");
this.headersConverter = headersConverter;
this.requestEntityConverter = this::populateRequest;
}
/**
* Add (compose) the provided {@code headersConverter} to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link HttpHeaders}
* used in the OAuth 2.0 Access Token Request headers.
* @param headersConverter the {@link Converter} to add (compose) to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link HttpHeaders}
* @since 5.6
*/
public final void addHeadersConverter(Converter<T, HttpHeaders> headersConverter) {
Assert.notNull(headersConverter, "headersConverter cannot be null");
Converter<T, HttpHeaders> currentHeadersConverter = this.headersConverter;
this.headersConverter = (authorizationGrantRequest) -> {
// Append headers using a Composite Converter
HttpHeaders headers = currentHeadersConverter.convert(authorizationGrantRequest);
if (headers == null) {
headers = new HttpHeaders();
}
HttpHeaders headersToAdd = headersConverter.convert(authorizationGrantRequest);
if (headersToAdd != null) {
headers.addAll(headersToAdd);
}
return headers;
};
this.requestEntityConverter = this::populateRequest;
}
/**
* Returns the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* used in the OAuth 2.0 Access Token Request body.
* @return the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to {@link MultiValueMap}
*/
final Converter<T, MultiValueMap<String, String>> getParametersConverter() {
return this.parametersConverter;
}
/**
* Sets the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* used in the OAuth 2.0 Access Token Request body.
* @param parametersConverter the {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to {@link MultiValueMap}
* @since 5.6
*/
public final void setParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
this.parametersConverter = parametersConverter;
this.requestEntityConverter = this::populateRequest;
}
/**
* Add (compose) the provided {@code parametersConverter} to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} instance to a {@link MultiValueMap}
* used in the OAuth 2.0 Access Token Request body.
* @param parametersConverter the {@link Converter} to add (compose) to the current
* {@link Converter} used for converting the
* {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link MultiValueMap}
* @since 5.6
*/
public final void addParametersConverter(Converter<T, MultiValueMap<String, String>> parametersConverter) {
Assert.notNull(parametersConverter, "parametersConverter cannot be null");
Converter<T, MultiValueMap<String, String>> currentParametersConverter = this.parametersConverter;
this.parametersConverter = (authorizationGrantRequest) -> {
MultiValueMap<String, String> parameters = currentParametersConverter.convert(authorizationGrantRequest);
if (parameters == null) {
parameters = new LinkedMultiValueMap<>();
}
MultiValueMap<String, String> parametersToAdd = parametersConverter.convert(authorizationGrantRequest);
if (parametersToAdd != null) {
parameters.addAll(parametersToAdd);
}
return parameters;
};
this.requestEntityConverter = this::populateRequest;
}
/**
* Sets the {@link BodyExtractor} that will be used to decode the
* {@link OAuth2AccessTokenResponse}
* @param bodyExtractor the {@link BodyExtractor} that will be used to decode the
* {@link OAuth2AccessTokenResponse}
* @since 5.6
*/
public final void setBodyExtractor(
BodyExtractor<Mono<OAuth2AccessTokenResponse>, ReactiveHttpInputMessage> bodyExtractor) {
Assert.notNull(bodyExtractor, "bodyExtractor cannot be null");
this.bodyExtractor = bodyExtractor;
}
}
| 17,082 | 41.389578 | 290 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationGrantRequestEntityUtils.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.endpoint;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
/**
* Utility methods used by the {@link Converter}'s that convert from an implementation of
* an {@link AbstractOAuth2AuthorizationGrantRequest} to a {@link RequestEntity}
* representation of an OAuth 2.0 Access Token Request for the specific Authorization
* Grant.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizationCodeGrantRequestEntityConverter
* @see OAuth2ClientCredentialsGrantRequestEntityConverter
*/
final class OAuth2AuthorizationGrantRequestEntityUtils {
private static HttpHeaders DEFAULT_TOKEN_REQUEST_HEADERS = getDefaultTokenRequestHeaders();
private OAuth2AuthorizationGrantRequestEntityUtils() {
}
static HttpHeaders getTokenRequestHeaders(ClientRegistration clientRegistration) {
HttpHeaders headers = new HttpHeaders();
headers.addAll(DEFAULT_TOKEN_REQUEST_HEADERS);
if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientRegistration.getClientAuthenticationMethod())) {
String clientId = encodeClientCredential(clientRegistration.getClientId());
String clientSecret = encodeClientCredential(clientRegistration.getClientSecret());
headers.setBasicAuth(clientId, clientSecret);
}
return headers;
}
private static String encodeClientCredential(String clientCredential) {
try {
return URLEncoder.encode(clientCredential, StandardCharsets.UTF_8.toString());
}
catch (UnsupportedEncodingException ex) {
// Will not happen since UTF-8 is a standard charset
throw new IllegalArgumentException(ex);
}
}
private static HttpHeaders getDefaultTokenRequestHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
final MediaType contentType = MediaType.valueOf(MediaType.APPLICATION_FORM_URLENCODED_VALUE + ";charset=UTF-8");
headers.setContentType(contentType);
return headers;
}
}
| 3,046 | 37.56962 | 114 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/http/OAuth2ErrorResponseErrorHandler.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.http;
import java.io.IOException;
import com.nimbusds.oauth2.sdk.token.BearerTokenError;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
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.http.converter.OAuth2ErrorHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResponseErrorHandler;
/**
* A {@link ResponseErrorHandler} that handles an {@link OAuth2Error OAuth 2.0 Error}.
*
* @author Joe Grandja
* @since 5.1
* @see ResponseErrorHandler
* @see OAuth2Error
*/
public class OAuth2ErrorResponseErrorHandler implements ResponseErrorHandler {
private HttpMessageConverter<OAuth2Error> oauth2ErrorConverter = new OAuth2ErrorHttpMessageConverter();
private final ResponseErrorHandler defaultErrorHandler = new DefaultResponseErrorHandler();
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return this.defaultErrorHandler.hasError(response);
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
if (HttpStatus.BAD_REQUEST.value() != response.getRawStatusCode()) {
this.defaultErrorHandler.handleError(response);
}
// A Bearer Token Error may be in the WWW-Authenticate response header
// See https://tools.ietf.org/html/rfc6750#section-3
OAuth2Error oauth2Error = this.readErrorFromWwwAuthenticate(response.getHeaders());
if (oauth2Error == null) {
oauth2Error = this.oauth2ErrorConverter.read(OAuth2Error.class, response);
}
throw new OAuth2AuthorizationException(oauth2Error);
}
private OAuth2Error readErrorFromWwwAuthenticate(HttpHeaders headers) {
String wwwAuthenticateHeader = headers.getFirst(HttpHeaders.WWW_AUTHENTICATE);
if (!StringUtils.hasText(wwwAuthenticateHeader)) {
return null;
}
BearerTokenError bearerTokenError = getBearerToken(wwwAuthenticateHeader);
if (bearerTokenError == null) {
return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null);
}
String errorCode = (bearerTokenError.getCode() != null) ? bearerTokenError.getCode()
: OAuth2ErrorCodes.SERVER_ERROR;
String errorDescription = bearerTokenError.getDescription();
String errorUri = (bearerTokenError.getURI() != null) ? bearerTokenError.getURI().toString() : null;
return new OAuth2Error(errorCode, errorDescription, errorUri);
}
private BearerTokenError getBearerToken(String wwwAuthenticateHeader) {
try {
return BearerTokenError.parse(wwwAuthenticateHeader);
}
catch (Exception ex) {
return null;
}
}
/**
* Sets the {@link HttpMessageConverter} for an OAuth 2.0 Error.
* @param oauth2ErrorConverter A {@link HttpMessageConverter} for an
* {@link OAuth2Error OAuth 2.0 Error}.
* @since 5.7
*/
public final void setErrorConverter(HttpMessageConverter<OAuth2Error> oauth2ErrorConverter) {
Assert.notNull(oauth2ErrorConverter, "oauth2ErrorConverter cannot be null");
this.oauth2ErrorConverter = oauth2ErrorConverter;
}
}
| 4,092 | 37.613208 | 104 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/annotation/RegisteredOAuth2AuthorizedClient.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.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2AuthorizedClientArgumentResolver;
/**
* This annotation may be used to resolve a method parameter to an argument value of type
* {@link OAuth2AuthorizedClient}.
*
* <p>
* For example: <pre>
* @Controller
* public class MyController {
* @GetMapping("/authorized-client")
* public String authorizedClient(@RegisteredOAuth2AuthorizedClient("login-client") OAuth2AuthorizedClient authorizedClient) {
* // do something with authorizedClient
* }
* }
* </pre>
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizedClientArgumentResolver
*/
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RegisteredOAuth2AuthorizedClient {
/**
* Sets the client registration identifier.
* @return the client registration identifier
*/
@AliasFor("value")
String registrationId() default "";
/**
* The default attribute for this annotation. This is an alias for
* {@link #registrationId()}. For example,
* {@code @RegisteredOAuth2AuthorizedClient("login-client")} is equivalent to
* {@code @RegisteredOAuth2AuthorizedClient(registrationId="login-client")}.
* @return the client registration identifier
*/
@AliasFor("registrationId")
String value() default "";
}
| 2,392 | 32.704225 | 130 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/SupplierReactiveJwtDecoderTests.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.jwt;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link SupplierReactiveJwtDecoder}
*/
public class SupplierReactiveJwtDecoderTests {
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
SupplierReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(() -> jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
ReactiveJwtDecoder jwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class)
.isThrownBy(() -> jwtDecoder.decode("token").block());
verify(broken).get();
}
@Test
public void decodeWhenInitializedThenCaches() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
Supplier<ReactiveJwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(supplier);
supplierReactiveJwtDecoder.decode("token").block();
supplierReactiveJwtDecoder.decode("token").block();
verify(supplier, times(1)).get();
verify(jwtDecoder, times(2)).decode("token");
}
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
ReactiveJwtDecoder jwtDecoder = mock(ReactiveJwtDecoder.class);
Supplier<ReactiveJwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
given(jwtDecoder.decode("token")).willReturn(Mono.empty());
ReactiveJwtDecoder supplierReactiveJwtDecoder = new SupplierReactiveJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class)
.isThrownBy(() -> supplierReactiveJwtDecoder.decode("token").block());
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierReactiveJwtDecoder.decode("token").block();
verify(jwtDecoder).decode("token");
}
}
| 3,305 | 38.357143 | 107 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimValidatorTests.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.jwt;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link JwtClaimValidator}.
*
* @author Zeeshan Adnan
*/
public class JwtClaimValidatorTests {
private static final Predicate<String> test = (claim) -> claim.equals("http://test");
private final JwtClaimValidator<String> validator = new JwtClaimValidator<>(JwtClaimNames.ISS, test);
@Test
public void validateWhenClaimPassesTheTestThenReturnsSuccess() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://test").build();
assertThat(this.validator.validate(jwt)).isEqualTo(OAuth2TokenValidatorResult.success());
}
@Test
public void validateWhenClaimFailsTheTestThenReturnsFailure() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "http://abc").build();
Collection<OAuth2Error> details = this.validator.validate(jwt).getErrors();
assertThat(this.validator.validate(jwt).getErrors().isEmpty()).isFalse();
assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN));
}
@Test
public void validateWhenClaimIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new JwtClaimValidator<>(null, test));
}
@Test
public void validateWhenTestIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new JwtClaimValidator<>(JwtClaimNames.ISS, null));
}
@Test
public void validateWhenJwtIsNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.validator.validate(null));
}
}
| 2,663 | 35.493151 | 112 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoderProviderConfigurationUtilsTests.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.jwt;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
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.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
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 ReactiveJwtDecoderProviderConfigurationUtils}
*
* @author Josh Cummings
*/
public class ReactiveJwtDecoderProviderConfigurationUtilsTests {
/**
* Contains those parameters required to construct a ReactiveJwtDecoder as well as any
* required parameters
*/
// @formatter:off
private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n"
+ " \"authorization_endpoint\": \"https://example.com/o/oauth2/v2/auth\", \n"
+ " \"id_token_signing_alg_values_supported\": [\n"
+ " \"RS256\"\n"
+ " ], \n"
+ " \"issuer\": \"%s\", \n"
+ " \"jwks_uri\": \"%s/.well-known/jwks.json\", \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"
+ " \"subject_types_supported\": [\n"
+ " \"public\"\n"
+ " ], \n"
+ " \"token_endpoint\": \"https://example.com/oauth2/v4/token\"\n"
+ "}";
// @formatter:on
private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"oXJ8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtdF4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAjjDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}";
private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";
private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
private final WebClient web = WebClient.builder().build();
private MockWebServer server;
private String issuer;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.issuer = createIssuerFromServer();
this.issuer += "path";
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void issuerWhenResponseIsTypicalThenReturnedConfigurationContainsJwksUri() {
prepareConfigurationResponse();
Map<String, Object> configuration = ReactiveJwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(this.issuer, this.web).block();
assertThat(configuration).containsKey("jwks_uri");
}
@Test
public void issuerWhenOidcFallbackResponseIsTypicalThenReturnedConfigurationContainsJwksUri() {
prepareConfigurationResponseOidc();
Map<String, Object> configuration = ReactiveJwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(this.issuer, this.web).block();
assertThat(configuration).containsKey("jwks_uri");
}
@Test
public void issuerWhenOAuth2ResponseIsTypicalThenReturnedConfigurationContainsJwksUri() {
prepareConfigurationResponseOAuth2();
Map<String, Object> configuration = ReactiveJwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(this.issuer, this.web).block();
assertThat(configuration).containsKey("jwks_uri");
}
@Test
public void issuerWhenOidcFallbackResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block());
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block());
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOidc(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block())
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOAuth2ResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOAuth2(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block())
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block());
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block());
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOidc(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> {
Map<String, Object> configuration = ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block();
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, this.issuer);
});
// @formatter:on
}
@Test
public void issuerWhenOAuth2RespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOAuth2(
String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> {
Map<String, Object> configuration = ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation(this.issuer, this.web).block();
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, this.issuer);
});
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException()
throws Exception {
this.server.shutdown();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoderProviderConfigurationUtils.getConfigurationForIssuerLocation("https://issuer", this.web).block());
// @formatter:on
}
private void prepareConfigurationResponse() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponse(body);
}
private void prepareConfigurationResponse(String body) {
this.server.enqueue(response(body));
this.server.enqueue(response(JWK_SET));
}
private void prepareConfigurationResponseOidc() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOidc(body);
}
private void prepareConfigurationResponseOidc(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oidc(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponseOAuth2() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOAuth2(body);
}
private void prepareConfigurationResponseOAuth2(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oauth(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponses(Map<String, MockResponse> responses) {
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
// @formatter:off
return Optional.of(request)
.map(RecordedRequest::getRequestUrl)
.map(HttpUrl::toString)
.map(responses::get)
.orElse(new MockResponse().setResponseCode(404));
// @formatter:on
}
};
this.server.setDispatcher(dispatcher);
}
private String createIssuerFromServer() {
return this.server.url("").toString();
}
private String oidc() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(uri.getPath() + OIDC_METADATA_PATH)
.toUriString();
// @formatter:on
}
private String oauth() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(OAUTH_METADATA_PATH + uri.getPath())
.toUriString();
// @formatter:on
}
private String jwks() {
return this.issuer + "/.well-known/jwks.json";
}
private MockResponse response(String body) {
// @formatter:off
return new MockResponse().setBody(body)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
public String buildResponseWithMissingJwksUri() throws JsonMappingException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> response = mapper.readValue(DEFAULT_RESPONSE_TEMPLATE,
new TypeReference<Map<String, Object>>() {
});
response.remove("jwks_uri");
return mapper.writeValueAsString(response);
}
}
| 12,076 | 36.740625 | 472 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJweEncoderTests.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.jwt;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWEHeader;
import com.nimbusds.jose.JWEObject;
import com.nimbusds.jose.Payload;
import com.nimbusds.jose.crypto.RSAEncrypter;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jwt.JWTClaimsSet;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.jose.JwaAlgorithm;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for proofing out future support of JWE.
*
* @author Joe Grandja
*/
public class NimbusJweEncoderTests {
// @formatter:off
private static final JweHeader DEFAULT_JWE_HEADER =
JweHeader.with(JweAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM.getName()).build();
// @formatter:on
private List<JWK> jwkList;
private JWKSource<SecurityContext> jwkSource;
private NimbusJweEncoder jweEncoder;
@BeforeEach
public void setUp() {
this.jwkList = new ArrayList<>();
this.jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(new JWKSet(this.jwkList));
this.jweEncoder = new NimbusJweEncoder(this.jwkSource);
}
@Test
public void encodeWhenJwtClaimsSetThenEncodes() {
RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
this.jwkList.add(rsaJwk);
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
// @formatter:off
// **********************
// Assume future API:
// JwtEncoderParameters.with(JweHeader jweHeader, JwtClaimsSet claims)
// **********************
// @formatter:on
Jwt encodedJwe = this.jweEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(DEFAULT_JWE_HEADER.getAlgorithm());
assertThat(encodedJwe.getHeaders().get("enc")).isEqualTo(DEFAULT_JWE_HEADER.<String>getHeader("enc"));
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5T)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.X5T_S256)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.TYP)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.CTY)).isNull();
assertThat(encodedJwe.getHeaders().get(JoseHeaderNames.CRIT)).isNull();
assertThat(encodedJwe.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer());
assertThat(encodedJwe.getSubject()).isEqualTo(jwtClaimsSet.getSubject());
assertThat(encodedJwe.getAudience()).isEqualTo(jwtClaimsSet.getAudience());
assertThat(encodedJwe.getExpiresAt()).isEqualTo(jwtClaimsSet.getExpiresAt());
assertThat(encodedJwe.getNotBefore()).isEqualTo(jwtClaimsSet.getNotBefore());
assertThat(encodedJwe.getIssuedAt()).isEqualTo(jwtClaimsSet.getIssuedAt());
assertThat(encodedJwe.getId()).isEqualTo(jwtClaimsSet.getId());
assertThat(encodedJwe.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
assertThat(encodedJwe.getTokenValue()).isNotNull();
}
@Test
public void encodeWhenNestedJwsThenEncodes() {
// See Nimbus example -> Nested signed and encrypted JWT
// https://connect2id.com/products/nimbus-jose-jwt/examples/signed-and-encrypted-jwt
RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
this.jwkList.add(rsaJwk);
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
// @formatter:off
// **********************
// Assume future API:
// JwtEncoderParameters.with(JwsHeader jwsHeader, JweHeader jweHeader, JwtClaimsSet claims)
// **********************
// @formatter:on
Jwt encodedJweNestedJws = this.jweEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.ALG))
.isEqualTo(DEFAULT_JWE_HEADER.getAlgorithm());
assertThat(encodedJweNestedJws.getHeaders().get("enc")).isEqualTo(DEFAULT_JWE_HEADER.<String>getHeader("enc"));
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.X5T_S256)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull();
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.CTY)).isEqualTo("JWT");
assertThat(encodedJweNestedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull();
assertThat(encodedJweNestedJws.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer());
assertThat(encodedJweNestedJws.getSubject()).isEqualTo(jwtClaimsSet.getSubject());
assertThat(encodedJweNestedJws.getAudience()).isEqualTo(jwtClaimsSet.getAudience());
assertThat(encodedJweNestedJws.getExpiresAt()).isEqualTo(jwtClaimsSet.getExpiresAt());
assertThat(encodedJweNestedJws.getNotBefore()).isEqualTo(jwtClaimsSet.getNotBefore());
assertThat(encodedJweNestedJws.getIssuedAt()).isEqualTo(jwtClaimsSet.getIssuedAt());
assertThat(encodedJweNestedJws.getId()).isEqualTo(jwtClaimsSet.getId());
assertThat(encodedJweNestedJws.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
assertThat(encodedJweNestedJws.getTokenValue()).isNotNull();
}
enum JweAlgorithm implements JwaAlgorithm {
RSA_OAEP_256("RSA-OAEP-256");
private final String name;
JweAlgorithm(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
}
private static final class JweHeader extends JoseHeader {
private JweHeader(Map<String, Object> headers) {
super(headers);
}
@SuppressWarnings("unchecked")
@Override
public JweAlgorithm getAlgorithm() {
return super.getAlgorithm();
}
private static Builder with(JweAlgorithm jweAlgorithm, String enc) {
return new Builder(jweAlgorithm, enc);
}
private static Builder from(JweHeader headers) {
return new Builder(headers);
}
private static final class Builder extends AbstractBuilder<JweHeader, Builder> {
private Builder(JweAlgorithm jweAlgorithm, String enc) {
Assert.notNull(jweAlgorithm, "jweAlgorithm cannot be null");
Assert.hasText(enc, "enc cannot be empty");
algorithm(jweAlgorithm);
header("enc", enc);
}
private Builder(JweHeader headers) {
Assert.notNull(headers, "headers cannot be null");
Consumer<Map<String, Object>> headersConsumer = (h) -> h.putAll(headers.getHeaders());
headers(headersConsumer);
}
@Override
public JweHeader build() {
return new JweHeader(getHeaders());
}
}
}
private static final class NimbusJweEncoder implements JwtEncoder {
private static final String ENCODING_ERROR_MESSAGE_TEMPLATE = "An error occurred while attempting to encode the Jwt: %s";
private static final Converter<JweHeader, JWEHeader> JWE_HEADER_CONVERTER = new JweHeaderConverter();
private static final Converter<JwtClaimsSet, JWTClaimsSet> JWT_CLAIMS_SET_CONVERTER = new JwtClaimsSetConverter();
private final JWKSource<SecurityContext> jwkSource;
private final JwtEncoder jwsEncoder;
private NimbusJweEncoder(JWKSource<SecurityContext> jwkSource) {
Assert.notNull(jwkSource, "jwkSource cannot be null");
this.jwkSource = jwkSource;
this.jwsEncoder = new NimbusJwtEncoder(jwkSource);
}
@Override
public Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException {
Assert.notNull(parameters, "parameters cannot be null");
// @formatter:off
// **********************
// Assume future API:
// JwtEncoderParameters.getJweHeader()
// **********************
// @formatter:on
JweHeader jweHeader = DEFAULT_JWE_HEADER; // Assume this is accessed via
// JwtEncoderParameters.getJweHeader()
JwsHeader jwsHeader = parameters.getJwsHeader();
JwtClaimsSet claims = parameters.getClaims();
JWK jwk = selectJwk(jweHeader);
jweHeader = addKeyIdentifierHeadersIfNecessary(jweHeader, jwk);
JWEHeader jweHeader2 = JWE_HEADER_CONVERTER.convert(jweHeader);
JWTClaimsSet jwtClaimsSet = JWT_CLAIMS_SET_CONVERTER.convert(claims);
String payload;
if (jwsHeader != null) {
// Sign then encrypt
Jwt jws = this.jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, claims));
payload = jws.getTokenValue();
// @formatter:off
jweHeader = JweHeader.from(jweHeader)
.contentType("JWT") // Indicates Nested JWT (REQUIRED)
.build();
// @formatter:on
}
else {
// Encrypt only
payload = jwtClaimsSet.toString();
}
JWEObject jweObject = new JWEObject(jweHeader2, new Payload(payload));
try {
// FIXME
// Resolve type of JWEEncrypter using the JWK key type
// For now, assuming RSA key type
jweObject.encrypt(new RSAEncrypter(jwk.toRSAKey()));
}
catch (JOSEException ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to encrypt the JWT -> " + ex.getMessage()), ex);
}
String jwe = jweObject.serialize();
// NOTE:
// For the Nested JWS use case, we lose access to the JWS Header in the
// returned JWT.
// If this is needed, we can simply add the new method Jwt.getNestedHeaders().
return new Jwt(jwe, claims.getIssuedAt(), claims.getExpiresAt(), jweHeader.getHeaders(),
claims.getClaims());
}
private JWK selectJwk(JweHeader headers) {
List<JWK> jwks;
try {
JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers));
jwks = this.jwkSource.get(jwkSelector, null);
}
catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to select a JWK encryption key -> " + ex.getMessage()), ex);
}
if (jwks.size() > 1) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Found multiple JWK encryption keys for algorithm '" + headers.getAlgorithm().getName() + "'"));
}
if (jwks.isEmpty()) {
throw new JwtEncodingException(
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK encryption key"));
}
return jwks.get(0);
}
private static JWKMatcher createJwkMatcher(JweHeader headers) {
JWEAlgorithm jweAlgorithm = JWEAlgorithm.parse(headers.getAlgorithm().getName());
// @formatter:off
return new JWKMatcher.Builder()
.keyType(KeyType.forAlgorithm(jweAlgorithm))
.keyID(headers.getKeyId())
.keyUses(KeyUse.ENCRYPTION, null)
.algorithms(jweAlgorithm, null)
.x509CertSHA256Thumbprint(Base64URL.from(headers.getX509SHA256Thumbprint()))
.build();
// @formatter:on
}
private static JweHeader addKeyIdentifierHeadersIfNecessary(JweHeader headers, JWK jwk) {
// Check if headers have already been added
if (StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(headers.getX509SHA256Thumbprint())) {
return headers;
}
// Check if headers can be added from JWK
if (!StringUtils.hasText(jwk.getKeyID()) && jwk.getX509CertSHA256Thumbprint() == null) {
return headers;
}
JweHeader.Builder headersBuilder = JweHeader.from(headers);
if (!StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(jwk.getKeyID())) {
headersBuilder.keyId(jwk.getKeyID());
}
if (!StringUtils.hasText(headers.getX509SHA256Thumbprint()) && jwk.getX509CertSHA256Thumbprint() != null) {
headersBuilder.x509SHA256Thumbprint(jwk.getX509CertSHA256Thumbprint().toString());
}
return headersBuilder.build();
}
}
private static class JweHeaderConverter implements Converter<JweHeader, JWEHeader> {
@Override
public JWEHeader convert(JweHeader headers) {
JWEAlgorithm jweAlgorithm = JWEAlgorithm.parse(headers.getAlgorithm().getName());
EncryptionMethod encryptionMethod = EncryptionMethod.parse(headers.getHeader("enc"));
JWEHeader.Builder builder = new JWEHeader.Builder(jweAlgorithm, encryptionMethod);
URL jwkSetUri = headers.getJwkSetUrl();
if (jwkSetUri != null) {
try {
builder.jwkURL(jwkSetUri.toURI());
}
catch (Exception ex) {
throw new IllegalArgumentException(
"Unable to convert '" + JoseHeaderNames.JKU + "' JOSE header to a URI", ex);
}
}
Map<String, Object> jwk = headers.getJwk();
if (!CollectionUtils.isEmpty(jwk)) {
try {
builder.jwk(JWK.parse(jwk));
}
catch (Exception ex) {
throw new IllegalArgumentException("Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header",
ex);
}
}
String keyId = headers.getKeyId();
if (StringUtils.hasText(keyId)) {
builder.keyID(keyId);
}
URL x509Uri = headers.getX509Url();
if (x509Uri != null) {
try {
builder.x509CertURL(x509Uri.toURI());
}
catch (Exception ex) {
throw new IllegalArgumentException(
"Unable to convert '" + JoseHeaderNames.X5U + "' JOSE header to a URI", ex);
}
}
List<String> x509CertificateChain = headers.getX509CertificateChain();
if (!CollectionUtils.isEmpty(x509CertificateChain)) {
builder.x509CertChain(x509CertificateChain.stream().map(Base64::new).collect(Collectors.toList()));
}
String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
if (StringUtils.hasText(x509SHA1Thumbprint)) {
builder.x509CertThumbprint(new Base64URL(x509SHA1Thumbprint));
}
String x509SHA256Thumbprint = headers.getX509SHA256Thumbprint();
if (StringUtils.hasText(x509SHA256Thumbprint)) {
builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
}
String type = headers.getType();
if (StringUtils.hasText(type)) {
builder.type(new JOSEObjectType(type));
}
String contentType = headers.getContentType();
if (StringUtils.hasText(contentType)) {
builder.contentType(contentType);
}
Set<String> critical = headers.getCritical();
if (!CollectionUtils.isEmpty(critical)) {
builder.criticalParams(critical);
}
Map<String, Object> customHeaders = headers.getHeaders().entrySet().stream()
.filter((header) -> !JWEHeader.getRegisteredParameterNames().contains(header.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (!CollectionUtils.isEmpty(customHeaders)) {
builder.customParams(customHeaders);
}
return builder.build();
}
}
private static class JwtClaimsSetConverter implements Converter<JwtClaimsSet, JWTClaimsSet> {
@Override
public JWTClaimsSet convert(JwtClaimsSet claims) {
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
// NOTE: The value of the 'iss' claim is a String or URL (StringOrURI).
Object issuer = claims.getClaim(JwtClaimNames.ISS);
if (issuer != null) {
builder.issuer(issuer.toString());
}
String subject = claims.getSubject();
if (StringUtils.hasText(subject)) {
builder.subject(subject);
}
List<String> audience = claims.getAudience();
if (!CollectionUtils.isEmpty(audience)) {
builder.audience(audience);
}
Instant expiresAt = claims.getExpiresAt();
if (expiresAt != null) {
builder.expirationTime(Date.from(expiresAt));
}
Instant notBefore = claims.getNotBefore();
if (notBefore != null) {
builder.notBeforeTime(Date.from(notBefore));
}
Instant issuedAt = claims.getIssuedAt();
if (issuedAt != null) {
builder.issueTime(Date.from(issuedAt));
}
String jwtId = claims.getId();
if (StringUtils.hasText(jwtId)) {
builder.jwtID(jwtId);
}
Map<String, Object> customClaims = new HashMap<>();
claims.getClaims().forEach((name, value) -> {
if (!JWTClaimsSet.getRegisteredNames().contains(name)) {
customClaims.put(name, value);
}
});
if (!customClaims.isEmpty()) {
customClaims.forEach(builder::claim);
}
return builder.build();
}
}
}
| 18,178 | 34.026975 | 123 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/TestJwtClaimsSets.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.jwt;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
/**
* @author Joe Grandja
*/
public final class TestJwtClaimsSets {
private TestJwtClaimsSets() {
}
public static JwtClaimsSet.Builder jwtClaimsSet() {
String issuer = "https://provider.com";
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(1, ChronoUnit.HOURS);
// @formatter:off
return JwtClaimsSet.builder()
.issuer(issuer)
.subject("subject")
.audience(Collections.singletonList("client-1"))
.issuedAt(issuedAt)
.notBefore(issuedAt)
.expiresAt(expiresAt)
.id("jti")
.claim("custom-claim-name", "custom-claim-value");
// @formatter:on
}
}
| 1,383 | 26.68 | 75 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/TestJwsHeaders.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.jwt;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
/**
* @author Joe Grandja
*/
public final class TestJwsHeaders {
private TestJwsHeaders() {
}
public static JwsHeader.Builder jwsHeader() {
return jwsHeader(SignatureAlgorithm.RS256);
}
public static JwsHeader.Builder jwsHeader(SignatureAlgorithm signatureAlgorithm) {
// @formatter:off
return JwsHeader.with(signatureAlgorithm)
.jwkSetUrl("https://provider.com/oauth2/jwks")
.jwk(rsaJwk())
.keyId("keyId")
.x509Url("https://provider.com/oauth2/x509")
.x509CertificateChain(Arrays.asList("x509Cert1", "x509Cert2"))
.x509SHA1Thumbprint("x509SHA1Thumbprint")
.x509SHA256Thumbprint("x509SHA256Thumbprint")
.type("JWT")
.contentType("jwt-content-type")
.header("custom-header-name", "custom-header-value");
// @formatter:on
}
private static Map<String, Object> rsaJwk() {
Map<String, Object> rsaJwk = new HashMap<>();
rsaJwk.put("kty", "RSA");
rsaJwk.put("n", "modulus");
rsaJwk.put("e", "exponent");
return rsaJwk;
}
}
| 1,809 | 28.193548 | 83 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverterTests.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.jwt;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.converter.Converter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link MappedJwtClaimSetConverter}
*
* @author Josh Cummings
*/
public class MappedJwtClaimSetConverterTests {
@Test
public void convertWhenUsingCustomExpiresAtConverterThenIssuedAtConverterStillConsultsIt() {
Instant at = Instant.ofEpochMilli(1000000000000L);
Converter<Object, Instant> expiresAtConverter = mock(Converter.class);
given(expiresAtConverter.convert(any())).willReturn(at);
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
.withDefaults(Collections.singletonMap(JwtClaimNames.EXP, expiresAtConverter));
Map<String, Object> source = new HashMap<>();
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochMilli(at.toEpochMilli()).minusSeconds(1));
}
@Test
public void convertWhenUsingDefaultsThenBasesIssuedAtOffOfExpiration() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.EXP, 1000000000L);
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L).minusSeconds(1));
}
@Test
public void convertWhenUsingDefaultsThenCoercesAudienceAccordingToJwtSpec() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.AUD, "audience");
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class);
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience"));
source = Collections.singletonMap(JwtClaimNames.AUD, Arrays.asList("one", "two"));
target = converter.convert(source);
assertThat(target.get(JwtClaimNames.AUD)).isInstanceOf(Collection.class);
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("one", "two"));
}
@Test
public void convertWhenUsingDefaultsThenCoercesAllAttributesInJwtSpec() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, 1);
source.put(JwtClaimNames.AUD, "audience");
source.put(JwtClaimNames.EXP, 2000000000L);
source.put(JwtClaimNames.IAT, new Date(1000000000000L));
source.put(JwtClaimNames.ISS, "https://any.url");
source.put(JwtClaimNames.NBF, 1000000000);
source.put(JwtClaimNames.SUB, 1234);
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo("1");
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience"));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(2000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://any.url");
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234");
}
@Test
public void convertWhenUsingCustomConverterThenAllOtherDefaultsAreStillUsed() {
Converter<Object, String> claimConverter = mock(Converter.class);
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
.withDefaults(Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, 1);
source.put(JwtClaimNames.AUD, "audience");
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(2000000000L));
source.put(JwtClaimNames.IAT, new Date(1000000000000L));
source.put(JwtClaimNames.ISS, URI.create("https://any.url"));
source.put(JwtClaimNames.NBF, "1000000000");
source.put(JwtClaimNames.SUB, 2345);
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo("1");
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(Arrays.asList("audience"));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(Instant.ofEpochSecond(2000000000L));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://any.url");
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(Instant.ofEpochSecond(1000000000L));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234");
}
// gh-10135
@Test
public void convertWhenConverterReturnsNullThenClaimIsRemoved() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
.withDefaults(Collections.singletonMap(JwtClaimNames.NBF, (nbfClaimValue) -> null));
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.NBF, Instant.now());
Map<String, Object> target = converter.convert(source);
assertThat(target).doesNotContainKey(JwtClaimNames.NBF);
}
@Test
public void convertWhenClaimValueIsNullThenClaimIsRemoved() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> source = Collections.singletonMap(JwtClaimNames.ISS, null);
Map<String, Object> target = converter.convert(source);
assertThat(target).doesNotContainKey(JwtClaimNames.ISS);
}
@Test
public void convertWhenConverterReturnsValueWhenEntryIsMissingThenEntryIsAdded() {
Converter<Object, String> claimConverter = mock(Converter.class);
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
.withDefaults(Collections.singletonMap("custom-claim", claimConverter));
given(claimConverter.convert(any())).willReturn("custom-value");
Map<String, Object> source = new HashMap<>();
Map<String, Object> target = converter.convert(source);
assertThat(target.get("custom-claim")).isEqualTo("custom-value");
}
@Test
public void convertWhenUsingConstructorThenOnlyConvertersInThatMapAreUsedForConversion() {
Converter<Object, String> claimConverter = mock(Converter.class);
MappedJwtClaimSetConverter converter = new MappedJwtClaimSetConverter(
Collections.singletonMap(JwtClaimNames.SUB, claimConverter));
given(claimConverter.convert(any(Object.class))).willReturn("1234");
Map<String, Object> source = new HashMap<>();
source.put(JwtClaimNames.JTI, new Object());
source.put(JwtClaimNames.AUD, new Object());
source.put(JwtClaimNames.EXP, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.IAT, Instant.ofEpochSecond(1L));
source.put(JwtClaimNames.ISS, new Object());
source.put(JwtClaimNames.NBF, new Object());
source.put(JwtClaimNames.SUB, new Object());
Map<String, Object> target = converter.convert(source);
assertThat(target.get(JwtClaimNames.JTI)).isEqualTo(source.get(JwtClaimNames.JTI));
assertThat(target.get(JwtClaimNames.AUD)).isEqualTo(source.get(JwtClaimNames.AUD));
assertThat(target.get(JwtClaimNames.EXP)).isEqualTo(source.get(JwtClaimNames.EXP));
assertThat(target.get(JwtClaimNames.IAT)).isEqualTo(source.get(JwtClaimNames.IAT));
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo(source.get(JwtClaimNames.ISS));
assertThat(target.get(JwtClaimNames.NBF)).isEqualTo(source.get(JwtClaimNames.NBF));
assertThat(target.get(JwtClaimNames.SUB)).isEqualTo("1234");
}
@Test
public void convertWhenUsingDefaultsThenFailedConversionThrowsIllegalStateException() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> badIssuer = Collections.singletonMap(JwtClaimNames.ISS, "https://badly formed iss");
assertThatIllegalStateException().isThrownBy(() -> converter.convert(badIssuer));
Map<String, Object> badIssuedAt = Collections.singletonMap(JwtClaimNames.IAT, "badly-formed-iat");
assertThatIllegalStateException().isThrownBy(() -> converter.convert(badIssuedAt));
Map<String, Object> badExpiresAt = Collections.singletonMap(JwtClaimNames.EXP, "badly-formed-exp");
assertThatIllegalStateException().isThrownBy(() -> converter.convert(badExpiresAt));
Map<String, Object> badNotBefore = Collections.singletonMap(JwtClaimNames.NBF, "badly-formed-nbf");
assertThatIllegalStateException().isThrownBy(() -> converter.convert(badNotBefore));
}
// gh-6073
@Test
public void convertWhenIssuerIsNotAUriThenConvertsToString() {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> nonUriIssuer = Collections.singletonMap(JwtClaimNames.ISS, "issuer");
Map<String, Object> target = converter.convert(nonUriIssuer);
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("issuer");
}
// gh-6073
@Test
public void convertWhenIssuerIsOfTypeURLThenConvertsToString() throws Exception {
MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
Map<String, Object> issuer = Collections.singletonMap(JwtClaimNames.ISS, new URL("https://issuer"));
Map<String, Object> target = converter.convert(issuer);
assertThat(target.get(JwtClaimNames.ISS)).isEqualTo("https://issuer");
}
@Test
public void constructWhenAnyParameterIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new MappedJwtClaimSetConverter(null));
}
@Test
public void withDefaultsWhenAnyParameterIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> MappedJwtClaimSetConverter.withDefaults(null));
}
}
| 11,033 | 48.927602 | 111 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecodersTests.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.jwt;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
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.web.util.UriComponentsBuilder;
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 JwtDecoders}
*
* @author Josh Cummings
* @author Rafiullah Hamedy
*/
public class JwtDecodersTests {
/**
* Contains those parameters required to construct a JwtDecoder as well as any
* required parameters
*/
// @formatter:off
private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n"
+ " \"authorization_endpoint\": \"https://example.com/o/oauth2/v2/auth\", \n"
+ " \"id_token_signing_alg_values_supported\": [\n"
+ " \"RS256\"\n"
+ " ], \n"
+ " \"issuer\": \"%s\", \n"
+ " \"jwks_uri\": \"%s/.well-known/jwks.json\", \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"
+ " \"subject_types_supported\": [\n"
+ " \"public\"\n"
+ " ], \n"
+ " \"token_endpoint\": \"https://example.com/oauth2/v4/token\"\n"
+ "}";
// @formatter:on
private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"oXJ8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtdF4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAjjDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}";
private static final String ISSUER_MISMATCH = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3Jvbmdpc3N1ZXIiLCJleHAiOjQ2ODcyNTYwNDl9.Ax8LMI6rhB9Pv_CE3kFi1JPuLj9gZycifWrLeDpkObWEEVAsIls9zAhNFyJlG-Oo7up6_mDhZgeRfyKnpSF5GhKJtXJDCzwg0ZDVUE6rS0QadSxsMMGbl7c4y0lG_7TfLX2iWeNJukJj_oSW9KzW4FsBp1BoocWjrreesqQU3fZHbikH-c_Fs2TsAIpHnxflyEzfOFWpJ8D4DtzHXqfvieMwpy42xsPZK3LR84zlasf0Ne1tC_hLHvyHRdAXwn0CMoKxc7-8j0r9Mq8kAzUsPn9If7bMLqGkxUcTPdk5x7opAUajDZx95SXHLmtztNtBa2S6EfPJXuPKG6tM5Wq5Ug";
private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";
private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
private MockWebServer server;
private String issuer;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.issuer = createIssuerFromServer() + "path";
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void issuerWhenResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponse();
JwtDecoder decoder = JwtDecoders.fromOidcIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH))
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponseOidc();
JwtDecoder decoder = JwtDecoders.fromIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH))
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponseOAuth2();
JwtDecoder decoder = JwtDecoders.fromIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH))
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenContainsTrailingSlashThenSuccess() {
this.issuer += "/";
prepareConfigurationResponse();
JwtDecoder jwtDecoder = JwtDecoders.fromOidcIssuerLocation(this.issuer);
assertThat(jwtDecoder).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenOidcFallbackContainsTrailingSlashThenSuccess() {
this.issuer += "/";
prepareConfigurationResponseOidc();
JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(this.issuer);
assertThat(jwtDecoder).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenOAuth2ContainsTrailingSlashThenSuccess() {
this.issuer += "/";
prepareConfigurationResponseOAuth2();
JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(this.issuer);
assertThat(jwtDecoder).isNotNull();
assertThat(this.issuer).endsWith("/");
}
@Test
public void issuerWhenResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponse("{ \"missing_required_keys\" : \"and_values\" }");
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer));
}
@Test
public void issuerWhenOidcFallbackResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponse(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer))
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOidc(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer))
.isInstanceOf(IllegalArgumentException.class)
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOAuth2ResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOAuth2(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer))
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
@Test
public void issuerWhenResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponse("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponse(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOidc(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2RespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOAuth2(
String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> JwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception {
this.server.shutdown();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoders.fromOidcIssuerLocation("https://issuer"));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException()
throws Exception {
this.server.shutdown();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoders.fromIssuerLocation("https://issuer"));
// @formatter:on
}
private void prepareConfigurationResponse() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponse(body);
}
private void prepareConfigurationResponse(String body) {
this.server.enqueue(response(body));
this.server.enqueue(response(JWK_SET));
}
private void prepareConfigurationResponseOidc() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOidc(body);
}
private void prepareConfigurationResponseOidc(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oidc(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponseOAuth2() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOAuth2(body);
}
private void prepareConfigurationResponseOAuth2(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oauth(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponses(Map<String, MockResponse> responses) {
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
// @formatter:off
return Optional.of(request)
.map(RecordedRequest::getRequestUrl)
.map(HttpUrl::toString)
.map(responses::get)
.orElse(new MockResponse().setResponseCode(404));
// @formatter:on
}
};
this.server.setDispatcher(dispatcher);
}
private String createIssuerFromServer() {
return this.server.url("").toString();
}
private String oidc() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(uri.getPath() + OIDC_METADATA_PATH)
.toUriString();
// @formatter:on
}
private String oauth() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(OAUTH_METADATA_PATH + uri.getPath())
.toUriString();
// @formatter:on
}
private String jwks() {
return this.issuer + "/.well-known/jwks.json";
}
private MockResponse response(String body) {
// @formatter:off
return new MockResponse()
.setBody(body)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
public String buildResponseWithMissingJwksUri() throws JsonMappingException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> response = mapper.readValue(DEFAULT_RESPONSE_TEMPLATE,
new TypeReference<Map<String, Object>>() {
});
response.remove("jwks_uri");
return mapper.writeValueAsString(response);
}
}
| 14,319 | 35.070529 | 478 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoderTests.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.jwt;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.util.Base64URL;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.security.oauth2.jose.TestJwks;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
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.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* Tests for {@link NimbusJwtEncoder}.
*
* @author Joe Grandja
*/
public class NimbusJwtEncoderTests {
private List<JWK> jwkList;
private JWKSource<SecurityContext> jwkSource;
private NimbusJwtEncoder jwtEncoder;
@BeforeEach
public void setUp() {
this.jwkList = new ArrayList<>();
this.jwkSource = (jwkSelector, securityContext) -> jwkSelector.select(new JWKSet(this.jwkList));
this.jwtEncoder = new NimbusJwtEncoder(this.jwkSource);
}
@Test
public void constructorWhenJwkSourceNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new NimbusJwtEncoder(null))
.withMessage("jwkSource cannot be null");
}
@Test
public void encodeWhenParametersNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> this.jwtEncoder.encode(null))
.withMessage("parameters cannot be null");
}
@Test
public void encodeWhenClaimsNullThenThrowIllegalArgumentException() {
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, null)))
.withMessage("claims cannot be null");
}
@Test
public void encodeWhenJwkSelectFailedThenThrowJwtEncodingException() throws Exception {
this.jwkSource = mock(JWKSource.class);
this.jwtEncoder = new NimbusJwtEncoder(this.jwkSource);
given(this.jwkSource.get(any(), any())).willThrow(new KeySourceException("key source error"));
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatExceptionOfType(JwtEncodingException.class)
.isThrownBy(() -> this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)))
.withMessageContaining("Failed to select a JWK signing key -> key source error");
}
@Test
public void encodeWhenJwkMultipleSelectedThenThrowJwtEncodingException() throws Exception {
RSAKey rsaJwk = TestJwks.DEFAULT_RSA_JWK;
this.jwkList.add(rsaJwk);
this.jwkList.add(rsaJwk);
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatExceptionOfType(JwtEncodingException.class)
.isThrownBy(() -> this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)))
.withMessageContaining("Found multiple JWK signing keys for algorithm 'RS256'");
}
@Test
public void encodeWhenJwkSelectEmptyThenThrowJwtEncodingException() {
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatExceptionOfType(JwtEncodingException.class)
.isThrownBy(() -> this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)))
.withMessageContaining("Failed to select a JWK signing key");
}
@Test
public void encodeWhenHeadersNotProvidedThenDefaulted() {
// @formatter:off
RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-1")
.build();
this.jwkList.add(rsaJwk);
// @formatter:on
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(SignatureAlgorithm.RS256);
}
@Test
public void encodeWhenJwkSelectWithProvidedKidThenSelected() {
// @formatter:off
RSAKey rsaJwk1 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-1")
.build();
this.jwkList.add(rsaJwk1);
RSAKey rsaJwk2 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-2")
.build();
this.jwkList.add(rsaJwk2);
// @formatter:on
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).keyId(rsaJwk2.getKeyID()).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk2.getKeyID());
}
@Test
public void encodeWhenJwkSelectWithProvidedX5TS256ThenSelected() {
// @formatter:off
RSAKey rsaJwk1 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-1"))
.keyID(null)
.build();
this.jwkList.add(rsaJwk1);
RSAKey rsaJwk2 = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-2"))
.keyID(null)
.build();
this.jwkList.add(rsaJwk2);
// @formatter:on
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256)
.x509SHA256Thumbprint(rsaJwk1.getX509CertSHA256Thumbprint().toString()).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256))
.isEqualTo(rsaJwk1.getX509CertSHA256Thumbprint().toString());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isNull();
}
@Test
public void encodeWhenJwkUseEncryptionThenThrowJwtEncodingException() throws Exception {
// @formatter:off
RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyUse(KeyUse.ENCRYPTION)
.build();
// @formatter:on
this.jwkSource = mock(JWKSource.class);
this.jwtEncoder = new NimbusJwtEncoder(this.jwkSource);
given(this.jwkSource.get(any(), any())).willReturn(Collections.singletonList(rsaJwk));
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
assertThatExceptionOfType(JwtEncodingException.class)
.isThrownBy(() -> this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet)))
.withMessageContaining(
"Failed to create a JWS Signer -> The JWK use must be sig (signature) or unspecified");
}
@Test
public void encodeWhenSuccessThenDecodes() throws Exception {
// @formatter:off
RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-1")
.x509CertSHA256Thumbprint(new Base64URL("x509CertSHA256Thumbprint-1"))
.build();
this.jwkList.add(rsaJwk);
// @formatter:on
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt encodedJws = this.jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.ALG)).isEqualTo(jwsHeader.getAlgorithm());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JKU)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.JWK)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.KID)).isEqualTo(rsaJwk.getKeyID());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5U)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5C)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.X5T_S256))
.isEqualTo(rsaJwk.getX509CertSHA256Thumbprint().toString());
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.TYP)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CTY)).isNull();
assertThat(encodedJws.getHeaders().get(JoseHeaderNames.CRIT)).isNull();
assertThat(encodedJws.getIssuer()).isEqualTo(jwtClaimsSet.getIssuer());
assertThat(encodedJws.getSubject()).isEqualTo(jwtClaimsSet.getSubject());
assertThat(encodedJws.getAudience()).isEqualTo(jwtClaimsSet.getAudience());
assertThat(encodedJws.getExpiresAt()).isEqualTo(jwtClaimsSet.getExpiresAt());
assertThat(encodedJws.getNotBefore()).isEqualTo(jwtClaimsSet.getNotBefore());
assertThat(encodedJws.getIssuedAt()).isEqualTo(jwtClaimsSet.getIssuedAt());
assertThat(encodedJws.getId()).isEqualTo(jwtClaimsSet.getId());
assertThat(encodedJws.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(rsaJwk.toRSAPublicKey()).build();
jwtDecoder.decode(encodedJws.getTokenValue());
}
@Test
public void encodeWhenKeysRotatedThenNewKeyUsed() throws Exception {
TestJWKSource jwkSource = new TestJWKSource();
JWKSource<SecurityContext> jwkSourceDelegate = spy(new JWKSource<SecurityContext>() {
@Override
public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) {
return jwkSource.get(jwkSelector, context);
}
});
NimbusJwtEncoder jwtEncoder = new NimbusJwtEncoder(jwkSourceDelegate);
JwkListResultCaptor jwkListResultCaptor = new JwkListResultCaptor();
willAnswer(jwkListResultCaptor).given(jwkSourceDelegate).get(any(), any());
JwsHeader jwsHeader = JwsHeader.with(SignatureAlgorithm.RS256).build();
JwtClaimsSet jwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
Jwt encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
JWK jwk1 = jwkListResultCaptor.getResult().get(0);
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk1).toRSAPublicKey()).build();
jwtDecoder.decode(encodedJws.getTokenValue());
jwkSource.rotate(); // Simulate key rotation
encodedJws = jwtEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
JWK jwk2 = jwkListResultCaptor.getResult().get(0);
jwtDecoder = NimbusJwtDecoder.withPublicKey(((RSAKey) jwk2).toRSAPublicKey()).build();
jwtDecoder.decode(encodedJws.getTokenValue());
assertThat(jwk1.getKeyID()).isNotEqualTo(jwk2.getKeyID());
}
private static final class JwkListResultCaptor implements Answer<List<JWK>> {
private List<JWK> result;
private List<JWK> getResult() {
return this.result;
}
@SuppressWarnings("unchecked")
@Override
public List<JWK> answer(InvocationOnMock invocationOnMock) throws Throwable {
this.result = (List<JWK>) invocationOnMock.callRealMethod();
return this.result;
}
}
private static final class TestJWKSource implements JWKSource<SecurityContext> {
private int keyId = 1000;
private JWKSet jwkSet;
private TestJWKSource() {
init();
}
@Override
public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) {
return jwkSelector.select(this.jwkSet);
}
private void init() {
// @formatter:off
RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-" + this.keyId++)
.build();
ECKey ecJwk = TestJwks.jwk((ECPublicKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPublic(), (ECPrivateKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPrivate())
.keyID("ec-jwk-" + this.keyId++)
.build();
OctetSequenceKey secretJwk = TestJwks.jwk(TestKeys.DEFAULT_SECRET_KEY)
.keyID("secret-jwk-" + this.keyId++)
.build();
// @formatter:on
this.jwkSet = new JWKSet(Arrays.asList(rsaJwk, ecJwk, secretJwk));
}
private void rotate() {
init();
}
}
}
| 13,432 | 37.711816 | 143 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtIssuerValidatorTests.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.jwt;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Josh Cummings
* @since 5.1
*/
public class JwtIssuerValidatorTests {
private static final String ISSUER = "https://issuer";
private final JwtIssuerValidator validator = new JwtIssuerValidator(ISSUER);
@Test
public void validateWhenIssuerMatchesThenReturnsSuccess() {
Jwt jwt = TestJwts.jwt().claim("iss", ISSUER).build();
// @formatter:off
assertThat(this.validator.validate(jwt))
.isEqualTo(OAuth2TokenValidatorResult.success());
// @formatter:on
}
@Test
public void validateWhenIssuerUrlMatchesThenReturnsSuccess() throws MalformedURLException {
Jwt jwt = TestJwts.jwt().claim("iss", new URL(ISSUER)).build();
assertThat(this.validator.validate(jwt)).isEqualTo(OAuth2TokenValidatorResult.success());
}
@Test
public void validateWhenIssuerMismatchesThenReturnsError() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "https://other").build();
OAuth2TokenValidatorResult result = this.validator.validate(jwt);
assertThat(result.getErrors()).isNotEmpty();
}
@Test
public void validateWhenIssuerUrlMismatchesThenReturnsError() throws MalformedURLException {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, new URL("https://other")).build();
OAuth2TokenValidatorResult result = this.validator.validate(jwt);
assertThat(result.getErrors()).isNotEmpty();
}
@Test
public void validateWhenJwtHasNoIssuerThenReturnsError() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.AUD, "https://aud").build();
OAuth2TokenValidatorResult result = this.validator.validate(jwt);
assertThat(result.getErrors()).isNotEmpty();
}
// gh-6073
@Test
public void validateWhenIssuerMatchesAndIsNotAUriThenReturnsSuccess() {
Jwt jwt = TestJwts.jwt().claim(JwtClaimNames.ISS, "issuer").build();
JwtIssuerValidator validator = new JwtIssuerValidator("issuer");
// @formatter:off
assertThat(validator.validate(jwt))
.isEqualTo(OAuth2TokenValidatorResult.success());
// @formatter:on
}
@Test
public void validateWhenJwtIsNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.validator.validate(null));
// @formatter:on
}
@Test
public void constructorWhenNullIssuerIsGivenThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new JwtIssuerValidator(null));
// @formatter:on
}
}
| 3,385 | 30.943396 | 93 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/TestJwts.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.jwt;
import java.time.Instant;
import java.util.Arrays;
public final class TestJwts {
private TestJwts() {
}
public static Jwt.Builder jwt() {
// @formatter:off
return Jwt.withTokenValue("token")
.header("alg", "none")
.audience(Arrays.asList("https://audience.example.org"))
.expiresAt(Instant.MAX)
.issuedAt(Instant.MIN)
.issuer("https://issuer.example.org")
.jti("jti")
.notBefore(Instant.MIN)
.subject("mock-test-subject");
// @formatter:on
}
public static Jwt user() {
// @formatter:off
return jwt()
.claim("sub", "mock-test-subject")
.build();
// @formatter:on
}
}
| 1,302 | 25.06 | 75 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoderTests.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.jwt;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.crypto.SecretKey;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.BadJWTException;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTProcessor;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.web.client.RestClientException;
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.assertj.core.api.Assertions.assertThatIllegalStateException;
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;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests for {@link NimbusJwtDecoder}
*
* @author Josh Cummings
* @author Joe Grandja
* @author Mykyta Bezverkhyi
*/
public class NimbusJwtDecoderTests {
private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"oXJ8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtdF4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAjjDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}";
private static final String NEW_KID_JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"kid\":\"two\",\"n\":\"ra9UJw4I0fCHuOqr1xWJsh-qcVeZWtKEU3uoqq1sAg5fG67dujNCm_Q16yuO0ZdDiU0vlJkbc_MXFAvm4ZxdJ_qR7PAneV-BOGNtLpSaiPclscCy3m7zjRWkaqwt9ZZEsdK5UqXyPlBpcYhNKsmnQGjnX4sYb7d8b2jSCM_qto48-6451rbyEhXXywtFy_JqtTpbsw_IIdQHMr1O-MdSjsQxX9kkvZwPU8LsC-CcqlcsZ7mnpOhmIXaf4tbRwAaluXwYft0yykFsp8e5C4t9mMs9Vu8AB5gT8o-D_ovXd2qh4k3ejzVpYLtzD4nbfvPJA_TXmjhn-9GOPAqkzfON2Q\"}]}";
private static final String MALFORMED_JWK_SET = "malformed";
private static final String SIGNED_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJzY3AiOlsibWVzc2FnZTpyZWFkIl0sImV4cCI6NDY4Mzg5Nzc3Nn0.LtMVtIiRIwSyc3aX35Zl0JVwLTcQZAB3dyBOMHNaHCKUljwMrf20a_gT79LfhjDzE_fUVUmFiAO32W1vFnYpZSVaMDUgeIOIOpxfoe9shj_uYenAwIS-_UxqGVIJiJoXNZh_MK80ShNpvsQwamxWEEOAMBtpWNiVYNDMdfgho9n3o5_Z7Gjy8RLBo1tbDREbO9kTFwGIxm_EYpezmRCRq4w1DdS6UDW321hkwMxPnCMSWOvp-hRpmgY2yjzLgPJ6Aucmg9TJ8jloAP1DjJoF1gRR7NTAk8LOGkSjTzVYDYMbCF51YdpojhItSk80YzXiEsv1mTz4oMM49jXBmfXFMA";
private static final String NEW_KID_SIGNED_JWT = "eyJraWQiOiJ0d28iLCJhbGciOiJSUzI1NiJ9.eyJleHAiOjIxMzMyNzg4MjV9.DQJn_qg0HfZ_sjlx9MJkdCjkp9t-0zOj3FzVp_UPzx6RCcBb8Jk373dNgcyfOP5CS29wv5gKX6geWEDj5cgqcJdTS53zqOaLETdNnKACd056SkPqgTLJv12gdJx7tr5WbBqRB9Y0ce96vbH6wwQGfqU_1Lz1RhZ7ZZuvIuWLp75ujld7dOshScg728Z9BQsiFOH_yFp09XraO15spwTXp9RO5TJRUSLih-5V3sdxHa5rPTm6by7me8I_l4iMJN81Z95_O7sbLeYH-4zZ-3T49uPyAC5suEOd-P5aFP89zPKh9Y3Uviu2OyvpUuXmpUjTtdAKf3p96dOEeLJvT3hkSg";
private static final String MALFORMED_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJuYmYiOnt9LCJleHAiOjQ2ODQyMjUwODd9.guoQvujdWvd3xw7FYQEn4D6-gzM_WqFvXdmvAUNSLbxG7fv2_LLCNujPdrBHJoYPbOwS1BGNxIKQWS1tylvqzmr1RohQ-RZ2iAM1HYQzboUlkoMkcd8ENM__ELqho8aNYBfqwkNdUOyBFoy7Syu_w2SoJADw2RTjnesKO6CVVa05bW118pDS4xWxqC4s7fnBjmZoTn4uQ-Kt9YSQZQk8YQxkJSiyanozzgyfgXULA6mPu1pTNU3FVFaK1i1av_xtH_zAPgb647ZeaNe4nahgqC5h8nhOlm8W2dndXbwAt29nd2ZWBsru_QwZz83XSKLhTPFz-mPBByZZDsyBbIHf9A";
private static final String UNSIGNED_JWT = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJleHAiOi0yMDMzMjI0OTcsImp0aSI6IjEyMyIsInR5cCI6IkpXVCJ9.";
private static final String EMPTY_EXP_CLAIM_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJhdWRpZW5jZSJ9.D1eT0jpBEpuh74p-YT-uF81Z7rkVqIpUtJ5hWWFiVShZ9s8NIntK4Q1GlvlziiySSaVYaXtpTmDB3c8r-Z5Mj4ibihiueCSq7jaPD3sA8IMQKL-L6Uol8MSD_lSFE2n3fVBTxFeaejBKfZsDxnhzgpy8g7PncR47w8NHs-7tKO4qw7G_SV3hkNpDNoqZTfMImxyWEebgKM2pJAhN4das2CO1KAjYMfEByLcgYncE8fzdYPJhMFo2XRRSQABoeUBuKSAwIntBaOGvcb-qII_Hefc5U0cmpNItG75F2XfX803plKI4FFpAxJsbPKWSQmhs6bZOrhx0x74pY5LS3ghmJw";
private static final String JWK_SET_URI = "https://issuer/.well-known/jwks.json";
private static final String RS512_SIGNED_JWT = "eyJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJleHAiOjE5NzQzMjYxMTl9.LKAx-60EBfD7jC1jb1eKcjO4uLvf3ssISV-8tN-qp7gAjSvKvj4YA9-V2mIb6jcS1X_xGmNy6EIimZXpWaBR3nJmeu-jpe85u4WaW2Ztr8ecAi-dTO7ZozwdtljKuBKKvj4u1nF70zyCNl15AozSG0W1ASrjUuWrJtfyDG6WoZ8VfNMuhtU-xUYUFvscmeZKUYQcJ1KS-oV5tHeF8aNiwQoiPC_9KXCOZtNEJFdq6-uzFdHxvOP2yex5Gbmg5hXonauIFXG2ZPPGdXzm-5xkhBpgM8U7A_6wb3So8wBvLYYm2245QUump63AJRAy8tQpwt4n9MvQxQgS3z9R-NK92A";
private static final String RS256_SIGNED_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJleHAiOjE5NzQzMjYzMzl9.CT-H2OWEqmSs1NWmnta5ealLFvM8OlbQTjGhfRcKLNxrTrzsOkqBJl-AN3k16BQU7mS32o744TiiZ29NcDlxPsr1MqTlN86-dobPiuNIDLp3A1bOVdXMcVFuMYkrNv0yW0tGS9OjEqsCCuZDkZ1by6AhsHLbGwRY-6AQdcRouZygGpOQu1hNun5j8q5DpSTY4AXKARIFlF-O3OpVbPJ0ebr3Ki-i3U9p_55H0e4-wx2bqcApWlqgofl1I8NKWacbhZgn81iibup2W7E0CzCzh71u1Mcy3xk1sYePx-dwcxJnHmxJReBBWjJZEAeCrkbnn_OCuo2fA-EQyNJtlN5F2w";
private static final String VERIFY_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq4yKxb6SNePdDmQi9xFCrP6QvHosErQzryknQTTTffs0t3cy3Er3lIceuhZ7yQNSCDfPFqG8GoyoKhuChRiA5D+J2ab7bqTa1QJKfnCyERoscftgN2fXPHjHoiKbpGV2tMVw8mXl//tePOAiKbMJaBUnlAvJgkk1rVm08dSwpLC1sr2M19euf9jwnRGkMRZuhp9iCPgECRke5T8Ixpv0uQjSmGHnWUKTFlbj8sM83suROR1Ue64JSGScANc5vk3huJ/J97qTC+K2oKj6L8d9O8dpc4obijEOJwpydNvTYDgbiivYeSB00KS9jlBkQ5B2QqLvLVEygDl3dp59nGx6YQIDAQAB";
private static final MediaType APPLICATION_JWK_SET_JSON = new MediaType("application", "jwk-set+json");
private static KeyFactory kf;
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(withoutSigning());
@BeforeAll
public static void keyFactory() throws NoSuchAlgorithmException {
kf = KeyFactory.getInstance("RSA");
}
@Test
public void constructorWhenJwtProcessorIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusJwtDecoder(null));
// @formatter:on
}
@Test
public void setClaimSetConverterWhenIsNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.jwtDecoder.setClaimSetConverter(null));
// @formatter:on
}
@Test
public void setJwtValidatorWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.jwtDecoder.setJwtValidator(null));
// @formatter:on
}
@Test
public void decodeWhenJwtInvalidThenThrowJwtException() {
// @formatter:off
assertThatExceptionOfType(JwtException.class)
.isThrownBy(() -> this.jwtDecoder.decode("invalid"));
// @formatter:on
}
// gh-5168
@Test
public void decodeWhenExpClaimNullThenDoesNotThrowException() {
this.jwtDecoder.decode(EMPTY_EXP_CLAIM_JWT);
}
@Test
public void decodeWhenIatClaimNullThenDoesNotThrowException() {
this.jwtDecoder.decode(SIGNED_JWT);
}
// gh-5457
@Test
public void decodeWhenPlainJwtThenExceptionDoesNotMentionClass() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.jwtDecoder.decode(UNSIGNED_JWT))
.withMessageContaining("Unsupported algorithm of none");
// @formatter:on
}
@Test
public void decodeWhenJwtIsMalformedThenReturnsStockException() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.jwtDecoder.decode(MALFORMED_JWT))
.withMessage("An error occurred while attempting to decode the Jwt: Malformed payload");
// @formatter:on
}
@Test
public void decodeWhenJwtFailsValidationThenReturnsCorrespondingErrorMessage() {
OAuth2Error failure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(failure));
this.jwtDecoder.setJwtValidator(jwtValidator);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT))
.withMessageContaining("mock-description");
// @formatter:on
}
@Test
public void decodeWhenJwtValidationHasTwoErrorsThenJwtExceptionMessageShowsFirstError() {
OAuth2Error firstFailure = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error secondFailure = new OAuth2Error("another-error", "another-description", "another-uri");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(firstFailure, secondFailure);
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
this.jwtDecoder.setJwtValidator(jwtValidator);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT))
.withMessageContaining("mock-description")
.satisfies((ex) -> assertThat(ex)
.hasFieldOrPropertyWithValue("errors", Arrays.asList(firstFailure, secondFailure))
);
// @formatter:on
}
@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
this.jwtDecoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT))
.withMessageContaining("mock-description");
// @formatter:on
}
@Test
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
this.jwtDecoder.setClaimSetConverter(claimSetConverter);
Jwt jwt = this.jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.getClaims().size()).isEqualTo(1);
assertThat(jwt.getClaims().get("custom")).isEqualTo("value");
}
// gh-7885
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.jwtDecoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.jwtDecoder.decode(SIGNED_JWT));
// @formatter:on
}
@Test
public void decodeWhenSignedThenOk() {
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(withSigning(JWK_SET));
Jwt jwt = jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.hasClaim(JwtClaimNames.EXP)).isNotNull();
}
@Test
public void decodeWhenJwkResponseIsMalformedThenReturnsStockException() {
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(withSigning(MALFORMED_JWK_SET));
// @formatter:off
assertThatExceptionOfType(JwtException.class)
.isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT))
.isNotInstanceOf(BadJwtException.class)
.withMessage("An error occurred while attempting to decode the Jwt: Malformed Jwk set");
// @formatter:on
}
@Test
public void decodeWhenJwkEndpointIsUnresponsiveThenReturnsJwtException() throws Exception {
try (MockWebServer server = new MockWebServer()) {
String jwkSetUri = server.url("/.well-known/jwks.json").toString();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
server.shutdown();
// @formatter:off
assertThatExceptionOfType(JwtException.class)
.isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT))
.isNotInstanceOf(BadJwtException.class)
.withMessageContaining("An error occurred while attempting to decode the Jwt");
// @formatter:on
}
}
@Test
public void decodeWhenJwkEndpointIsUnresponsiveAndCacheIsConfiguredThenReturnsJwtException() throws Exception {
try (MockWebServer server = new MockWebServer()) {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
String jwkSetUri = server.url("/.well-known/jwks.json").toString();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).cache(cache).build();
server.shutdown();
// @formatter:off
assertThatExceptionOfType(JwtException.class)
.isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT))
.isNotInstanceOf(BadJwtException.class)
.withMessageContaining("An error occurred while attempting to decode the Jwt");
// @formatter:on
}
}
@Test
public void decodeWhenIssuerLocationThenOk() {
String issuer = "https://example.org/issuer";
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), any(ParameterizedTypeReference.class))).willReturn(
new ResponseEntity<>(Map.of("issuer", issuer, "jwks_uri", issuer + "/jwks"), HttpStatus.OK));
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
JwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(restOperations).build();
Jwt jwt = jwtDecoder.decode(SIGNED_JWT);
assertThat(jwt.hasClaim(JwtClaimNames.EXP)).isNotNull();
}
@Test
public void withJwkSetUriWhenNullOrEmptyThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(null));
// @formatter:on
}
@Test
public void jwsAlgorithmWhenNullThenThrowsException() {
NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> builder.jwsAlgorithm(null));
// @formatter:on
}
@Test
public void restOperationsWhenNullThenThrowsException() {
NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> builder.restOperations(null));
// @formatter:on
}
@Test
public void cacheWhenNullThenThrowsException() {
NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder builder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> builder.cache(null));
// @formatter:on
}
@Test
public void withPublicKeyWhenNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withPublicKey(null));
// @formatter:on
}
@Test
public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() {
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> NimbusJwtDecoder.withPublicKey(key())
.signatureAlgorithm(SignatureAlgorithm.ES256)
.build()
);
// @formatter:on
}
@Test
public void decodeWhenUsingPublicKeyThenSuccessfullyDecodes() throws Exception {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).build();
// @formatter:off
assertThat(decoder.decode(RS256_SIGNED_JWT))
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
@Test
public void decodeWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Exception {
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key())
.signatureAlgorithm(SignatureAlgorithm.RS512)
.build();
assertThat(decoder.decode(RS512_SIGNED_JWT))
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
// gh-7049
@Test
public void decodeWhenUsingPublicKeyWithKidThenStillUsesKey() throws Exception {
RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY;
RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY;
// @formatter:off
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
.keyID("one")
.build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder
.withPublicKey(publicKey)
.signatureAlgorithm(SignatureAlgorithm.RS256)
.build();
assertThat(decoder.decode(signedJwt.serialize()))
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
@Test
public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception {
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(key()).signatureAlgorithm(SignatureAlgorithm.RS512)
.build();
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(RS256_SIGNED_JWT));
// @formatter:on
}
// gh-8730
@Test
public void withPublicKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception {
RSAPublicKey publicKey = TestKeys.DEFAULT_PUBLIC_KEY;
RSAPrivateKey privateKey = TestKeys.DEFAULT_PRIVATE_KEY;
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(new JOSEObjectType("JWS")).build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
SignedJWT signedJwt = signedJwt(privateKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withPublicKey(publicKey)
.signatureAlgorithm(SignatureAlgorithm.RS256)
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
// @formatter:on
assertThat(decoder.decode(signedJwt.serialize()).hasClaim(JwtClaimNames.EXP)).isNotNull();
}
@Test
public void withPublicKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withPublicKey(key()).jwtProcessorCustomizer(null))
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
@Test
public void withSecretKeyWhenNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withSecretKey(null))
.withMessage("secretKey cannot be null");
// @formatter:on
}
@Test
public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).macAlgorithm(null))
.withMessage("macAlgorithm cannot be null");
// @formatter:on
}
@Test
public void decodeWhenUsingSecretKeyThenSuccessfullyDecodes() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
// @formatter:off
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(macAlgorithm)
.build();
assertThat(decoder.decode(signedJWT.serialize()))
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
@Test
public void decodeWhenUsingSecretKeyAndIncorrectAlgorithmThenThrowsJwtException() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
// @formatter:off
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS512)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(signedJWT.serialize()));
// @formatter:on
}
// gh-7056
@Test
public void decodeWhenUsingSecretKeyWithKidThenStillUsesKey() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
.keyID("one")
.build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS256)
.build();
assertThat(decoder.decode(signedJwt.serialize()))
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
// gh-8730
@Test
public void withSecretKeyWhenUsingCustomTypeHeaderThenSuccessfullyDecodes() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
.type(new JOSEObjectType("JWS"))
.build();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJwt = signedJwt(secretKey, header, claimsSet);
// @formatter:off
NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS256)
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
// @formatter:on
assertThat(decoder.decode(signedJwt.serialize()).hasClaim(JwtClaimNames.EXP)).isNotNull();
}
@Test
public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withSecretKey(secretKey).jwtProcessorCustomizer(null))
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.jwsKeySelector(jwkSource);
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
// @formatter:off
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.jwsAlgorithm(SignatureAlgorithm.RS512)
.jwsKeySelector(jwkSource);
// @formatter:on
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsVerificationKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
// @formatter:off
JWSKeySelector<SecurityContext> jwsKeySelector = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.jwsAlgorithm(SignatureAlgorithm.RS256)
.jwsAlgorithm(SignatureAlgorithm.RS512)
.jwsKeySelector(jwkSource);
// @formatter:on
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
// gh-7290
@Test
public void decodeWhenJwkSetRequestedThenAcceptHeaderJsonAndJwkSetJson() {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
JWTProcessor<SecurityContext> processor = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.processor();
// @formatter:on
NimbusJwtDecoder jwtDecoder = new NimbusJwtDecoder(processor);
jwtDecoder.decode(SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
@Test
public void decodeWhenCacheThenStoreRetrievedJwkSetToCache() {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.cache(cache)
.build();
// @formatter:on
jwtDecoder.decode(SIGNED_JWT);
assertThat(cache.get(JWK_SET_URI, String.class)).isEqualTo(JWK_SET);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
List<MediaType> acceptHeader = requestEntityCaptor.getValue().getHeaders().getAccept();
assertThat(acceptHeader).contains(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON);
}
@Test
public void decodeWhenCacheStoredThenAbleToRetrieveJwkSetFromCache() {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder1 = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.cache(cache)
.build();
// @formatter:on
jwtDecoder1.decode(SIGNED_JWT);
assertThat(cache.get(JWK_SET_URI, String.class)).isEqualTo(JWK_SET);
verify(restOperations).exchange(any(RequestEntity.class), eq(String.class));
// @formatter:off
NimbusJwtDecoder jwtDecoder2 = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.cache(cache)
.build();
// @formatter:on
jwtDecoder2.decode(SIGNED_JWT);
verifyNoMoreInteractions(restOperations);
}
// gh-11621
@Test
public void decodeWhenCacheThenRetrieveFromCache() throws Exception {
RestOperations restOperations = mock(RestOperations.class);
Cache cache = mock(Cache.class);
given(cache.get(eq(JWK_SET_URI), eq(String.class))).willReturn(JWK_SET);
given(cache.get(eq(JWK_SET_URI))).willReturn(mock(Cache.ValueWrapper.class));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.cache(cache)
.restOperations(restOperations)
.build();
// @formatter:on
jwtDecoder.decode(SIGNED_JWT);
verify(cache).get(eq(JWK_SET_URI), eq(String.class));
verify(cache, times(2)).get(eq(JWK_SET_URI));
verifyNoMoreInteractions(cache);
verifyNoInteractions(restOperations);
}
// gh-11621
@Test
public void decodeWhenCacheAndUnknownKidShouldTriggerFetchOfJwkSet() throws JOSEException {
RestOperations restOperations = mock(RestOperations.class);
Cache cache = mock(Cache.class);
given(cache.get(eq(JWK_SET_URI), eq(String.class))).willReturn(JWK_SET);
given(cache.get(eq(JWK_SET_URI))).willReturn(new SimpleValueWrapper(JWK_SET));
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(NEW_KID_JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.cache(cache)
.restOperations(restOperations)
.build();
// @formatter:on
// Decode JWT with new KID
jwtDecoder.decode(NEW_KID_SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
assertThat(requestEntityCaptor.getValue().getHeaders().getAccept()).contains(MediaType.APPLICATION_JSON,
APPLICATION_JWK_SET_JSON);
}
// gh-11621
@Test
public void decodeWithoutCacheSpecifiedAndUnknownKidShouldTriggerFetchOfJwkSet() throws JOSEException {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(
new ResponseEntity<>(JWK_SET, HttpStatus.OK), new ResponseEntity<>(NEW_KID_JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.build();
// @formatter:on
jwtDecoder.decode(SIGNED_JWT);
// Decode JWT with new KID
jwtDecoder.decode(NEW_KID_SIGNED_JWT);
ArgumentCaptor<RequestEntity> requestEntityCaptor = ArgumentCaptor.forClass(RequestEntity.class);
verify(restOperations, times(2)).exchange(requestEntityCaptor.capture(), eq(String.class));
verifyNoMoreInteractions(restOperations);
List<RequestEntity> requestEntities = requestEntityCaptor.getAllValues();
assertThat(requestEntities.get(0).getHeaders().getAccept()).contains(MediaType.APPLICATION_JSON,
APPLICATION_JWK_SET_JSON);
assertThat(requestEntities.get(1).getHeaders().getAccept()).contains(MediaType.APPLICATION_JSON,
APPLICATION_JWK_SET_JSON);
}
@Test
public void decodeWhenCacheIsConfiguredAndValueLoaderErrorsThenThrowsJwtException() {
Cache cache = new ConcurrentMapCache("test-jwk-set-cache");
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willThrow(new RestClientException("Cannot retrieve JWK Set"));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.cache(cache)
.build();
assertThatExceptionOfType(JwtException.class)
.isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT))
.isNotInstanceOf(BadJwtException.class)
.withMessageContaining("An error occurred while attempting to decode the Jwt");
// @formatter:on
}
// gh-11621
@Test
public void decodeWhenCacheIsConfiguredAndParseFailsOnCachedValueThenExceptionIgnored() {
RestOperations restOperations = mock(RestOperations.class);
Cache cache = mock(Cache.class);
given(cache.get(eq(JWK_SET_URI), eq(String.class))).willReturn(JWK_SET);
given(cache.get(eq(JWK_SET_URI))).willReturn(mock(Cache.ValueWrapper.class));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.cache(cache)
.restOperations(restOperations)
.build();
// @formatter:on
jwtDecoder.decode(SIGNED_JWT);
verify(cache).get(eq(JWK_SET_URI), eq(String.class));
verify(cache, times(2)).get(eq(JWK_SET_URI));
verifyNoMoreInteractions(cache);
verifyNoInteractions(restOperations);
}
// gh-8730
@Test
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(JWK_SET, HttpStatus.OK));
// @formatter:off
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> jwtDecoder.decode(SIGNED_JWT))
.withMessageContaining("An error occurred while attempting to decode the Jwt: "
+ "Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
@Test
public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI).jwtProcessorCustomizer(null))
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
private RSAPublicKey key() throws InvalidKeySpecException {
byte[] decoded = Base64.getDecoder().decode(VERIFY_KEY.getBytes());
EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
return (RSAPublicKey) kf.generatePublic(spec);
}
private SignedJWT signedJwt(SecretKey secretKey, MacAlgorithm jwsAlgorithm, JWTClaimsSet claimsSet)
throws Exception {
return signedJwt(secretKey, new JWSHeader(JWSAlgorithm.parse(jwsAlgorithm.getName())), claimsSet);
}
private SignedJWT signedJwt(SecretKey secretKey, JWSHeader header, JWTClaimsSet claimsSet) throws Exception {
JWSSigner signer = new MACSigner(secretKey);
return signedJwt(signer, header, claimsSet);
}
private SignedJWT signedJwt(PrivateKey privateKey, JWSHeader header, JWTClaimsSet claimsSet) throws Exception {
JWSSigner signer = new RSASSASigner(privateKey);
return signedJwt(signer, header, claimsSet);
}
private SignedJWT signedJwt(JWSSigner signer, JWSHeader header, JWTClaimsSet claimsSet) throws Exception {
SignedJWT signedJWT = new SignedJWT(header, claimsSet);
signedJWT.sign(signer);
return signedJWT;
}
private static JWTProcessor<SecurityContext> withSigning(String jwkResponse) {
RestOperations restOperations = mock(RestOperations.class);
given(restOperations.exchange(any(RequestEntity.class), eq(String.class)))
.willReturn(new ResponseEntity<>(jwkResponse, HttpStatus.OK));
// @formatter:off
return NimbusJwtDecoder.withJwkSetUri(JWK_SET_URI)
.restOperations(restOperations)
.processor();
// @formatter:on
}
private static JWTProcessor<SecurityContext> withoutSigning() {
return new MockJwtProcessor();
}
private static class MockJwtProcessor extends DefaultJWTProcessor<SecurityContext> {
@Override
public JWTClaimsSet process(SignedJWT signedJWT, SecurityContext context) throws BadJOSEException {
try {
return signedJWT.getJWTClaimsSet();
}
catch (ParseException ex) {
// Payload not a JSON object
throw new BadJWTException(ex.getMessage(), ex);
}
}
}
}
| 38,521 | 42.186099 | 492 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTests.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.jwt;
import java.time.Instant;
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 org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link Jwt}.
*
* @author Joe Grandja
*/
public class JwtTests {
private static final String ISS_CLAIM = "iss";
private static final String SUB_CLAIM = "sub";
private static final String AUD_CLAIM = "aud";
private static final String EXP_CLAIM = "exp";
private static final String NBF_CLAIM = "nbf";
private static final String IAT_CLAIM = "iat";
private static final String JTI_CLAIM = "jti";
private static final String ISS_VALUE = "https://provider.com";
private static final String SUB_VALUE = "subject1";
private static final List<String> AUD_VALUE = Arrays.asList("aud1", "aud2");
private static final long EXP_VALUE = Instant.now().plusSeconds(60).toEpochMilli();
private static final long NBF_VALUE = Instant.now().plusSeconds(5).toEpochMilli();
private static final long IAT_VALUE = Instant.now().toEpochMilli();
private static final String JTI_VALUE = "jwt-id-1";
private static final Map<String, Object> HEADERS;
private static final Map<String, Object> CLAIMS;
private static final String JWT_TOKEN_VALUE = "jwt-token-value";
static {
HEADERS = new HashMap<>();
HEADERS.put("alg", JwsAlgorithms.RS256);
CLAIMS = new HashMap<>();
CLAIMS.put(ISS_CLAIM, ISS_VALUE);
CLAIMS.put(SUB_CLAIM, SUB_VALUE);
CLAIMS.put(AUD_CLAIM, AUD_VALUE);
CLAIMS.put(EXP_CLAIM, EXP_VALUE);
CLAIMS.put(NBF_CLAIM, NBF_VALUE);
CLAIMS.put(IAT_CLAIM, IAT_VALUE);
CLAIMS.put(JTI_CLAIM, JTI_VALUE);
}
@Test
public void constructorWhenTokenValueIsNullThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(
() -> new Jwt(null, Instant.ofEpochMilli(IAT_VALUE), Instant.ofEpochMilli(EXP_VALUE), HEADERS, CLAIMS));
}
@Test
public void constructorWhenHeadersIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new Jwt(JWT_TOKEN_VALUE, Instant.ofEpochMilli(IAT_VALUE),
Instant.ofEpochMilli(EXP_VALUE), Collections.emptyMap(), CLAIMS));
}
@Test
public void constructorWhenClaimsIsEmptyThenThrowIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new Jwt(JWT_TOKEN_VALUE, Instant.ofEpochMilli(IAT_VALUE),
Instant.ofEpochMilli(EXP_VALUE), HEADERS, Collections.emptyMap()));
}
@Test
public void constructorWhenParametersProvidedAndValidThenCreated() {
Jwt jwt = new Jwt(JWT_TOKEN_VALUE, Instant.ofEpochMilli(IAT_VALUE), Instant.ofEpochMilli(EXP_VALUE), HEADERS,
CLAIMS);
assertThat(jwt.getTokenValue()).isEqualTo(JWT_TOKEN_VALUE);
assertThat(jwt.getHeaders()).isEqualTo(HEADERS);
assertThat(jwt.getClaims()).isEqualTo(CLAIMS);
assertThat(jwt.getIssuer().toString()).isEqualTo(ISS_VALUE);
assertThat(jwt.getSubject()).isEqualTo(SUB_VALUE);
assertThat(jwt.getAudience()).isEqualTo(AUD_VALUE);
assertThat(jwt.getExpiresAt().toEpochMilli()).isEqualTo(EXP_VALUE);
assertThat(jwt.getNotBefore().getEpochSecond()).isEqualTo(NBF_VALUE);
assertThat(jwt.getIssuedAt().toEpochMilli()).isEqualTo(IAT_VALUE);
assertThat(jwt.getId()).isEqualTo(JTI_VALUE);
}
}
| 4,132 | 33.157025 | 113 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtClaimsSetTests.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.jwt;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link JwtClaimsSet}.
*
* @author Joe Grandja
*/
public class JwtClaimsSetTests {
@Test
public void buildWhenClaimsEmptyThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwtClaimsSet.builder().build())
.withMessage("claims cannot be empty");
}
@Test
public void buildWhenAllClaimsProvidedThenAllClaimsAreSet() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
// @formatter:off
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.builder()
.issuer(expectedJwtClaimsSet.getIssuer().toExternalForm())
.subject(expectedJwtClaimsSet.getSubject())
.audience(expectedJwtClaimsSet.getAudience())
.issuedAt(expectedJwtClaimsSet.getIssuedAt())
.notBefore(expectedJwtClaimsSet.getNotBefore())
.expiresAt(expectedJwtClaimsSet.getExpiresAt())
.id(expectedJwtClaimsSet.getId())
.claims((claims) -> claims.put("custom-claim-name", "custom-claim-value"))
.build();
// @formatter:on
assertThat(jwtClaimsSet.getIssuer()).isEqualTo(expectedJwtClaimsSet.getIssuer());
assertThat(jwtClaimsSet.getSubject()).isEqualTo(expectedJwtClaimsSet.getSubject());
assertThat(jwtClaimsSet.getAudience()).isEqualTo(expectedJwtClaimsSet.getAudience());
assertThat(jwtClaimsSet.getIssuedAt()).isEqualTo(expectedJwtClaimsSet.getIssuedAt());
assertThat(jwtClaimsSet.getNotBefore()).isEqualTo(expectedJwtClaimsSet.getNotBefore());
assertThat(jwtClaimsSet.getExpiresAt()).isEqualTo(expectedJwtClaimsSet.getExpiresAt());
assertThat(jwtClaimsSet.getId()).isEqualTo(expectedJwtClaimsSet.getId());
assertThat(jwtClaimsSet.<String>getClaim("custom-claim-name")).isEqualTo("custom-claim-value");
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void fromWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwtClaimsSet.from(null))
.withMessage("claims cannot be null");
}
@Test
public void fromWhenClaimsProvidedThenCopied() {
JwtClaimsSet expectedJwtClaimsSet = TestJwtClaimsSets.jwtClaimsSet().build();
JwtClaimsSet jwtClaimsSet = JwtClaimsSet.from(expectedJwtClaimsSet).build();
assertThat(jwtClaimsSet.getClaims()).isEqualTo(expectedJwtClaimsSet.getClaims());
}
@Test
public void claimWhenNameNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwtClaimsSet.builder().claim(null, "value")).withMessage("name cannot be empty");
}
@Test
public void claimWhenValueNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwtClaimsSet.builder().claim("name", null)).withMessage("value cannot be null");
}
}
| 3,668 | 39.318681 | 108 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtDecoderProviderConfigurationUtilsTests.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.jwt;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import com.nimbusds.jose.Algorithm;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.util.Base64URL;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
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.ArgumentMatchers.isNull;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.mock;
public class JwtDecoderProviderConfigurationUtilsTests {
@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesAlgorithmThenUses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE)
.algorithm(JWSAlgorithm.RS384).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS384);
}
@Test
public void getSignatureAlgorithmsWhenJwkSetIsEmptyThenIllegalArgumentException() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.emptyList());
assertThatIllegalArgumentException()
.isThrownBy(() -> JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource));
}
@Test
public void getSignatureAlgorithmsWhenJwkSetSpecifiesFamilyThenUses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
// Test parameters are from Anders Rundgren, public only
ECKey ecKey = new ECKey.Builder(Curve.P_256, new Base64URL("3l2Da_flYc-AuUTm2QzxgyvJxYM_2TeB9DMlwz7j1PE"),
new Base64URL("-kjT7Wrfhwsi9SG6H4UXiyUiVE9GHCLauslksZ3-_t0")).keyUse(KeyUse.SIGNATURE).build();
RSAKey rsaKey = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.ENCRYPTION).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Arrays.asList(ecKey, rsaKey));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).contains(SignatureAlgorithm.ES256, SignatureAlgorithm.ES384, SignatureAlgorithm.ES512);
}
// gh-9651
@Test
public void getSignatureAlgorithmsWhenAlgorithmThenParses() throws Exception {
JWKSource<SecurityContext> jwkSource = mock(JWKSource.class);
RSAKey key = new RSAKey.Builder(TestKeys.DEFAULT_PUBLIC_KEY).keyUse(KeyUse.SIGNATURE)
.algorithm(new Algorithm(JwsAlgorithms.RS256)).build();
given(jwkSource.get(any(JWKSelector.class), isNull())).willReturn(Collections.singletonList(key));
Set<SignatureAlgorithm> algorithms = JwtDecoderProviderConfigurationUtils.getSignatureAlgorithms(jwkSource);
assertThat(algorithms).containsOnly(SignatureAlgorithm.RS256);
}
}
| 4,201 | 45.688889 | 112 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtTimestampValidatorTests.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.jwt;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithms;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests verifying {@link JwtTimestampValidator}
*
* @author Josh Cummings
*/
public class JwtTimestampValidatorTests {
private static final Clock MOCK_NOW = Clock.fixed(Instant.ofEpochMilli(0), ZoneId.systemDefault());
private static final String MOCK_TOKEN_VALUE = "token";
private static final Instant MOCK_ISSUED_AT = Instant.MIN;
private static final Map<String, Object> MOCK_HEADER = Collections.singletonMap("alg", JwsAlgorithms.RS256);
private static final Map<String, Object> MOCK_CLAIM_SET = Collections.singletonMap("some", "claim");
@Test
public void validateWhenJwtIsExpiredThenErrorMessageIndicatesExpirationTime() {
Instant oneHourAgo = Instant.now().minusSeconds(3600);
Jwt jwt = TestJwts.jwt().expiresAt(oneHourAgo).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
Collection<OAuth2Error> details = jwtValidator.validate(jwt).getErrors();
// @formatter:off
Collection<String> messages = details.stream()
.map(OAuth2Error::getDescription)
.collect(Collectors.toList());
// @formatter:on
assertThat(messages).contains("Jwt expired at " + oneHourAgo);
assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN));
}
@Test
public void validateWhenJwtIsTooEarlyThenErrorMessageIndicatesNotBeforeTime() {
Instant oneHourFromNow = Instant.now().plusSeconds(3600);
Jwt jwt = TestJwts.jwt().notBefore(oneHourFromNow).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
Collection<OAuth2Error> details = jwtValidator.validate(jwt).getErrors();
// @formatter:off
Collection<String> messages = details.stream()
.map(OAuth2Error::getDescription)
.collect(Collectors.toList());
// @formatter:on
assertThat(messages).contains("Jwt used before " + oneHourFromNow);
assertThat(details).allMatch((error) -> Objects.equals(error.getErrorCode(), OAuth2ErrorCodes.INVALID_TOKEN));
}
@Test
public void validateWhenConfiguredWithClockSkewThenValidatesUsingThatSkew() {
Duration oneDayOff = Duration.ofDays(1);
JwtTimestampValidator jwtValidator = new JwtTimestampValidator(oneDayOff);
Instant now = Instant.now();
Instant almostOneDayAgo = now.minus(oneDayOff).plusSeconds(10);
Instant almostOneDayFromNow = now.plus(oneDayOff).minusSeconds(10);
Instant justOverOneDayAgo = now.minus(oneDayOff).minusSeconds(10);
Instant justOverOneDayFromNow = now.plus(oneDayOff).plusSeconds(10);
Jwt jwt = TestJwts.jwt().expiresAt(almostOneDayAgo).notBefore(almostOneDayFromNow).build();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
jwt = TestJwts.jwt().expiresAt(justOverOneDayAgo).build();
OAuth2TokenValidatorResult result = jwtValidator.validate(jwt);
// @formatter:off
Collection<String> messages = result.getErrors()
.stream()
.map(OAuth2Error::getDescription)
.collect(Collectors.toList());
// @formatter:on
assertThat(result.hasErrors()).isTrue();
assertThat(messages).contains("Jwt expired at " + justOverOneDayAgo);
jwt = TestJwts.jwt().notBefore(justOverOneDayFromNow).build();
result = jwtValidator.validate(jwt);
// @formatter:off
messages = result.getErrors()
.stream()
.map(OAuth2Error::getDescription)
.collect(Collectors.toList());
// @formatter:on
assertThat(result.hasErrors()).isTrue();
assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_TOKEN);
assertThat(messages).contains("Jwt used before " + justOverOneDayFromNow);
}
@Test
public void validateWhenConfiguredWithFixedClockThenValidatesUsingFixedTime() {
Jwt jwt = TestJwts.jwt().expiresAt(Instant.now(MOCK_NOW)).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofNanos(0));
jwtValidator.setClock(MOCK_NOW);
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
jwt = TestJwts.jwt().notBefore(Instant.now(MOCK_NOW)).build();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
}
@Test
public void validateWhenNeitherExpiryNorNotBeforeIsSpecifiedThenReturnsSuccessfulResult() {
Jwt jwt = TestJwts.jwt().claims((c) -> c.remove(JwtClaimNames.EXP)).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
}
@Test
public void validateWhenNotBeforeIsValidAndExpiryIsNotSpecifiedThenReturnsSuccessfulResult() {
Jwt jwt = TestJwts.jwt().claims((c) -> c.remove(JwtClaimNames.EXP)).notBefore(Instant.MIN).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
}
@Test
public void validateWhenExpiryIsValidAndNotBeforeIsNotSpecifiedThenReturnsSuccessfulResult() {
Jwt jwt = TestJwts.jwt().build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
}
@Test
public void validateWhenBothExpiryAndNotBeforeAreValidThenReturnsSuccessfulResult() {
Jwt jwt = TestJwts.jwt().expiresAt(Instant.now(MOCK_NOW)).notBefore(Instant.now(MOCK_NOW)).build();
JwtTimestampValidator jwtValidator = new JwtTimestampValidator(Duration.ofNanos(0));
jwtValidator.setClock(MOCK_NOW);
assertThat(jwtValidator.validate(jwt).hasErrors()).isFalse();
}
@Test
public void setClockWhenInvokedWithNullThenThrowsIllegalArgumentException() {
JwtTimestampValidator jwtValidator = new JwtTimestampValidator();
assertThatIllegalArgumentException().isThrownBy(() -> jwtValidator.setClock(null));
}
@Test
public void constructorWhenInvokedWithNullDurationThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> new JwtTimestampValidator(null));
}
}
| 7,137 | 40.74269 | 112 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwtBuilderTests.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.jwt;
import java.time.Instant;
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 Jwt.Builder}.
*
* @author Jérôme Wacongne <ch4mp@c4-soft.com>
* @author Josh Cummings
*/
public class JwtBuilderTests {
@Test
public void buildWhenCalledTwiceThenGeneratesTwoJwts() {
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token");
// @formatter:off
Jwt first = jwtBuilder.tokenValue("V1")
.header("TEST_HEADER_1", "H1")
.claim("TEST_CLAIM_1", "C1")
.build();
Jwt second = jwtBuilder.tokenValue("V2")
.header("TEST_HEADER_1", "H2")
.header("TEST_HEADER_2", "H3")
.claim("TEST_CLAIM_1", "C2")
.claim("TEST_CLAIM_2", "C3")
.build();
// @formatter:on
assertThat(first.getHeaders()).hasSize(1);
assertThat(first.getHeaders().get("TEST_HEADER_1")).isEqualTo("H1");
assertThat(first.getClaims()).hasSize(1);
assertThat(first.getClaims().get("TEST_CLAIM_1")).isEqualTo("C1");
assertThat(first.getTokenValue()).isEqualTo("V1");
assertThat(second.getHeaders()).hasSize(2);
assertThat(second.getHeaders().get("TEST_HEADER_1")).isEqualTo("H2");
assertThat(second.getHeaders().get("TEST_HEADER_2")).isEqualTo("H3");
assertThat(second.getClaims()).hasSize(2);
assertThat(second.getClaims().get("TEST_CLAIM_1")).isEqualTo("C2");
assertThat(second.getClaims().get("TEST_CLAIM_2")).isEqualTo("C3");
assertThat(second.getTokenValue()).isEqualTo("V2");
}
@Test
public void expiresAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.header("needs", "a header");
// @formatter:on
Instant now = Instant.now();
Jwt jwt = jwtBuilder.expiresAt(now).build();
assertThat(jwt.getExpiresAt()).isSameAs(now);
jwt = jwtBuilder.expiresAt(now).build();
assertThat(jwt.getExpiresAt()).isSameAs(now);
assertThatIllegalArgumentException()
.isThrownBy(() -> jwtBuilder.claim(JwtClaimNames.EXP, "not an instant").build());
}
@Test
public void issuedAtWhenUsingGenericOrNamedClaimMethodRequiresInstant() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.header("needs", "a header");
// @formatter:on
Instant now = Instant.now();
Jwt jwt = jwtBuilder.issuedAt(now).build();
assertThat(jwt.getIssuedAt()).isSameAs(now);
jwt = jwtBuilder.issuedAt(now).build();
assertThat(jwt.getIssuedAt()).isSameAs(now);
assertThatIllegalArgumentException()
.isThrownBy(() -> jwtBuilder.claim(JwtClaimNames.IAT, "not an instant").build());
}
@Test
public void subjectWhenUsingGenericOrNamedClaimMethodThenLastOneWins() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.header("needs", "a header");
// @formatter:on
String generic = new String("sub");
String named = new String("sub");
Jwt jwt = jwtBuilder.subject(named).claim(JwtClaimNames.SUB, generic).build();
assertThat(jwt.getSubject()).isSameAs(generic);
jwt = jwtBuilder.claim(JwtClaimNames.SUB, generic).subject(named).build();
assertThat(jwt.getSubject()).isSameAs(named);
}
@Test
public void claimsWhenRemovingAClaimThenIsNotPresent() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.claim("needs", "a claim")
.header("needs", "a header");
Jwt jwt = jwtBuilder.subject("sub")
.claims((claims) -> claims.remove(JwtClaimNames.SUB))
.build();
// @formatter:on
assertThat(jwt.getSubject()).isNull();
}
@Test
public void claimsWhenAddingAClaimThenIsPresent() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.header("needs", "a header");
// @formatter:on
String name = new String("name");
String value = new String("value");
Jwt jwt = jwtBuilder.claims((claims) -> claims.put(name, value)).build();
assertThat(jwt.getClaims()).hasSize(1);
assertThat(jwt.getClaims().get(name)).isSameAs(value);
}
@Test
public void headersWhenRemovingAClaimThenIsNotPresent() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.claim("needs", "a claim")
.header("needs", "a header");
Jwt jwt = jwtBuilder.header("alg", "none")
.headers((headers) -> headers.remove("alg"))
.build();
// @formatter:on
assertThat(jwt.getHeaders().get("alg")).isNull();
}
@Test
public void headersWhenAddingAClaimThenIsPresent() {
// @formatter:off
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token")
.claim("needs", "a claim");
// @formatter:on
String name = new String("name");
String value = new String("value");
// @formatter:off
Jwt jwt = jwtBuilder.headers((headers) -> headers.put(name, value))
.build();
// @formatter:on
assertThat(jwt.getHeaders()).hasSize(1);
assertThat(jwt.getHeaders().get(name)).isSameAs(value);
}
}
| 5,580 | 33.239264 | 85 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/JwsHeaderTests.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.jwt;
import org.junit.jupiter.api.Test;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link JwsHeader}.
*
* @author Joe Grandja
*/
public class JwsHeaderTests {
@Test
public void withWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwsHeader.with(null))
.withMessage("jwsAlgorithm cannot be null");
}
@Test
public void fromWhenNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwsHeader.from(null))
.withMessage("headers cannot be null");
}
@Test
public void fromWhenHeadersProvidedThenCopied() {
JwsHeader expectedJwsHeader = TestJwsHeaders.jwsHeader().build();
JwsHeader jwsHeader = JwsHeader.from(expectedJwsHeader).build();
assertThat(jwsHeader.getHeaders()).isEqualTo(expectedJwsHeader.getHeaders());
}
@Test
public void buildWhenAllHeadersProvidedThenAllHeadersAreSet() {
JwsHeader expectedJwsHeader = TestJwsHeaders.jwsHeader().build();
// @formatter:off
JwsHeader jwsHeader = JwsHeader.with(expectedJwsHeader.getAlgorithm())
.jwkSetUrl(expectedJwsHeader.getJwkSetUrl().toExternalForm())
.jwk(expectedJwsHeader.getJwk())
.keyId(expectedJwsHeader.getKeyId())
.x509Url(expectedJwsHeader.getX509Url().toExternalForm())
.x509CertificateChain(expectedJwsHeader.getX509CertificateChain())
.x509SHA1Thumbprint(expectedJwsHeader.getX509SHA1Thumbprint())
.x509SHA256Thumbprint(expectedJwsHeader.getX509SHA256Thumbprint())
.type(expectedJwsHeader.getType())
.contentType(expectedJwsHeader.getContentType())
.criticalHeader("critical-header1-name", "critical-header1-value")
.criticalHeader("critical-header2-name", "critical-header2-value")
.headers((headers) -> headers.put("custom-header-name", "custom-header-value"))
.build();
// @formatter:on
assertThat(jwsHeader.getAlgorithm()).isEqualTo(expectedJwsHeader.getAlgorithm());
assertThat(jwsHeader.getJwkSetUrl()).isEqualTo(expectedJwsHeader.getJwkSetUrl());
assertThat(jwsHeader.getJwk()).isEqualTo(expectedJwsHeader.getJwk());
assertThat(jwsHeader.getKeyId()).isEqualTo(expectedJwsHeader.getKeyId());
assertThat(jwsHeader.getX509Url()).isEqualTo(expectedJwsHeader.getX509Url());
assertThat(jwsHeader.getX509CertificateChain()).isEqualTo(expectedJwsHeader.getX509CertificateChain());
assertThat(jwsHeader.getX509SHA1Thumbprint()).isEqualTo(expectedJwsHeader.getX509SHA1Thumbprint());
assertThat(jwsHeader.getX509SHA256Thumbprint()).isEqualTo(expectedJwsHeader.getX509SHA256Thumbprint());
assertThat(jwsHeader.getType()).isEqualTo(expectedJwsHeader.getType());
assertThat(jwsHeader.getContentType()).isEqualTo(expectedJwsHeader.getContentType());
assertThat(jwsHeader.getCritical()).containsExactlyInAnyOrder("critical-header1-name", "critical-header2-name");
assertThat(jwsHeader.<String>getHeader("critical-header1-name")).isEqualTo("critical-header1-value");
assertThat(jwsHeader.<String>getHeader("critical-header2-name")).isEqualTo("critical-header2-value");
assertThat(jwsHeader.<String>getHeader("custom-header-name")).isEqualTo("custom-header-value");
}
@Test
public void headerWhenNameNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwsHeader.with(SignatureAlgorithm.RS256).header(null, "value"))
.withMessage("name cannot be empty");
}
@Test
public void headerWhenValueNullThenThrowIllegalArgumentException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> JwsHeader.with(SignatureAlgorithm.RS256).header("name", null))
.withMessage("value cannot be null");
}
@Test
public void getHeaderWhenNullThenThrowIllegalArgumentException() {
JwsHeader jwsHeader = TestJwsHeaders.jwsHeader().build();
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jwsHeader.getHeader(null))
.withMessage("name cannot be empty");
}
}
| 4,849 | 42.303571 | 114 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoderTests.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.jwt;
import java.net.UnknownHostException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.function.Consumer;
import javax.crypto.SecretKey;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSecurityContextJWKSet;
import com.nimbusds.jose.proc.DefaultJOSEObjectTypeVerifier;
import com.nimbusds.jose.proc.JWKSecurityContext;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jose.TestKeys;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
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.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
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.verify;
/**
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
*/
public class NimbusReactiveJwtDecoderTests {
private String expired = "eyJraWQiOiJrZXktaWQtMSIsImFsZyI6IlJTMjU2In0.eyJzY29wZSI6Im1lc3NhZ2U6cmVhZCIsImV4cCI6MTUyOTkzNzYzMX0.Dt5jFOKkB8zAmjciwvlGkj4LNStXWH0HNIfr8YYajIthBIpVgY5Hg_JL8GBmUFzKDgyusT0q60OOg8_Pdi4Lu-VTWyYutLSlNUNayMlyBaVEWfyZJnh2_OwMZr1vRys6HF-o1qZldhwcfvczHg61LwPa1ISoqaAltDTzBu9cGISz2iBUCuR0x71QhbuRNyJdjsyS96NqiM_TspyiOSxmlNch2oAef1MssOQ23CrKilIvEDsz_zk5H94q7rH0giWGdEHCENESsTJS0zvzH6r2xIWjd5WnihFpCPkwznEayxaEhrdvJqT_ceyXCIfY4m3vujPQHNDG0UshpwvDuEbPUg";
private String messageReadToken = "eyJraWQiOiJrZXktaWQtMSIsImFsZyI6IlJTMjU2In0.eyJzY29wZSI6Im1lc3NhZ2U6cmVhZCIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NX0.bnQ8IJDXmQbmIXWku0YT1HOyV_3d0iQSA_0W2CmPyELhsxFETzBEEcZ0v0xCBiswDT51rwD83wbX3YXxb84fM64AhpU8wWOxLjha4J6HJX2JnlG47ydaAVD7eWGSYTavyyQ-CwUjQWrfMVcObFZLYG11ydzRYOR9-aiHcK3AobcTcS8jZFeI8EGQV_Cd3IJ018uFCf6VnXLv7eV2kRt08Go2RiPLW47ExvD7Dzzz_wDBKfb4pNem7fDvuzB3UPcp5m9QvLZicnbS_6AvDi6P1y_DFJf-1T5gkGmX5piDH1L1jg2Yl6tjmXbk5B3VhsyjJuXE6gzq1d-xie0Z1NVOxw";
private String unsignedToken = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJleHAiOi0yMDMzMjI0OTcsImp0aSI6IjEyMyIsInR5cCI6IkpXVCJ9.";
// @formatter:off
private String jwkSet = "{\n"
+ " \"keys\":[\n"
+ " {\n"
+ " \"kty\":\"RSA\",\n"
+ " \"e\":\"AQAB\",\n"
+ " \"use\":\"sig\",\n"
+ " \"kid\":\"key-id-1\",\n"
+ " \"n\":\"qL48v1clgFw-Evm145pmh8nRYiNt72Gupsshn7Qs8dxEydCRp1DPOV_PahPk1y2nvldBNIhfNL13JOAiJ6BTiF-2ICuICAhDArLMnTH61oL1Hepq8W1xpa9gxsnL1P51thvfmiiT4RTW57koy4xIWmIp8ZXXfYgdH2uHJ9R0CQBuYKe7nEOObjxCFWC8S30huOfW2cYtv0iB23h6w5z2fDLjddX6v_FXM7ktcokgpm3_XmvT_-bL6_GGwz9k6kJOyMTubecr-WT__le8ikY66zlplYXRQh6roFfFCL21Pt8xN5zrk-0AMZUnmi8F2S2ztSBmAVJ7H71ELXsURBVZpw\"\n"
+ " }\n"
+ " ]\n"
+ "}";
// @formatter:on
private String jwkSetUri = "https://issuer/certs";
private String rsa512 = "eyJhbGciOiJSUzUxMiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJleHAiOjE5NzQzMjYxMTl9.LKAx-60EBfD7jC1jb1eKcjO4uLvf3ssISV-8tN-qp7gAjSvKvj4YA9-V2mIb6jcS1X_xGmNy6EIimZXpWaBR3nJmeu-jpe85u4WaW2Ztr8ecAi-dTO7ZozwdtljKuBKKvj4u1nF70zyCNl15AozSG0W1ASrjUuWrJtfyDG6WoZ8VfNMuhtU-xUYUFvscmeZKUYQcJ1KS-oV5tHeF8aNiwQoiPC_9KXCOZtNEJFdq6-uzFdHxvOP2yex5Gbmg5hXonauIFXG2ZPPGdXzm-5xkhBpgM8U7A_6wb3So8wBvLYYm2245QUump63AJRAy8tQpwt4n9MvQxQgS3z9R-NK92A";
private String rsa256 = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ0ZXN0LXN1YmplY3QiLCJleHAiOjE5NzQzMjYzMzl9.CT-H2OWEqmSs1NWmnta5ealLFvM8OlbQTjGhfRcKLNxrTrzsOkqBJl-AN3k16BQU7mS32o744TiiZ29NcDlxPsr1MqTlN86-dobPiuNIDLp3A1bOVdXMcVFuMYkrNv0yW0tGS9OjEqsCCuZDkZ1by6AhsHLbGwRY-6AQdcRouZygGpOQu1hNun5j8q5DpSTY4AXKARIFlF-O3OpVbPJ0ebr3Ki-i3U9p_55H0e4-wx2bqcApWlqgofl1I8NKWacbhZgn81iibup2W7E0CzCzh71u1Mcy3xk1sYePx-dwcxJnHmxJReBBWjJZEAeCrkbnn_OCuo2fA-EQyNJtlN5F2w";
private String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAq4yKxb6SNePdDmQi9xFCrP6QvHosErQzryknQTTTffs0t3cy3Er3lIceuhZ7yQNSCDfPFqG8GoyoKhuChRiA5D+J2ab7bqTa1QJKfnCyERoscftgN2fXPHjHoiKbpGV2tMVw8mXl//tePOAiKbMJaBUnlAvJgkk1rVm08dSwpLC1sr2M19euf9jwnRGkMRZuhp9iCPgECRke5T8Ixpv0uQjSmGHnWUKTFlbj8sM83suROR1Ue64JSGScANc5vk3huJ/J97qTC+K2oKj6L8d9O8dpc4obijEOJwpydNvTYDgbiivYeSB00KS9jlBkQ5B2QqLvLVEygDl3dp59nGx6YQIDAQAB";
private MockWebServer server;
private NimbusReactiveJwtDecoder decoder;
private static KeyFactory kf;
@BeforeAll
public static void keyFactory() throws NoSuchAlgorithmException {
kf = KeyFactory.getInstance("RSA");
}
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.server.enqueue(new MockResponse().setBody(this.jwkSet));
this.decoder = new NimbusReactiveJwtDecoder(this.server.url("/certs").toString());
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void decodeWhenInvalidUrl() {
this.decoder = new NimbusReactiveJwtDecoder("https://s");
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> this.decoder.decode(this.messageReadToken).block())
.withStackTraceContaining(UnknownHostException.class.getSimpleName());
// @formatter:on
}
@Test
public void decodeWhenMessageReadScopeThenSuccess() {
Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims().get("scope")).isEqualTo("message:read");
}
@Test
public void decodeWhenRSAPublicKeyThenSuccess() throws Exception {
byte[] bytes = Base64.getDecoder().decode(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqL48v1clgFw+Evm145pmh8nRYiNt72Gupsshn7Qs8dxEydCRp1DPOV/PahPk1y2nvldBNIhfNL13JOAiJ6BTiF+2ICuICAhDArLMnTH61oL1Hepq8W1xpa9gxsnL1P51thvfmiiT4RTW57koy4xIWmIp8ZXXfYgdH2uHJ9R0CQBuYKe7nEOObjxCFWC8S30huOfW2cYtv0iB23h6w5z2fDLjddX6v/FXM7ktcokgpm3/XmvT/+bL6/GGwz9k6kJOyMTubecr+WT//le8ikY66zlplYXRQh6roFfFCL21Pt8xN5zrk+0AMZUnmi8F2S2ztSBmAVJ7H71ELXsURBVZpwIDAQAB");
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(bytes));
this.decoder = new NimbusReactiveJwtDecoder(publicKey);
String noKeyId = "eyJhbGciOiJSUzI1NiJ9.eyJzY29wZSI6IiIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NX0.hNVuHSUkxdLZrDfqdmKcOi0ggmNaDuB4ZPxPtJl1gwBiXzIGN6Hwl24O2BfBZiHFKUTQDs4_RvzD71mEG3DvUrcKmdYWqIB1l8KNmxQLUDG-cAPIpJmRJgCh50tf8OhOE_Cb9E1HcsOUb47kT9iz-VayNBcmo6BmyZLdEGhsdGBrc3Mkz2dd_0PF38I2Hf_cuSjn9gBjFGtiPEXJvob3PEjVTSx_zvodT8D9p3An1R3YBZf5JSd1cQisrXgDX2k1Jmf7UKKWzgfyCgnEtRWWbsUdPqo3rSEY9GDC1iSQXsFTTC1FT_JJDkwzGf011fsU5O_Ko28TARibmKTCxAKNRQ";
this.decoder.decode(noKeyId).block();
}
@Test
public void decodeWhenIssuedAtThenSuccess() {
String withIssuedAt = "eyJraWQiOiJrZXktaWQtMSIsImFsZyI6IlJTMjU2In0.eyJzY29wZSI6IiIsImV4cCI6OTIyMzM3MjAwNjA5NjM3NSwiaWF0IjoxNTI5OTQyNDQ4fQ.LBzAJO-FR-uJDHST61oX4kimuQjz6QMJPW_mvEXRB6A-fMQWpfTQ089eboipAqsb33XnwWth9ELju9HMWLk0FjlWVVzwObh9FcoKelmPNR8mZIlFG-pAYGgSwi8HufyLabXHntFavBiFtqwp_z9clSOFK1RxWvt3lywEbGgtCKve0BXOjfKWiH1qe4QKGixH-NFxidvz8Qd5WbJwyb9tChC6ZKoKPv7Jp-N5KpxkY-O2iUtINvn4xOSactUsvKHgF8ZzZjvJGzG57r606OZXaNtoElQzjAPU5xDGg5liuEJzfBhvqiWCLRmSuZ33qwp3aoBnFgEw0B85gsNe3ggABg";
Jwt jwt = this.decoder.decode(withIssuedAt).block();
assertThat(jwt.getClaims().get(JwtClaimNames.IAT)).isEqualTo(Instant.ofEpochSecond(1529942448L));
}
@Test
public void decodeWhenExpiredThenFail() {
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.decoder.decode(this.expired).block());
}
@Test
public void decodeWhenNoPeriodThenFail() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder.decode("").block());
// @formatter:on
}
@Test
public void decodeWhenInvalidJwkSetUrlThenFail() {
this.decoder = new NimbusReactiveJwtDecoder("http://localhost:1280/certs");
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> this.decoder.decode(this.messageReadToken).block());
// @formatter:on
}
@Test
public void decodeWhenInvalidSignatureThenFail() {
assertThatExceptionOfType(BadJwtException.class).isThrownBy(() -> this.decoder
.decode(this.messageReadToken.substring(0, this.messageReadToken.length() - 2)).block());
}
@Test
public void decodeWhenAlgNoneThenFail() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder
.decode("ew0KICAiYWxnIjogIm5vbmUiLA0KICAidHlwIjogIkpXVCINCn0.ew0KICAic3ViIjogIjEyMzQ1Njc4OTAiLA0KICAibmFtZSI6ICJKb2huIERvZSIsDQogICJpYXQiOiAxNTE2MjM5MDIyDQp9.")
.block()
)
.withMessage("Unsupported algorithm of none");
// @formatter:on
}
@Test
public void decodeWhenInvalidAlgMismatchThenFail() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder
.decode("ew0KICAiYWxnIjogIkVTMjU2IiwNCiAgInR5cCI6ICJKV1QiDQp9.ew0KICAic3ViIjogIjEyMzQ1Njc4OTAiLA0KICAibmFtZSI6ICJKb2huIERvZSIsDQogICJpYXQiOiAxNTE2MjM5MDIyDQp9.")
.block()
);
// @formatter:on
}
@Test
public void decodeWhenUnsignedTokenThenMessageDoesNotMentionClass() {
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder.decode(this.unsignedToken).block())
.withMessage("Unsupported algorithm of none");
// @formatter:on
}
@Test
public void decodeWhenUsingCustomValidatorThenValidatorIsInvoked() {
OAuth2TokenValidator jwtValidator = mock(OAuth2TokenValidator.class);
this.decoder.setJwtValidator(jwtValidator);
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(error);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.decoder.decode(this.messageReadToken).block())
.withMessageContaining("mock-description");
// @formatter:on
}
@Test
public void decodeWhenReadingErrorPickTheFirstErrorMessage() {
OAuth2TokenValidator<Jwt> jwtValidator = mock(OAuth2TokenValidator.class);
this.decoder.setJwtValidator(jwtValidator);
OAuth2Error errorEmpty = new OAuth2Error("mock-error", "", "mock-uri");
OAuth2Error error = new OAuth2Error("mock-error", "mock-description", "mock-uri");
OAuth2Error error2 = new OAuth2Error("mock-error-second", "mock-description-second", "mock-uri-second");
OAuth2TokenValidatorResult result = OAuth2TokenValidatorResult.failure(errorEmpty, error, error2);
given(jwtValidator.validate(any(Jwt.class))).willReturn(result);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> this.decoder.decode(this.messageReadToken).block())
.withMessageContaining("mock-description");
// @formatter:on
}
@Test
public void decodeWhenUsingSignedJwtThenReturnsClaimsGivenByClaimSetConverter() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.decoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willReturn(Collections.singletonMap("custom", "value"));
Jwt jwt = this.decoder.decode(this.messageReadToken).block();
assertThat(jwt.getClaims().size()).isEqualTo(1);
assertThat(jwt.getClaims().get("custom")).isEqualTo("value");
verify(claimSetConverter).convert(any(Map.class));
}
// gh-7885
@Test
public void decodeWhenClaimSetConverterFailsThenBadJwtException() {
Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = mock(Converter.class);
this.decoder.setClaimSetConverter(claimSetConverter);
given(claimSetConverter.convert(any(Map.class))).willThrow(new IllegalArgumentException("bad conversion"));
// @formatter:off
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder.decode(this.messageReadToken).block());
// @formatter:on
}
@Test
public void setJwtValidatorWhenGivenNullThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.decoder.setJwtValidator(null));
// @formatter:on
}
@Test
public void setClaimSetConverterWhenNullThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.decoder.setClaimSetConverter(null));
// @formatter:on
}
@Test
public void withJwkSetUriWhenNullOrEmptyThenThrowsException() {
assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder.withJwkSetUri(null));
}
@Test
public void jwsAlgorithmWhenNullThenThrowsException() {
NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder
.withJwkSetUri(this.jwkSetUri);
assertThatIllegalArgumentException().isThrownBy(() -> builder.jwsAlgorithm(null));
}
@Test
public void withJwkSetUriWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder
.withJwkSetUri(this.jwkSetUri)
.jwtProcessorCustomizer((Consumer<ConfigurableJWTProcessor<JWKSecurityContext>>) null)
.build()
)
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
@Test
public void restOperationsWhenNullThenThrowsException() {
NimbusReactiveJwtDecoder.JwkSetUriReactiveJwtDecoderBuilder builder = NimbusReactiveJwtDecoder
.withJwkSetUri(this.jwkSetUri);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> builder.webClient(null));
// @formatter:on
}
// gh-5603
@Test
public void decodeWhenSignedThenOk() {
WebClient webClient = mockJwkSetResponse(this.jwkSet);
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.webClient(webClient)
.build();
assertThat(decoder.decode(this.messageReadToken).block())
.extracting(Jwt::getExpiresAt)
.isNotNull();
// @formatter:on
verify(webClient).get();
}
// gh-8730
@Test
public void withJwkSetUriWhenUsingCustomTypeHeaderThenRefuseOmittedType() {
WebClient webClient = mockJwkSetResponse(this.jwkSet);
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.webClient(webClient)
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(this.messageReadToken).block())
.havingRootCause().withMessage("Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
@Test
public void withJwkSetUriWhenJwtProcessorCustomizerSetsJWSKeySelectorThenUseCustomizedJWSKeySelector()
throws InvalidKeySpecException {
WebClient webClient = mockJwkSetResponse(new JWKSet(new RSAKey.Builder(key()).build()).toString());
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.jwsAlgorithm(SignatureAlgorithm.ES256).webClient(webClient)
.jwtProcessorCustomizer((p) -> p
.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS512, new JWKSecurityContextJWKSet())))
.build();
assertThat(decoder.decode(this.rsa512).block()).extracting(Jwt::getSubject).isEqualTo("test-subject");
// @formatter:on
}
@Test
public void withPublicKeyWhenNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(null));
// @formatter:on
}
@Test
public void buildWhenSignatureAlgorithmMismatchesKeyTypeThenThrowsException() {
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(key())
.signatureAlgorithm(SignatureAlgorithm.ES256)
.build()
);
// @formatter:on
}
@Test
public void buildWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder.withPublicKey(key())
.jwtProcessorCustomizer(null)
.build()
)
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
@Test
public void decodeWhenUsingPublicKeyThenSuccessfullyDecodes() throws Exception {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key())
.build();
assertThat(decoder.decode(this.rsa256).block())
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
@Test
public void decodeWhenUsingPublicKeyWithRs512ThenSuccessfullyDecodes() throws Exception {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key())
.signatureAlgorithm(SignatureAlgorithm.RS512)
.build();
assertThat(decoder.decode(this.rsa512).block())
.extracting(Jwt::getSubject)
.isEqualTo("test-subject");
// @formatter:on
}
@Test
public void decodeWhenSignatureMismatchesAlgorithmThenThrowsException() throws Exception {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key())
.signatureAlgorithm(SignatureAlgorithm.RS512)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder
.decode(this.rsa256)
.block()
);
// @formatter:on
}
// gh-8730
@Test
public void withPublicKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() throws Exception {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withPublicKey(key())
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(this.rsa256).block())
.havingRootCause().withMessage("Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
@Test
public void withJwkSourceWhenNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder.withJwkSource(null));
// @formatter:on
}
@Test
public void withJwkSourceWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
assertThatIllegalArgumentException().isThrownBy(() -> NimbusReactiveJwtDecoder
.withJwkSource((jwt) -> Flux.empty()).jwtProcessorCustomizer(null).build())
.withMessage("jwtProcessorCustomizer cannot be null");
}
@Test
public void decodeWhenCustomJwkSourceResolutionThenDecodes() {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder
.withJwkSource((jwt) -> Flux.fromIterable(parseJWKSet(this.jwkSet).getKeys()))
.build();
assertThat(decoder.decode(this.messageReadToken).block())
.extracting(Jwt::getExpiresAt)
.isNotNull();
// @formatter:on
}
// gh-8730
@Test
public void withJwkSourceWhenUsingCustomTypeHeaderThenRefuseOmittedType() {
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder
.withJwkSource((jwt) -> Flux.empty())
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(this.messageReadToken).block())
.havingRootCause()
.withMessage("Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
@Test
public void withSecretKeyWhenSecretKeyNullThenThrowsIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder.withSecretKey(null))
.withMessage("secretKey cannot be null");
// @formatter:on
}
@Test
public void withSecretKeyWhenJwtProcessorCustomizerNullThenThrowsIllegalArgumentException() {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder
.withSecretKey(secretKey)
.jwtProcessorCustomizer(null)
.build()
)
.withMessage("jwtProcessorCustomizer cannot be null");
// @formatter:on
}
@Test
public void withSecretKeyWhenMacAlgorithmNullThenThrowsIllegalArgumentException() {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> NimbusReactiveJwtDecoder
.withSecretKey(secretKey)
.macAlgorithm(null)
)
.withMessage("macAlgorithm cannot be null");
// @formatter:on
}
@Test
public void decodeWhenSecretKeyThenSuccess() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
// @formatter:off
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60)))
.build();
// @formatter:on
SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
// @formatter:off
this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(macAlgorithm)
.build();
Jwt jwt = this.decoder.decode(signedJWT.serialize())
.block();
// @formatter:on
assertThat(jwt.getSubject()).isEqualTo("test-subject");
}
// gh-8730
@Test
public void withSecretKeyWhenUsingCustomTypeHeaderThenRefuseOmittedType() {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
// @formatter:off
NimbusReactiveJwtDecoder decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey)
.jwtProcessorCustomizer((p) -> p
.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("JWS")))
)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> decoder.decode(this.messageReadToken).block())
.havingRootCause().withMessage("Required JOSE header typ (type) parameter is missing");
// @formatter:on
}
@Test
public void decodeWhenSecretKeyAndAlgorithmMismatchThenThrowsJwtException() throws Exception {
SecretKey secretKey = TestKeys.DEFAULT_SECRET_KEY;
MacAlgorithm macAlgorithm = MacAlgorithm.HS256;
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject("test-subject")
.expirationTime(Date.from(Instant.now().plusSeconds(60))).build();
SignedJWT signedJWT = signedJwt(secretKey, macAlgorithm, claimsSet);
// @formatter:off
this.decoder = NimbusReactiveJwtDecoder.withSecretKey(secretKey)
.macAlgorithm(MacAlgorithm.HS512)
.build();
assertThatExceptionOfType(BadJwtException.class)
.isThrownBy(() -> this.decoder.decode(signedJWT.serialize()).block());
// @formatter:on
}
@Test
public void decodeWhenIssuerLocationThenOk() {
String issuer = "https://example.org/issuer";
WebClient real = WebClient.builder().build();
WebClient.RequestHeadersUriSpec spec = spy(real.get());
WebClient webClient = spy(WebClient.class);
given(webClient.get()).willReturn(spec);
WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class);
given(responseSpec.bodyToMono(String.class)).willReturn(Mono.just(this.jwkSet));
given(responseSpec.bodyToMono(any(ParameterizedTypeReference.class)))
.willReturn(Mono.just(Map.of("issuer", issuer, "jwks_uri", issuer + "/jwks")));
given(spec.retrieve()).willReturn(responseSpec);
ReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withIssuerLocation(issuer).webClient(webClient)
.build();
Jwt jwt = jwtDecoder.decode(this.messageReadToken).block();
assertThat(jwt.hasClaim(JwtClaimNames.EXP)).isNotNull();
}
@Test
public void jwsKeySelectorWhenNoAlgorithmThenReturnsRS256Selector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
}
@Test
public void jwsKeySelectorWhenOneAlgorithmThenReturnsSingleSelector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.jwsAlgorithm(SignatureAlgorithm.RS512).jwsKeySelector(jwkSource).block();
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<JWKSecurityContext> jwsVerificationKeySelector = (JWSVerificationKeySelector<JWKSecurityContext>) jwsKeySelector;
assertThat(jwsVerificationKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
@Test
public void jwsKeySelectorWhenMultipleAlgorithmThenReturnsCompositeSelector() {
ReactiveRemoteJWKSource jwkSource = mock(ReactiveRemoteJWKSource.class);
// @formatter:off
JWSKeySelector<JWKSecurityContext> jwsKeySelector = NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
.jwsAlgorithm(SignatureAlgorithm.RS256)
.jwsAlgorithm(SignatureAlgorithm.RS512)
.jwsKeySelector(jwkSource).block();
// @formatter:on
assertThat(jwsKeySelector instanceof JWSVerificationKeySelector);
JWSVerificationKeySelector<?> jwsAlgorithmMapKeySelector = (JWSVerificationKeySelector<?>) jwsKeySelector;
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS256)).isTrue();
assertThat(jwsAlgorithmMapKeySelector.isAllowed(JWSAlgorithm.RS512)).isTrue();
}
private SignedJWT signedJwt(SecretKey secretKey, MacAlgorithm jwsAlgorithm, JWTClaimsSet claimsSet)
throws Exception {
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.parse(jwsAlgorithm.getName())), claimsSet);
JWSSigner signer = new MACSigner(secretKey);
signedJWT.sign(signer);
return signedJWT;
}
private JWKSet parseJWKSet(String jwkSet) {
try {
return JWKSet.parse(jwkSet);
}
catch (ParseException ex) {
throw new IllegalArgumentException(ex);
}
}
private RSAPublicKey key() throws InvalidKeySpecException {
byte[] decoded = Base64.getDecoder().decode(this.publicKey.getBytes());
EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
return (RSAPublicKey) kf.generatePublic(spec);
}
private static WebClient mockJwkSetResponse(String response) {
WebClient real = WebClient.builder().build();
WebClient.RequestHeadersUriSpec spec = spy(real.get());
WebClient webClient = spy(WebClient.class);
given(webClient.get()).willReturn(spec);
WebClient.ResponseSpec responseSpec = mock(WebClient.ResponseSpec.class);
given(responseSpec.bodyToMono(String.class)).willReturn(Mono.just(response));
given(spec.retrieve()).willReturn(responseSpec);
return webClient;
}
}
| 29,161 | 41.386628 | 488 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecodersTests.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.jwt;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
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.web.util.UriComponentsBuilder;
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 ReactiveJwtDecoders}
*
* @author Josh Cummings
* @author Rafiullah Hamedy
*/
public class ReactiveJwtDecodersTests {
/**
* Contains those parameters required to construct a ReactiveJwtDecoder as well as any
* required parameters
*/
// @formatter:off
private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n"
+ " \"authorization_endpoint\": \"https://example.com/o/oauth2/v2/auth\", \n"
+ " \"id_token_signing_alg_values_supported\": [\n"
+ " \"RS256\"\n"
+ " ], \n"
+ " \"issuer\": \"%s\", \n"
+ " \"jwks_uri\": \"%s/.well-known/jwks.json\", \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"
+ " \"subject_types_supported\": [\n"
+ " \"public\"\n"
+ " ], \n"
+ " \"token_endpoint\": \"https://example.com/oauth2/v4/token\"\n"
+ "}";
// @formatter:on
private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"oXJ8OyOv_eRnce4akdanR4KYRfnC2zLV4uYNQpcFn6oHL0dj7D6kxQmsXoYgJV8ZVDn71KGmuLvolxsDncc2UrhyMBY6DVQVgMSVYaPCTgW76iYEKGgzTEw5IBRQL9w3SRJWd3VJTZZQjkXef48Ocz06PGF3lhbz4t5UEZtdF4rIe7u-977QwHuh7yRPBQ3sII-cVoOUMgaXB9SHcGF2iZCtPzL_IffDUcfhLQteGebhW8A6eUHgpD5A1PQ-JCw_G7UOzZAjjDjtNM2eqm8j-Ms_gqnm4MiCZ4E-9pDN77CAAPVN7kuX6ejs9KBXpk01z48i9fORYk9u7rAkh1HuQw\"}]}";
private static final String ISSUER_MISMATCH = "eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3Jvbmdpc3N1ZXIiLCJleHAiOjQ2ODcyNTYwNDl9.Ax8LMI6rhB9Pv_CE3kFi1JPuLj9gZycifWrLeDpkObWEEVAsIls9zAhNFyJlG-Oo7up6_mDhZgeRfyKnpSF5GhKJtXJDCzwg0ZDVUE6rS0QadSxsMMGbl7c4y0lG_7TfLX2iWeNJukJj_oSW9KzW4FsBp1BoocWjrreesqQU3fZHbikH-c_Fs2TsAIpHnxflyEzfOFWpJ8D4DtzHXqfvieMwpy42xsPZK3LR84zlasf0Ne1tC_hLHvyHRdAXwn0CMoKxc7-8j0r9Mq8kAzUsPn9If7bMLqGkxUcTPdk5x7opAUajDZx95SXHLmtztNtBa2S6EfPJXuPKG6tM5Wq5Ug";
private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";
private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
private MockWebServer server;
private String issuer;
@BeforeEach
public void setup() throws Exception {
this.server = new MockWebServer();
this.server.start();
this.issuer = createIssuerFromServer();
this.issuer += "path";
}
@AfterEach
public void cleanup() throws Exception {
this.server.shutdown();
}
@Test
public void issuerWhenResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponse();
ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block())
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponseOidc();
ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block())
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsTypicalThenReturnedDecoderValidatesIssuer() {
prepareConfigurationResponseOAuth2();
ReactiveJwtDecoder decoder = ReactiveJwtDecoders.fromIssuerLocation(this.issuer);
// @formatter:off
assertThatExceptionOfType(JwtValidationException.class)
.isThrownBy(() -> decoder.decode(ISSUER_MISMATCH).block())
.withMessageContaining("The iss claim is not valid");
// @formatter:on
}
@Test
public void issuerWhenResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponse("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsNonCompliantThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("{ \"missing_required_keys\" : \"and_values\" }");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponse(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer))
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOidcFallbackResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOidc(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer))
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
// gh-7512
@Test
public void issuerWhenOAuth2ResponseDoesNotContainJwksUriThenThrowsIllegalArgumentException()
throws JsonMappingException, JsonProcessingException {
prepareConfigurationResponseOAuth2(this.buildResponseWithMissingJwksUri());
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer))
.withMessage("The public JWK set URI must not be null");
// @formatter:on
}
@Test
public void issuerWhenResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponse("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOidc("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2ResponseIsMalformedThenThrowsRuntimeException() {
prepareConfigurationResponseOAuth2("malformed");
// @formatter:off
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponse(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOidc(String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenOAuth2RespondingIssuerMismatchesRequestedIssuerThenThrowsIllegalStateException() {
prepareConfigurationResponseOAuth2(
String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer + "/wrong", this.issuer));
// @formatter:off
assertThatIllegalStateException()
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation(this.issuer));
// @formatter:on
}
@Test
public void issuerWhenRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException() throws Exception {
this.server.shutdown();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoders.fromOidcIssuerLocation("https://issuer"));
// @formatter:on
}
@Test
public void issuerWhenOidcFallbackRequestedIssuerIsUnresponsiveThenThrowsIllegalArgumentException()
throws Exception {
this.server.shutdown();
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> ReactiveJwtDecoders.fromIssuerLocation("https://issuer"));
// @formatter:on
}
private void prepareConfigurationResponse() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponse(body);
}
private void prepareConfigurationResponse(String body) {
this.server.enqueue(response(body));
this.server.enqueue(response(JWK_SET));
}
private void prepareConfigurationResponseOidc() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOidc(body);
}
private void prepareConfigurationResponseOidc(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oidc(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponseOAuth2() {
String body = String.format(DEFAULT_RESPONSE_TEMPLATE, this.issuer, this.issuer);
prepareConfigurationResponseOAuth2(body);
}
private void prepareConfigurationResponseOAuth2(String body) {
Map<String, MockResponse> responses = new HashMap<>();
responses.put(oauth(), response(body));
responses.put(jwks(), response(JWK_SET));
prepareConfigurationResponses(responses);
}
private void prepareConfigurationResponses(Map<String, MockResponse> responses) {
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
// @formatter:off
return Optional.of(request)
.map(RecordedRequest::getRequestUrl)
.map(HttpUrl::toString)
.map(responses::get)
.orElse(new MockResponse().setResponseCode(404));
// @formatter:on
}
};
this.server.setDispatcher(dispatcher);
}
private String createIssuerFromServer() {
return this.server.url("").toString();
}
private String oidc() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(uri.getPath() + OIDC_METADATA_PATH)
.toUriString();
// @formatter:on
}
private String oauth() {
URI uri = URI.create(this.issuer);
// @formatter:off
return UriComponentsBuilder.fromUri(uri)
.replacePath(OAUTH_METADATA_PATH + uri.getPath())
.toUriString();
// @formatter:on
}
private String jwks() {
return this.issuer + "/.well-known/jwks.json";
}
private MockResponse response(String body) {
// @formatter:off
return new MockResponse().setBody(body)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
public String buildResponseWithMissingJwksUri() throws JsonMappingException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> response = mapper.readValue(DEFAULT_RESPONSE_TEMPLATE,
new TypeReference<Map<String, Object>>() {
});
response.remove("jwks_uri");
return mapper.writeValueAsString(response);
}
}
| 13,610 | 35.786486 | 478 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSourceTests.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.jwt;
import java.util.Collections;
import java.util.List;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
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 static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
/**
* @author Rob Winch
* @since 5.1
*/
@ExtendWith(MockitoExtension.class)
public class ReactiveRemoteJWKSourceTests {
@Mock
private JWKMatcher matcher;
private ReactiveRemoteJWKSource source;
private JWKSelector selector;
private MockWebServer server;
// @formatter:off
private String keys = "{\n"
+ " \"keys\": [\n"
+ " {\n"
+ " \"alg\": \"RS256\", \n"
+ " \"e\": \"AQAB\", \n"
+ " \"kid\": \"1923397381d9574bb873202a90c32b7ceeaed027\", \n"
+ " \"kty\": \"RSA\", \n"
+ " \"n\": \"m4I5Dk5GnbzzUtqaljDVbpMONi1JLNJ8ZuXE8VvjCAVebDg5vTYhQ33jUwGgbn1wFmytUMgMmvK8A8Gpshl0sO2GBIZoh6_pwLrk657ZEtv-hx9fYKnzwyrfHqxtSswMAyr7XtKl8Ha1I03uFMSaYaaBTwVXCHByhzr4PVXfKAYJNbbcteUZfE8ODlBQkjQLI0IB78Nu8XIRrdzTF_5LCuM6rLUNtX6_KdzPpeX9KEtB7OBAfkdZEtBzGI-aYNLtIaL4qO6cVxBeVDLMoj9kVsRPylrwhEFQcGOjtJhwJwXFzTMZVhkiLFCHxZkkjoMrK5osSRlhduuGI9ot8XTUKQ\", \n"
+ " \"use\": \"sig\"\n"
+ " }, \n"
+ " {\n"
+ " \"alg\": \"RS256\", \n"
+ " \"e\": \"AQAB\", \n"
+ " \"kid\": \"7ddf54d3032d1f0d48c3618892ca74c1ac30ad77\", \n"
+ " \"kty\": \"RSA\", \n"
+ " \"n\": \"yLlYyux949b7qS-DdqTNjdZb4NtqiNH-Jt7DtRxmfW9XZLOQ6Q2NYgmPe9hyy5GHG7W3zsd6Q-rzq5eGRNEUx1767K1dS5PtkVWPiPG_M7rDqCu3HsLmKQKhRjHYaCWl5NuiMB5mXoPhSwrHd2yeGE7QHIV7_CiQFc1xQsXeiC-nTeJohJO3HI97w0GXE8pHspLYq9oG87f5IHxFr89abmwRug-D7QWQyW5b4doe4ZL-52J-8WHd52kGrGfu4QyV83oAad3I_9Q-yiWOXUr_0GIrzz4_-u5HgqYexnodFhZZSaKuRSg_b5qCnPhW8gBDLAHkmQzQMaWsN14L0pokbQ\", \n"
+ " \"use\": \"sig\"\n"
+ " }\n"
+ " ]\n"
+ "}\n";
// @formatter:on
// @formatter:off
private String keys2 = "{\n"
+ " \"keys\": [\n"
+ " {\n"
+ " \"alg\": \"RS256\", \n"
+ " \"e\": \"AQAB\", \n"
+ " \"kid\": \"rotated\", \n"
+ " \"kty\": \"RSA\", \n"
+ " \"n\": \"m4I5Dk5GnbzzUtqaljDVbpMONi1JLNJ8ZuXE8VvjCAVebDg5vTYhQ33jUwGgbn1wFmytUMgMmvK8A8Gpshl0sO2GBIZoh6_pwLrk657ZEtv-hx9fYKnzwyrfHqxtSswMAyr7XtKl8Ha1I03uFMSaYaaBTwVXCHByhzr4PVXfKAYJNbbcteUZfE8ODlBQkjQLI0IB78Nu8XIRrdzTF_5LCuM6rLUNtX6_KdzPpeX9KEtB7OBAfkdZEtBzGI-aYNLtIaL4qO6cVxBeVDLMoj9kVsRPylrwhEFQcGOjtJhwJwXFzTMZVhkiLFCHxZkkjoMrK5osSRlhduuGI9ot8XTUKQ\", \n"
+ " \"use\": \"sig\"\n"
+ " }\n"
+ " ]\n"
+ "}\n";
// @formatter:on
@BeforeEach
public void setup() {
this.server = new MockWebServer();
this.source = new ReactiveRemoteJWKSource(this.server.url("/").toString());
this.server.enqueue(new MockResponse().setBody(this.keys));
this.selector = new JWKSelector(this.matcher);
}
@Test
public void getWhenMultipleRequestThenCached() {
given(this.matcher.matches(any())).willReturn(true);
this.source.get(this.selector).block();
this.source.get(this.selector).block();
assertThat(this.server.getRequestCount()).isEqualTo(1);
}
@Test
public void getWhenMatchThenCreatesKeys() {
given(this.matcher.matches(any())).willReturn(true);
List<JWK> keys = this.source.get(this.selector).block();
assertThat(keys).hasSize(2);
JWK key1 = keys.get(0);
assertThat(key1.getKeyID()).isEqualTo("1923397381d9574bb873202a90c32b7ceeaed027");
assertThat(key1.getAlgorithm().getName()).isEqualTo("RS256");
assertThat(key1.getKeyType()).isEqualTo(KeyType.RSA);
assertThat(key1.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
JWK key2 = keys.get(1);
assertThat(key2.getKeyID()).isEqualTo("7ddf54d3032d1f0d48c3618892ca74c1ac30ad77");
assertThat(key2.getAlgorithm().getName()).isEqualTo("RS256");
assertThat(key2.getKeyType()).isEqualTo(KeyType.RSA);
assertThat(key2.getKeyUse()).isEqualTo(KeyUse.SIGNATURE);
}
@Test
public void getWhenNoMatchAndNoKeyIdThenEmpty() {
given(this.matcher.matches(any())).willReturn(false);
given(this.matcher.getKeyIDs()).willReturn(Collections.emptySet());
assertThat(this.source.get(this.selector).block()).isEmpty();
}
@Test
public void getWhenNoMatchAndKeyIdNotMatchThenRefreshAndFoundThenFound() {
this.server.enqueue(new MockResponse().setBody(this.keys2));
given(this.matcher.matches(any())).willReturn(false, false, true);
given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("rotated"));
List<JWK> keys = this.source.get(this.selector).block();
assertThat(keys).hasSize(1);
assertThat(keys.get(0).getKeyID()).isEqualTo("rotated");
}
@Test
public void getWhenNoMatchAndKeyIdNotMatchThenRefreshAndNotFoundThenEmpty() {
this.server.enqueue(new MockResponse().setBody(this.keys2));
given(this.matcher.matches(any())).willReturn(false, false, false);
given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("rotated"));
List<JWK> keys = this.source.get(this.selector).block();
assertThat(keys).isEmpty();
}
@Test
public void getWhenNoMatchAndKeyIdMatchThenEmpty() {
given(this.matcher.matches(any())).willReturn(false);
given(this.matcher.getKeyIDs()).willReturn(Collections.singleton("7ddf54d3032d1f0d48c3618892ca74c1ac30ad77"));
assertThat(this.source.get(this.selector).block()).isEmpty();
}
}
| 6,488 | 39.55625 | 376 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/SupplierJwtDecoderTests.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.jwt;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link SupplierJwtDecoder}
*
* @author Josh Cummings
*/
public class SupplierJwtDecoderTests {
@Test
public void decodeWhenUninitializedThenSupplierInitializes() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
SupplierJwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(() -> jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
}
@Test
public void decodeWhenInitializationFailsThenInitializationException() {
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder jwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class).isThrownBy(() -> jwtDecoder.decode("token"));
verify(broken).get();
}
@Test
public void decodeWhenInitializedThenCaches() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
Supplier<JwtDecoder> supplier = mock(Supplier.class);
given(supplier.get()).willReturn(jwtDecoder);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(supplier);
supplierJwtDecoder.decode("token");
supplierJwtDecoder.decode("token");
verify(supplier, times(1)).get();
verify(jwtDecoder, times(2)).decode("token");
}
@Test
public void decodeWhenInitializationInitiallyFailsThenRecoverable() {
JwtDecoder jwtDecoder = mock(JwtDecoder.class);
Supplier<JwtDecoder> broken = mock(Supplier.class);
given(broken.get()).willThrow(RuntimeException.class);
JwtDecoder supplierJwtDecoder = new SupplierJwtDecoder(broken);
assertThatExceptionOfType(JwtDecoderInitializationException.class)
.isThrownBy(() -> supplierJwtDecoder.decode("token"));
reset(broken);
given(broken.get()).willReturn(jwtDecoder);
supplierJwtDecoder.decode("token");
verify(jwtDecoder).decode("token");
}
}
| 2,842 | 34.098765 | 114 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jose/TestKeys.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.jose;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECFieldFp;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.EllipticCurve;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @author Joe Grandja
* @since 5.2
*/
public final class TestKeys {
public static final KeyFactory kf;
static {
try {
kf = KeyFactory.getInstance("RSA");
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
}
public static final String DEFAULT_ENCODED_SECRET_KEY = "bCzY/M48bbkwBEWjmNSIEPfwApcvXOnkCxORBEbPr+4=";
public static final SecretKey DEFAULT_SECRET_KEY = new SecretKeySpec(
Base64.getDecoder().decode(DEFAULT_ENCODED_SECRET_KEY), "AES");
// @formatter:off
public static final String DEFAULT_RSA_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3FlqJr5TRskIQIgdE3Dd"
+ "7D9lboWdcTUT8a+fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRv"
+ "c5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4/1tfRgG6ii4Uhxh6"
+ "iI8qNMJQX+fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2"
+ "kJdJ/ZIV+WW4noDdzpKqHcwmB8FsrumlVY/DNVvUSDIipiq9PbP4H99TXN1o746o"
+ "RaNa07rq1hoCgMSSy+85SagCoxlmyE+D+of9SsMY8Ol9t0rdzpobBuhyJ/o5dfvj"
+ "KwIDAQAB";
// @formatter:on
public static final RSAPublicKey DEFAULT_PUBLIC_KEY;
static {
X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(DEFAULT_RSA_PUBLIC_KEY));
try {
DEFAULT_PUBLIC_KEY = (RSAPublicKey) kf.generatePublic(spec);
}
catch (InvalidKeySpecException ex) {
throw new IllegalArgumentException(ex);
}
}
// @formatter:off
public static final String DEFAULT_RSA_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDcWWomvlNGyQhA"
+ "iB0TcN3sP2VuhZ1xNRPxr58lHswC9Cbtdc2hiSbe/sxAvU1i0O8vaXwICdzRZ1JM"
+ "g1TohG9zkqqjZDhyw1f1Ic6YR/OhE6NCpqERy97WMFeW6gJd1i5inHj/W19GAbqK"
+ "LhSHGHqIjyo0wlBf58t+qFt9h/EFBVE/LAGQBsg/jHUQCxsLoVI2aSELGIw2oSDF"
+ "oiljwLaQl0n9khX5ZbiegN3OkqodzCYHwWyu6aVVj8M1W9RIMiKmKr09s/gf31Nc"
+ "3WjvjqhFo1rTuurWGgKAxJLL7zlJqAKjGWbIT4P6h/1Kwxjw6X23St3OmhsG6HIn"
+ "+jl1++MrAgMBAAECggEBAMf820wop3pyUOwI3aLcaH7YFx5VZMzvqJdNlvpg1jbE"
+ "E2Sn66b1zPLNfOIxLcBG8x8r9Ody1Bi2Vsqc0/5o3KKfdgHvnxAB3Z3dPh2WCDek"
+ "lCOVClEVoLzziTuuTdGO5/CWJXdWHcVzIjPxmK34eJXioiLaTYqN3XKqKMdpD0ZG"
+ "mtNTGvGf+9fQ4i94t0WqIxpMpGt7NM4RHy3+Onggev0zLiDANC23mWrTsUgect/7"
+ "62TYg8g1bKwLAb9wCBT+BiOuCc2wrArRLOJgUkj/F4/gtrR9ima34SvWUyoUaKA0"
+ "bi4YBX9l8oJwFGHbU9uFGEMnH0T/V0KtIB7qetReywkCgYEA9cFyfBIQrYISV/OA"
+ "+Z0bo3vh2aL0QgKrSXZ924cLt7itQAHNZ2ya+e3JRlTczi5mnWfjPWZ6eJB/8MlH"
+ "Gpn12o/POEkU+XjZZSPe1RWGt5g0S3lWqyx9toCS9ACXcN9tGbaqcFSVI73zVTRA"
+ "8J9grR0fbGn7jaTlTX2tnlOTQ60CgYEA5YjYpEq4L8UUMFkuj+BsS3u0oEBnzuHd"
+ "I9LEHmN+CMPosvabQu5wkJXLuqo2TxRnAznsA8R3pCLkdPGoWMCiWRAsCn979TdY"
+ "QbqO2qvBAD2Q19GtY7lIu6C35/enQWzJUMQE3WW0OvjLzZ0l/9mA2FBRR+3F9A1d"
+ "rBdnmv0c3TcCgYEAi2i+ggVZcqPbtgrLOk5WVGo9F1GqUBvlgNn30WWNTx4zIaEk"
+ "HSxtyaOLTxtq2odV7Kr3LGiKxwPpn/T+Ief+oIp92YcTn+VfJVGw4Z3BezqbR8lA"
+ "Uf/+HF5ZfpMrVXtZD4Igs3I33Duv4sCuqhEvLWTc44pHifVloozNxYfRfU0CgYBN"
+ "HXa7a6cJ1Yp829l62QlJKtx6Ymj95oAnQu5Ez2ROiZMqXRO4nucOjGUP55Orac1a"
+ "FiGm+mC/skFS0MWgW8evaHGDbWU180wheQ35hW6oKAb7myRHtr4q20ouEtQMdQIF"
+ "snV39G1iyqeeAsf7dxWElydXpRi2b68i3BIgzhzebQKBgQCdUQuTsqV9y/JFpu6H"
+ "c5TVvhG/ubfBspI5DhQqIGijnVBzFT//UfIYMSKJo75qqBEyP2EJSmCsunWsAFsM"
+ "TszuiGTkrKcZy9G0wJqPztZZl2F2+bJgnA6nBEV7g5PA4Af+QSmaIhRwqGDAuROR"
+ "47jndeyIaMTNETEmOnms+as17g==";
// @formatter:on
public static final RSAPrivateKey DEFAULT_PRIVATE_KEY;
static {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(DEFAULT_RSA_PRIVATE_KEY));
try {
DEFAULT_PRIVATE_KEY = (RSAPrivateKey) kf.generatePrivate(spec);
}
catch (InvalidKeySpecException ex) {
throw new IllegalArgumentException(ex);
}
}
public static final KeyPair DEFAULT_RSA_KEY_PAIR = new KeyPair(DEFAULT_PUBLIC_KEY, DEFAULT_PRIVATE_KEY);
public static final KeyPair DEFAULT_EC_KEY_PAIR = generateEcKeyPair();
static KeyPair generateEcKeyPair() {
EllipticCurve ellipticCurve = new EllipticCurve(
new ECFieldFp(new BigInteger(
"115792089210356248762697446949407573530086143415290314195533631308867097853951")),
new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853948"),
new BigInteger("41058363725152142129326129780047268409114441015993725554835256314039467401291"));
ECPoint ecPoint = new ECPoint(
new BigInteger("48439561293906451759052585252797914202762949526041747995844080717082404635286"),
new BigInteger("36134250956749795798585127919587881956611106672985015071877198253568414405109"));
ECParameterSpec ecParameterSpec = new ECParameterSpec(ellipticCurve, ecPoint,
new BigInteger("115792089210356248762697446949407573529996955224135760342422259061068512044369"), 1);
KeyPair keyPair;
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
keyPairGenerator.initialize(ecParameterSpec);
keyPair = keyPairGenerator.generateKeyPair();
}
catch (Exception ex) {
throw new IllegalStateException(ex);
}
return keyPair;
}
private TestKeys() {
}
}
| 6,326 | 40.900662 | 120 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jose/TestJwks.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.jose;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import javax.crypto.SecretKey;
import com.nimbusds.jose.jwk.Curve;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.jwk.RSAKey;
/**
* @author Joe Grandja
*/
public final class TestJwks {
// @formatter:off
public static final RSAKey DEFAULT_RSA_JWK =
jwk(
TestKeys.DEFAULT_PUBLIC_KEY,
TestKeys.DEFAULT_PRIVATE_KEY
).build();
// @formatter:on
// @formatter:off
public static final ECKey DEFAULT_EC_JWK =
jwk(
(ECPublicKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPublic(),
(ECPrivateKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPrivate()
).build();
// @formatter:on
// @formatter:off
public static final OctetSequenceKey DEFAULT_SECRET_JWK =
jwk(
TestKeys.DEFAULT_SECRET_KEY
).build();
// @formatter:on
private TestJwks() {
}
public static RSAKey.Builder jwk(RSAPublicKey publicKey, RSAPrivateKey privateKey) {
// @formatter:off
return new RSAKey.Builder(publicKey)
.privateKey(privateKey)
.keyID("rsa-jwk-kid");
// @formatter:on
}
public static ECKey.Builder jwk(ECPublicKey publicKey, ECPrivateKey privateKey) {
// @formatter:off
Curve curve = Curve.forECParameterSpec(publicKey.getParams());
return new ECKey.Builder(curve, publicKey)
.privateKey(privateKey)
.keyID("ec-jwk-kid");
// @formatter:on
}
public static OctetSequenceKey.Builder jwk(SecretKey secretKey) {
// @formatter:off
return new OctetSequenceKey.Builder(secretKey)
.keyID("secret-jwk-kid");
// @formatter:on
}
}
| 2,393 | 26.517241 | 85 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jose/jws/MacAlgorithmTests.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.jose.jws;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link MacAlgorithm}
*
* @author Joe Grandja
* @since 5.2
*/
public class MacAlgorithmTests {
@Test
public void fromWhenAlgorithmValidThenResolves() {
assertThat(MacAlgorithm.from(JwsAlgorithms.HS256)).isEqualTo(MacAlgorithm.HS256);
assertThat(MacAlgorithm.from(JwsAlgorithms.HS384)).isEqualTo(MacAlgorithm.HS384);
assertThat(MacAlgorithm.from(JwsAlgorithms.HS512)).isEqualTo(MacAlgorithm.HS512);
}
@Test
public void fromWhenAlgorithmInvalidThenDoesNotResolve() {
assertThat(MacAlgorithm.from("invalid")).isNull();
}
}
| 1,330 | 29.25 | 83 | java |
null | spring-security-main/oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jose/jws/SignatureAlgorithmTests.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.jose.jws;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SignatureAlgorithm}
*
* @author Joe Grandja
* @since 5.2
*/
public class SignatureAlgorithmTests {
@Test
public void fromWhenAlgorithmValidThenResolves() {
assertThat(SignatureAlgorithm.from(JwsAlgorithms.RS256)).isEqualTo(SignatureAlgorithm.RS256);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.RS384)).isEqualTo(SignatureAlgorithm.RS384);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.RS512)).isEqualTo(SignatureAlgorithm.RS512);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.ES256)).isEqualTo(SignatureAlgorithm.ES256);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.ES384)).isEqualTo(SignatureAlgorithm.ES384);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.ES512)).isEqualTo(SignatureAlgorithm.ES512);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.PS256)).isEqualTo(SignatureAlgorithm.PS256);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.PS384)).isEqualTo(SignatureAlgorithm.PS384);
assertThat(SignatureAlgorithm.from(JwsAlgorithms.PS512)).isEqualTo(SignatureAlgorithm.PS512);
}
@Test
public void fromWhenAlgorithmInvalidThenDoesNotResolve() {
assertThat(SignatureAlgorithm.from("invalid")).isNull();
}
}
| 1,960 | 38.22 | 95 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/Jwt.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.jwt;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
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 a JSON Web Token
* (JWT).
*
* <p>
* JWTs represent a set of "claims" as a JSON object that may be encoded in a
* JSON Web Signature (JWS) and/or JSON Web Encryption (JWE) structure. The JSON object,
* also known as the JWT Claims Set, consists of one or more claim name/value pairs. The
* claim name is a {@code String} and the claim value is an arbitrary JSON object.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractOAuth2Token
* @see JwtClaimAccessor
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516">JSON Web Encryption
* (JWE)</a>
*/
public class Jwt extends AbstractOAuth2Token implements JwtClaimAccessor {
private final Map<String, Object> headers;
private final Map<String, Object> claims;
/**
* Constructs a {@code Jwt} using the provided parameters.
* @param tokenValue the token value
* @param issuedAt the time at which the JWT was issued
* @param expiresAt the expiration time on or after which the JWT MUST NOT be accepted
* @param headers the JOSE header(s)
* @param claims the JWT Claims Set
*
*/
public Jwt(String tokenValue, Instant issuedAt, Instant expiresAt, Map<String, Object> headers,
Map<String, Object> claims) {
super(tokenValue, issuedAt, expiresAt);
Assert.notEmpty(headers, "headers cannot be empty");
Assert.notEmpty(claims, "claims cannot be empty");
this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
this.claims = Collections.unmodifiableMap(new LinkedHashMap<>(claims));
}
/**
* Returns the JOSE header(s).
* @return a {@code Map} of the JOSE header(s)
*/
public Map<String, Object> getHeaders() {
return this.headers;
}
/**
* Returns the JWT Claims Set.
* @return a {@code Map} of the JWT Claims Set
*/
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
/**
* Return a {@link Jwt.Builder}
* @return A {@link Jwt.Builder}
*/
public static Builder withTokenValue(String tokenValue) {
return new Builder(tokenValue);
}
/**
* Helps configure a {@link Jwt}
*
* @author Jérôme Wacongne <ch4mp@c4-soft.com>
* @author Josh Cummings
* @since 5.2
*/
public static final class Builder {
private String tokenValue;
private final Map<String, Object> claims = new LinkedHashMap<>();
private final Map<String, Object> headers = new LinkedHashMap<>();
private Builder(String tokenValue) {
this.tokenValue = tokenValue;
}
/**
* Use this token value in the resulting {@link Jwt}
* @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 Jwt}
* @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 header in the resulting {@link Jwt}
* @param name The header name
* @param value The header value
* @return the {@link Builder} for further configurations
*/
public Builder header(String name, Object value) {
this.headers.put(name, value);
return this;
}
/**
* Provides access to every {@link #header(String, Object)} declared so far with
* the possibility to add, replace, or remove.
* @param headersConsumer the consumer
* @return the {@link Builder} for further configurations
*/
public Builder headers(Consumer<Map<String, Object>> headersConsumer) {
headersConsumer.accept(this.headers);
return this;
}
/**
* Use this audience in the resulting {@link Jwt}
* @param audience The audience(s) to use
* @return the {@link Builder} for further configurations
*/
public Builder audience(Collection<String> audience) {
return claim(JwtClaimNames.AUD, audience);
}
/**
* Use this expiration in the resulting {@link Jwt}
* @param expiresAt The expiration to use
* @return the {@link Builder} for further configurations
*/
public Builder expiresAt(Instant expiresAt) {
this.claim(JwtClaimNames.EXP, expiresAt);
return this;
}
/**
* Use this identifier in the resulting {@link Jwt}
* @param jti The identifier to use
* @return the {@link Builder} for further configurations
*/
public Builder jti(String jti) {
this.claim(JwtClaimNames.JTI, jti);
return this;
}
/**
* Use this issued-at timestamp in the resulting {@link Jwt}
* @param issuedAt The issued-at timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder issuedAt(Instant issuedAt) {
this.claim(JwtClaimNames.IAT, issuedAt);
return this;
}
/**
* Use this issuer in the resulting {@link Jwt}
* @param issuer The issuer to use
* @return the {@link Builder} for further configurations
*/
public Builder issuer(String issuer) {
this.claim(JwtClaimNames.ISS, issuer);
return this;
}
/**
* Use this not-before timestamp in the resulting {@link Jwt}
* @param notBefore The not-before timestamp to use
* @return the {@link Builder} for further configurations
*/
public Builder notBefore(Instant notBefore) {
this.claim(JwtClaimNames.NBF, notBefore);
return this;
}
/**
* Use this subject in the resulting {@link Jwt}
* @param subject The subject to use
* @return the {@link Builder} for further configurations
*/
public Builder subject(String subject) {
this.claim(JwtClaimNames.SUB, subject);
return this;
}
/**
* Build the {@link Jwt}
* @return The constructed {@link Jwt}
*/
public Jwt build() {
Instant iat = toInstant(this.claims.get(JwtClaimNames.IAT));
Instant exp = toInstant(this.claims.get(JwtClaimNames.EXP));
return new Jwt(this.tokenValue, iat, exp, this.headers, this.claims);
}
private Instant toInstant(Object timestamp) {
if (timestamp != null) {
Assert.isInstanceOf(Instant.class, timestamp, "timestamps must be of type Instant");
}
return (Instant) timestamp;
}
}
}
| 7,779 | 28.808429 | 96 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusReactiveJwtDecoder.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.jwt;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.crypto.SecretKey;
import com.nimbusds.jose.Header;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.source.JWKSecurityContextJWKSet;
import com.nimbusds.jose.proc.BadJOSEException;
import com.nimbusds.jose.proc.JWKSecurityContext;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.proc.SingleKeyJWSKeySelector;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.WebClient;
/**
* An implementation of a {@link ReactiveJwtDecoder} that "decodes" a JSON Web
* Token (JWT) and additionally verifies it's digital signature if the JWT is a JSON Web
* Signature (JWS).
*
* <p>
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK internally.
*
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
* @see ReactiveJwtDecoder
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7517">JSON Web Key
* (JWK)</a>
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus
* JOSE + JWT SDK</a>
*/
public final class NimbusReactiveJwtDecoder implements ReactiveJwtDecoder {
private final Converter<JWT, Mono<JWTClaimsSet>> jwtProcessor;
private OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefault();
private Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MappedJwtClaimSetConverter
.withDefaults(Collections.emptyMap());
/**
* Constructs a {@code NimbusReactiveJwtDecoder} using the provided parameters.
* @param jwkSetUrl the JSON Web Key (JWK) Set {@code URL}
*/
public NimbusReactiveJwtDecoder(String jwkSetUrl) {
this(withJwkSetUri(jwkSetUrl).processor());
}
/**
* Constructs a {@code NimbusReactiveJwtDecoder} using the provided parameters.
* @param publicKey the {@code RSAPublicKey} used to verify the signature
* @since 5.2
*/
public NimbusReactiveJwtDecoder(RSAPublicKey publicKey) {
this(withPublicKey(publicKey).processor());
}
/**
* Constructs a {@code NimbusReactiveJwtDecoder} using the provided parameters.
* @param jwtProcessor the {@link Converter} used to process and verify the signed Jwt
* and return the Jwt Claim Set
* @since 5.2
*/
public NimbusReactiveJwtDecoder(Converter<JWT, Mono<JWTClaimsSet>> jwtProcessor) {
this.jwtProcessor = jwtProcessor;
}
/**
* Use the provided {@link OAuth2TokenValidator} to validate incoming {@link Jwt}s.
* @param jwtValidator the {@link OAuth2TokenValidator} to use
*/
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) {
Assert.notNull(jwtValidator, "jwtValidator cannot be null");
this.jwtValidator = jwtValidator;
}
/**
* Use the following {@link Converter} for manipulating the JWT's claim set
* @param claimSetConverter the {@link Converter} to use
*/
public void setClaimSetConverter(Converter<Map<String, Object>, Map<String, Object>> claimSetConverter) {
Assert.notNull(claimSetConverter, "claimSetConverter cannot be null");
this.claimSetConverter = claimSetConverter;
}
@Override
public Mono<Jwt> decode(String token) throws JwtException {
JWT jwt = parse(token);
if (jwt instanceof PlainJWT) {
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
}
return this.decode(jwt);
}
private JWT parse(String token) {
try {
return JWTParser.parse(token);
}
catch (Exception ex) {
throw new BadJwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
}
}
private Mono<Jwt> decode(JWT parsedToken) {
try {
// @formatter:off
return this.jwtProcessor.convert(parsedToken)
.map((set) -> createJwt(parsedToken, set))
.map(this::validateJwt)
.onErrorMap((ex) -> !(ex instanceof IllegalStateException) && !(ex instanceof JwtException),
(ex) -> new JwtException("An error occurred while attempting to decode the Jwt: ", ex));
// @formatter:on
}
catch (JwtException ex) {
throw ex;
}
catch (RuntimeException ex) {
throw new JwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
}
}
private Jwt createJwt(JWT parsedJwt, JWTClaimsSet jwtClaimsSet) {
try {
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
return Jwt.withTokenValue(parsedJwt.getParsedString()).headers((h) -> h.putAll(headers))
.claims((c) -> c.putAll(claims)).build();
}
catch (Exception ex) {
throw new BadJwtException("An error occurred while attempting to decode the Jwt: " + ex.getMessage(), ex);
}
}
private Jwt validateJwt(Jwt jwt) {
OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt);
if (result.hasErrors()) {
Collection<OAuth2Error> errors = result.getErrors();
String validationErrorString = getJwtValidationExceptionMessage(errors);
throw new JwtValidationException(validationErrorString, errors);
}
return jwt;
}
private String getJwtValidationExceptionMessage(Collection<OAuth2Error> errors) {
for (OAuth2Error oAuth2Error : errors) {
if (StringUtils.hasLength(oAuth2Error.getDescription())) {
return oAuth2Error.getDescription();
}
}
return "Unable to validate Jwt";
}
/**
* Use the given <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by making an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
* Provider Configuration Request</a> and using the values in the <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> to derive the needed
* <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a> uri.
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder} that will derive the
* JWK Set uri when {@link NimbusJwtDecoder.JwkSetUriJwtDecoderBuilder#build} is
* called
* @since 6.1
* @see JwtDecoders
*/
public static JwkSetUriReactiveJwtDecoderBuilder withIssuerLocation(String issuer) {
return new JwkSetUriReactiveJwtDecoderBuilder((web) -> ReactiveJwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(issuer, web).flatMap((configuration) -> {
try {
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
}
catch (IllegalStateException ex) {
return Mono.error(ex);
}
return Mono.just(configuration.get("jwks_uri").toString());
}), ReactiveJwtDecoderProviderConfigurationUtils::getJWSAlgorithms);
}
/**
* Use the given <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a>
* uri to validate JWTs.
* @param jwkSetUri the JWK Set uri to use
* @return a {@link JwkSetUriReactiveJwtDecoderBuilder} for further configurations
*
* @since 5.2
*/
public static JwkSetUriReactiveJwtDecoderBuilder withJwkSetUri(String jwkSetUri) {
return new JwkSetUriReactiveJwtDecoderBuilder(jwkSetUri);
}
/**
* Use the given public key to validate JWTs
* @param key the public key to use
* @return a {@link PublicKeyReactiveJwtDecoderBuilder} for further configurations
*
* @since 5.2
*/
public static PublicKeyReactiveJwtDecoderBuilder withPublicKey(RSAPublicKey key) {
return new PublicKeyReactiveJwtDecoderBuilder(key);
}
/**
* Use the given {@code SecretKey} to validate the MAC on a JSON Web Signature (JWS).
* @param secretKey the {@code SecretKey} used to validate the MAC
* @return a {@link SecretKeyReactiveJwtDecoderBuilder} for further configurations
*
* @since 5.2
*/
public static SecretKeyReactiveJwtDecoderBuilder withSecretKey(SecretKey secretKey) {
return new SecretKeyReactiveJwtDecoderBuilder(secretKey);
}
/**
* Use the given {@link Function} to validate JWTs
* @param source the {@link Function}
* @return a {@link JwkSourceReactiveJwtDecoderBuilder} for further configurations
*
* @since 5.2
*/
public static JwkSourceReactiveJwtDecoderBuilder withJwkSource(Function<SignedJWT, Flux<JWK>> source) {
return new JwkSourceReactiveJwtDecoderBuilder(source);
}
private static <C extends SecurityContext> JWTClaimsSet createClaimsSet(JWTProcessor<C> jwtProcessor,
JWT parsedToken, C context) {
try {
return jwtProcessor.process(parsedToken, context);
}
catch (BadJOSEException ex) {
throw new BadJwtException("Failed to validate the token", ex);
}
catch (JOSEException ex) {
throw new JwtException("Failed to validate the token", ex);
}
}
/**
* A builder for creating {@link NimbusReactiveJwtDecoder} instances based on a
* <a target="_blank" href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a>
* uri.
*
* @since 5.2
*/
public static final class JwkSetUriReactiveJwtDecoderBuilder {
private static final Duration FOREVER = Duration.ofMillis(Long.MAX_VALUE);
private Function<WebClient, Mono<String>> jwkSetUri;
private Function<ReactiveRemoteJWKSource, Mono<Set<JWSAlgorithm>>> defaultAlgorithms = (source) -> Mono
.just(Set.of(JWSAlgorithm.RS256));
private Set<SignatureAlgorithm> signatureAlgorithms = new HashSet<>();
private WebClient webClient = WebClient.create();
private BiFunction<ReactiveRemoteJWKSource, ConfigurableJWTProcessor<JWKSecurityContext>, Mono<ConfigurableJWTProcessor<JWKSecurityContext>>> jwtProcessorCustomizer;
private JwkSetUriReactiveJwtDecoderBuilder(String jwkSetUri) {
Assert.hasText(jwkSetUri, "jwkSetUri cannot be empty");
this.jwkSetUri = (web) -> Mono.just(jwkSetUri);
this.jwtProcessorCustomizer = (source, processor) -> Mono.just(processor);
}
private JwkSetUriReactiveJwtDecoderBuilder(Function<WebClient, Mono<String>> jwkSetUri,
Function<ReactiveRemoteJWKSource, Mono<Set<JWSAlgorithm>>> defaultAlgorithms) {
Assert.notNull(jwkSetUri, "jwkSetUri cannot be null");
Assert.notNull(defaultAlgorithms, "defaultAlgorithms cannot be null");
this.jwkSetUri = jwkSetUri;
this.defaultAlgorithms = defaultAlgorithms;
this.jwtProcessorCustomizer = (source, processor) -> Mono.just(processor);
}
/**
* Append the given signing
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a> to the set of algorithms to use.
* @param signatureAlgorithm the algorithm to use
* @return a {@link JwkSetUriReactiveJwtDecoderBuilder} for further configurations
*/
public JwkSetUriReactiveJwtDecoderBuilder jwsAlgorithm(SignatureAlgorithm signatureAlgorithm) {
Assert.notNull(signatureAlgorithm, "sig cannot be null");
this.signatureAlgorithms.add(signatureAlgorithm);
return this;
}
/**
* Configure the list of
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithms</a> to use with the given {@link Consumer}.
* @param signatureAlgorithmsConsumer a {@link Consumer} for further configuring
* the algorithm list
* @return a {@link JwkSetUriReactiveJwtDecoderBuilder} for further configurations
*/
public JwkSetUriReactiveJwtDecoderBuilder jwsAlgorithms(
Consumer<Set<SignatureAlgorithm>> signatureAlgorithmsConsumer) {
Assert.notNull(signatureAlgorithmsConsumer, "signatureAlgorithmsConsumer cannot be null");
signatureAlgorithmsConsumer.accept(this.signatureAlgorithms);
return this;
}
/**
* Use the given {@link WebClient} to coordinate with the authorization servers
* indicated in the <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK
* Set</a> uri as well as the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>.
* @param webClient
* @return a {@link JwkSetUriReactiveJwtDecoderBuilder} for further configurations
*/
public JwkSetUriReactiveJwtDecoderBuilder webClient(WebClient webClient) {
Assert.notNull(webClient, "webClient cannot be null");
this.webClient = webClient;
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusReactiveJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link JwkSetUriReactiveJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public JwkSetUriReactiveJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<JWKSecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = (source, processor) -> {
jwtProcessorCustomizer.accept(processor);
return Mono.just(processor);
};
return this;
}
JwkSetUriReactiveJwtDecoderBuilder jwtProcessorCustomizer(
BiFunction<ReactiveRemoteJWKSource, ConfigurableJWTProcessor<JWKSecurityContext>, Mono<ConfigurableJWTProcessor<JWKSecurityContext>>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusReactiveJwtDecoder}.
* @return the configured {@link NimbusReactiveJwtDecoder}
*/
public NimbusReactiveJwtDecoder build() {
return new NimbusReactiveJwtDecoder(processor());
}
Mono<JWSKeySelector<JWKSecurityContext>> jwsKeySelector(ReactiveRemoteJWKSource source) {
JWKSecurityContextJWKSet jwkSource = new JWKSecurityContextJWKSet();
if (this.signatureAlgorithms.isEmpty()) {
return this.defaultAlgorithms.apply(source)
.map((algorithms) -> new JWSVerificationKeySelector<>(algorithms, jwkSource));
}
Set<JWSAlgorithm> jwsAlgorithms = new HashSet<>();
for (SignatureAlgorithm signatureAlgorithm : this.signatureAlgorithms) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(signatureAlgorithm.getName());
jwsAlgorithms.add(jwsAlgorithm);
}
return Mono.just(new JWSVerificationKeySelector<>(jwsAlgorithms, jwkSource));
}
Converter<JWT, Mono<JWTClaimsSet>> processor() {
DefaultJWTProcessor<JWKSecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
ReactiveRemoteJWKSource source = new ReactiveRemoteJWKSource(this.jwkSetUri.apply(this.webClient));
source.setWebClient(this.webClient);
Mono<JWSKeySelector<JWKSecurityContext>> jwsKeySelector = jwsKeySelector(source);
Mono<Tuple2<ConfigurableJWTProcessor<JWKSecurityContext>, Function<JWSAlgorithm, Boolean>>> jwtProcessorMono = jwsKeySelector
.flatMap((selector) -> {
jwtProcessor.setJWSKeySelector(selector);
return this.jwtProcessorCustomizer.apply(source, jwtProcessor);
}).map((processor) -> Tuples.of(processor, getExpectedJwsAlgorithms(processor.getJWSKeySelector())))
.cache((processor) -> FOREVER, (ex) -> Duration.ZERO, () -> Duration.ZERO);
return (jwt) -> {
return jwtProcessorMono.flatMap((tuple) -> {
JWTProcessor<JWKSecurityContext> processor = tuple.getT1();
Function<JWSAlgorithm, Boolean> expectedJwsAlgorithms = tuple.getT2();
JWKSelector selector = createSelector(expectedJwsAlgorithms, jwt.getHeader());
return source.get(selector)
.onErrorMap((ex) -> new IllegalStateException("Could not obtain the keys", ex))
.map((jwkList) -> createClaimsSet(processor, jwt, new JWKSecurityContext(jwkList)));
});
};
}
private Function<JWSAlgorithm, Boolean> getExpectedJwsAlgorithms(JWSKeySelector<?> jwsKeySelector) {
if (jwsKeySelector instanceof JWSVerificationKeySelector) {
return ((JWSVerificationKeySelector<?>) jwsKeySelector)::isAllowed;
}
throw new IllegalArgumentException("Unsupported key selector type " + jwsKeySelector.getClass());
}
private JWKSelector createSelector(Function<JWSAlgorithm, Boolean> expectedJwsAlgorithms, Header header) {
JWSHeader jwsHeader = (JWSHeader) header;
if (!expectedJwsAlgorithms.apply(jwsHeader.getAlgorithm())) {
throw new BadJwtException("Unsupported algorithm of " + header.getAlgorithm());
}
return new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
}
}
/**
* A builder for creating {@link NimbusReactiveJwtDecoder} instances based on a public
* key.
*
* @since 5.2
*/
public static final class PublicKeyReactiveJwtDecoderBuilder {
private final RSAPublicKey key;
private JWSAlgorithm jwsAlgorithm;
private Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer;
private PublicKeyReactiveJwtDecoderBuilder(RSAPublicKey key) {
Assert.notNull(key, "key cannot be null");
this.key = key;
this.jwsAlgorithm = JWSAlgorithm.RS256;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Use the given signing
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a>. The value should be one of
* <a href="https://tools.ietf.org/html/rfc7518#section-3.3" target=
* "_blank">RS256, RS384, or RS512</a>.
* @param signatureAlgorithm the algorithm to use
* @return a {@link PublicKeyReactiveJwtDecoderBuilder} for further configurations
*/
public PublicKeyReactiveJwtDecoderBuilder signatureAlgorithm(SignatureAlgorithm signatureAlgorithm) {
Assert.notNull(signatureAlgorithm, "signatureAlgorithm cannot be null");
this.jwsAlgorithm = JWSAlgorithm.parse(signatureAlgorithm.getName());
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusReactiveJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link PublicKeyReactiveJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public PublicKeyReactiveJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusReactiveJwtDecoder}.
* @return the configured {@link NimbusReactiveJwtDecoder}
*/
public NimbusReactiveJwtDecoder build() {
return new NimbusReactiveJwtDecoder(processor());
}
Converter<JWT, Mono<JWTClaimsSet>> processor() {
Assert.state(JWSAlgorithm.Family.RSA.contains(this.jwsAlgorithm),
() -> "The provided key is of type RSA; however the signature algorithm is of some other type: "
+ this.jwsAlgorithm + ". Please indicate one of RS256, RS384, or RS512.");
JWSKeySelector<SecurityContext> jwsKeySelector = new SingleKeyJWSKeySelector<>(this.jwsAlgorithm, this.key);
DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
// Spring Security validates the claim set independent from Nimbus
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return (jwt) -> Mono.fromCallable(() -> createClaimsSet(jwtProcessor, jwt, null));
}
}
/**
* A builder for creating {@link NimbusReactiveJwtDecoder} instances based on a
* {@code SecretKey}.
*
* @since 5.2
*/
public static final class SecretKeyReactiveJwtDecoderBuilder {
private final SecretKey secretKey;
private JWSAlgorithm jwsAlgorithm = JWSAlgorithm.HS256;
private Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer;
private SecretKeyReactiveJwtDecoderBuilder(SecretKey secretKey) {
Assert.notNull(secretKey, "secretKey cannot be null");
this.secretKey = secretKey;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Use the given
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a> when generating the MAC.
*
* The value should be one of
* <a href="https://tools.ietf.org/html/rfc7518#section-3.2" target=
* "_blank">HS256, HS384 or HS512</a>.
* @param macAlgorithm the MAC algorithm to use
* @return a {@link SecretKeyReactiveJwtDecoderBuilder} for further configurations
*/
public SecretKeyReactiveJwtDecoderBuilder macAlgorithm(MacAlgorithm macAlgorithm) {
Assert.notNull(macAlgorithm, "macAlgorithm cannot be null");
this.jwsAlgorithm = JWSAlgorithm.parse(macAlgorithm.getName());
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusReactiveJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link SecretKeyReactiveJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public SecretKeyReactiveJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusReactiveJwtDecoder}.
* @return the configured {@link NimbusReactiveJwtDecoder}
*/
public NimbusReactiveJwtDecoder build() {
return new NimbusReactiveJwtDecoder(processor());
}
Converter<JWT, Mono<JWTClaimsSet>> processor() {
JWSKeySelector<SecurityContext> jwsKeySelector = new SingleKeyJWSKeySelector<>(this.jwsAlgorithm,
this.secretKey);
DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
// Spring Security validates the claim set independent from Nimbus
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return (jwt) -> Mono.fromCallable(() -> createClaimsSet(jwtProcessor, jwt, null));
}
}
/**
* A builder for creating {@link NimbusReactiveJwtDecoder} instances.
*
* @since 5.2
*/
public static final class JwkSourceReactiveJwtDecoderBuilder {
private final Function<SignedJWT, Flux<JWK>> jwkSource;
private JWSAlgorithm jwsAlgorithm = JWSAlgorithm.RS256;
private Consumer<ConfigurableJWTProcessor<JWKSecurityContext>> jwtProcessorCustomizer;
private JwkSourceReactiveJwtDecoderBuilder(Function<SignedJWT, Flux<JWK>> jwkSource) {
Assert.notNull(jwkSource, "jwkSource cannot be null");
this.jwkSource = jwkSource;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Use the given signing
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a>.
* @param jwsAlgorithm the algorithm to use
* @return a {@link JwkSourceReactiveJwtDecoderBuilder} for further configurations
*/
public JwkSourceReactiveJwtDecoderBuilder jwsAlgorithm(JwsAlgorithm jwsAlgorithm) {
Assert.notNull(jwsAlgorithm, "jwsAlgorithm cannot be null");
this.jwsAlgorithm = JWSAlgorithm.parse(jwsAlgorithm.getName());
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusReactiveJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link JwkSourceReactiveJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public JwkSourceReactiveJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<JWKSecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusReactiveJwtDecoder}.
* @return the configured {@link NimbusReactiveJwtDecoder}
*/
public NimbusReactiveJwtDecoder build() {
return new NimbusReactiveJwtDecoder(processor());
}
Converter<JWT, Mono<JWTClaimsSet>> processor() {
JWKSecurityContextJWKSet jwkSource = new JWKSecurityContextJWKSet();
JWSKeySelector<JWKSecurityContext> jwsKeySelector = new JWSVerificationKeySelector<>(this.jwsAlgorithm,
jwkSource);
DefaultJWTProcessor<JWKSecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return (jwt) -> {
if (jwt instanceof SignedJWT) {
return this.jwkSource.apply((SignedJWT) jwt)
.onErrorMap((e) -> new IllegalStateException("Could not obtain the keys", e)).collectList()
.map((jwks) -> createClaimsSet(jwtProcessor, jwt, new JWKSecurityContext(jwks)));
}
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
};
}
}
}
| 27,642 | 38.603152 | 167 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoderFactory.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.jwt;
/**
* A factory for {@link ReactiveJwtDecoder}(s). This factory should be supplied with a
* type that provides contextual information used to create a specific
* {@code ReactiveJwtDecoder}.
*
* @param <C> The type that provides contextual information used to create a specific
* {@code ReactiveJwtDecoder}.
* @author Joe Grandja
* @since 5.2
* @see ReactiveJwtDecoder
*/
@FunctionalInterface
public interface ReactiveJwtDecoderFactory<C> {
/**
* Creates a {@code ReactiveJwtDecoder} using the supplied "contextual" type.
* @param context the type that provides contextual information
* @return a {@link ReactiveJwtDecoder}
*/
ReactiveJwtDecoder createDecoder(C context);
}
| 1,368 | 32.390244 | 86 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/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 JSON Web Token (JWT).
*/
package org.springframework.security.oauth2.jwt;
| 755 | 35 | 75 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtEncoder.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.jwt;
/**
* Implementations of this interface are responsible for encoding a JSON Web Token (JWT)
* to it's compact claims representation format.
*
* <p>
* JWTs may be represented using the JWS Compact Serialization format for a JSON Web
* Signature (JWS) structure or JWE Compact Serialization format for a JSON Web Encryption
* (JWE) structure. Therefore, implementors are responsible for signing a JWS and/or
* encrypting a JWE.
*
* @author Anoop Garlapati
* @author Joe Grandja
* @since 5.6
* @see Jwt
* @see JwtEncoderParameters
* @see JwtDecoder
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516">JSON Web Encryption
* (JWE)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS
* Compact Serialization</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-3.1">JWE
* Compact Serialization</a>
*/
@FunctionalInterface
public interface JwtEncoder {
/**
* Encode the JWT to it's compact claims representation format.
* @param parameters the parameters containing the JOSE header and JWT Claims Set
* @return a {@link Jwt}
* @throws JwtEncodingException if an error occurs while attempting to encode the JWT
*/
Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException;
}
| 2,171 | 36.448276 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoderFactory.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.jwt;
/**
* A factory for {@link JwtDecoder}(s). This factory should be supplied with a type that
* provides contextual information used to create a specific {@code JwtDecoder}.
*
* @param <C> The type that provides contextual information used to create a specific
* {@code JwtDecoder}.
* @author Joe Grandja
* @since 5.2
* @see JwtDecoder
*/
@FunctionalInterface
public interface JwtDecoderFactory<C> {
/**
* Creates a {@code JwtDecoder} using the supplied "contextual" type.
* @param context the type that provides contextual information
* @return a {@link JwtDecoder}
*/
JwtDecoder createDecoder(C context);
}
| 1,301 | 31.55 | 88 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JoseHeaderNames.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.jwt;
/**
* The Registered Header Parameter Names defined by the JSON Web Token (JWT), JSON Web
* Signature (JWS) and JSON Web Encryption (JWE) specifications that may be contained in
* the JOSE Header of a JWT.
*
* @author Anoop Garlapati
* @author Joe Grandja
* @since 5.6
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519#section-5">JWT JOSE
* Header</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JWS JOSE
* Header</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-4">JWE JOSE
* Header</a>
*/
public final class JoseHeaderNames {
/**
* {@code alg} - the algorithm header identifies the cryptographic algorithm used to
* secure a JWS or JWE
*/
public static final String ALG = "alg";
/**
* {@code jku} - the JWK Set URL header is a URI that refers to a resource for a set
* of JSON-encoded public keys, one of which corresponds to the key used to digitally
* sign a JWS or encrypt a JWE
*/
public static final String JKU = "jku";
/**
* {@code jwk} - the JSON Web Key header is the public key that corresponds to the key
* used to digitally sign a JWS or encrypt a JWE
*/
public static final String JWK = "jwk";
/**
* {@code kid} - the key ID header is a hint indicating which key was used to secure a
* JWS or JWE
*/
public static final String KID = "kid";
/**
* {@code x5u} - the X.509 URL header is a URI that refers to a resource for the X.509
* public key certificate or certificate chain corresponding to the key used to
* digitally sign a JWS or encrypt a JWE
*/
public static final String X5U = "x5u";
/**
* {@code x5c} - the X.509 certificate chain header contains the X.509 public key
* certificate or certificate chain corresponding to the key used to digitally sign a
* JWS or encrypt a JWE
*/
public static final String X5C = "x5c";
/**
* {@code x5t} - the X.509 certificate SHA-1 thumbprint header is a base64url-encoded
* SHA-1 thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate
* corresponding to the key used to digitally sign a JWS or encrypt a JWE
*/
public static final String X5T = "x5t";
/**
* {@code x5t#S256} - the X.509 certificate SHA-256 thumbprint header is a
* base64url-encoded SHA-256 thumbprint (a.k.a. digest) of the DER encoding of the
* X.509 certificate corresponding to the key used to digitally sign a JWS or encrypt
* a JWE
*/
public static final String X5T_S256 = "x5t#S256";
/**
* {@code typ} - the type header is used by JWS/JWE applications to declare the media
* type of a JWS/JWE
*/
public static final String TYP = "typ";
/**
* {@code cty} - the content type header is used by JWS/JWE applications to declare
* the media type of the secured content (the payload)
*/
public static final String CTY = "cty";
/**
* {@code crit} - the critical header indicates that extensions to the JWS/JWE/JWA
* specifications are being used that MUST be understood and processed
*/
public static final String CRIT = "crit";
private JoseHeaderNames() {
}
}
| 3,788 | 32.830357 | 88 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimValidator.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.jwt;
import java.util.function.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.util.Assert;
/**
* Validates a claim in a {@link Jwt} against a provided
* {@link java.util.function.Predicate}
*
* @author Zeeshan Adnan
* @since 5.3
*/
public final class JwtClaimValidator<T> implements OAuth2TokenValidator<Jwt> {
private final Log logger = LogFactory.getLog(getClass());
private final String claim;
private final Predicate<T> test;
private final OAuth2Error error;
/**
* Constructs a {@link JwtClaimValidator} using the provided parameters
* @param claim - is the name of the claim in {@link Jwt} to validate.
* @param test - is the predicate function for the claim to test against.
*/
public JwtClaimValidator(String claim, Predicate<T> test) {
Assert.notNull(claim, "claim can not be null");
Assert.notNull(test, "test can not be null");
this.claim = claim;
this.test = test;
this.error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, "The " + this.claim + " claim is not valid",
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
T claimValue = token.getClaim(this.claim);
if (this.test.test(claimValue)) {
return OAuth2TokenValidatorResult.success();
}
this.logger.debug(this.error.getDescription());
return OAuth2TokenValidatorResult.failure(this.error);
}
}
| 2,460 | 32.712329 | 107 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtException.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.jwt;
/**
* Base exception for all JSON Web Token (JWT) related errors.
*
* @author Joe Grandja
* @since 5.0
*/
public class JwtException extends RuntimeException {
/**
* Constructs a {@code JwtException} using the provided parameters.
* @param message the detail message
*/
public JwtException(String message) {
super(message);
}
/**
* Constructs a {@code JwtException} using the provided parameters.
* @param message the detail message
* @param cause the root cause
*/
public JwtException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,252 | 26.844444 | 75 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/MappedJwtClaimSetConverter.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.jwt;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.util.Assert;
/**
* Converts a JWT claim set, claim by claim. Can be configured with custom converters by
* claim name.
*
* @author Josh Cummings
* @since 5.1
* @see ClaimTypeConverter
*/
public final class MappedJwtClaimSetConverter implements Converter<Map<String, Object>, Map<String, Object>> {
private static final ConversionService CONVERSION_SERVICE = ClaimConversionService.getSharedInstance();
private static final TypeDescriptor OBJECT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Object.class);
private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
private static final TypeDescriptor INSTANT_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(Instant.class);
private static final TypeDescriptor URL_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(URL.class);
private final Map<String, Converter<Object, ?>> claimTypeConverters;
/**
* Constructs a {@link MappedJwtClaimSetConverter} with the provided arguments
*
* This will completely replace any set of default converters.
*
* A converter that returns {@code null} removes the claim from the claim set. A
* converter that returns a non-{@code null} value adds or replaces that claim in the
* claim set.
* @param claimTypeConverters The {@link Map} of converters to use
*/
public MappedJwtClaimSetConverter(Map<String, Converter<Object, ?>> claimTypeConverters) {
Assert.notNull(claimTypeConverters, "claimTypeConverters cannot be null");
this.claimTypeConverters = claimTypeConverters;
}
/**
* Construct a {@link MappedJwtClaimSetConverter}, overriding individual claim
* converters with the provided {@link Map} of {@link Converter}s.
*
* For example, the following would give an instance that is configured with only the
* default claim converters:
*
* <pre>
* MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
* </pre>
*
* Or, the following would supply a custom converter for the subject, leaving the
* other defaults in place:
*
* <pre>
* MappedJwtClaimsSetConverter.withDefaults(
* Collections.singletonMap(JwtClaimNames.SUB, new UserDetailsServiceJwtSubjectConverter()));
* </pre>
*
* To completely replace the underlying {@link Map} of converters, see
* {@link MappedJwtClaimSetConverter#MappedJwtClaimSetConverter(Map)}.
*
* A converter that returns {@code null} removes the claim from the claim set. A
* converter that returns a non-{@code null} value adds or replaces that claim in the
* claim set.
* @param claimTypeConverters
* @return An instance of {@link MappedJwtClaimSetConverter} that contains the
* converters provided, plus any defaults that were not overridden.
*/
public static MappedJwtClaimSetConverter withDefaults(Map<String, Converter<Object, ?>> claimTypeConverters) {
Assert.notNull(claimTypeConverters, "claimTypeConverters cannot be null");
Converter<Object, ?> stringConverter = getConverter(STRING_TYPE_DESCRIPTOR);
Converter<Object, ?> collectionStringConverter = getConverter(
TypeDescriptor.collection(Collection.class, STRING_TYPE_DESCRIPTOR));
Map<String, Converter<Object, ?>> claimNameToConverter = new HashMap<>();
claimNameToConverter.put(JwtClaimNames.AUD, collectionStringConverter);
claimNameToConverter.put(JwtClaimNames.EXP, MappedJwtClaimSetConverter::convertInstant);
claimNameToConverter.put(JwtClaimNames.IAT, MappedJwtClaimSetConverter::convertInstant);
claimNameToConverter.put(JwtClaimNames.ISS, MappedJwtClaimSetConverter::convertIssuer);
claimNameToConverter.put(JwtClaimNames.JTI, stringConverter);
claimNameToConverter.put(JwtClaimNames.NBF, MappedJwtClaimSetConverter::convertInstant);
claimNameToConverter.put(JwtClaimNames.SUB, stringConverter);
claimNameToConverter.putAll(claimTypeConverters);
return new MappedJwtClaimSetConverter(claimNameToConverter);
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
return (source) -> CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, targetDescriptor);
}
private static Instant convertInstant(Object source) {
if (source == null) {
return null;
}
Instant result = (Instant) CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, INSTANT_TYPE_DESCRIPTOR);
Assert.state(result != null, () -> "Could not coerce " + source + " into an Instant");
return result;
}
private static String convertIssuer(Object source) {
if (source == null) {
return null;
}
URL result = (URL) CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, URL_TYPE_DESCRIPTOR);
if (result != null) {
return result.toExternalForm();
}
if (source instanceof String && ((String) source).contains(":")) {
try {
return new URI((String) source).toString();
}
catch (Exception ex) {
throw new IllegalStateException("Could not coerce " + source + " into a URI String", ex);
}
}
return (String) CONVERSION_SERVICE.convert(source, OBJECT_TYPE_DESCRIPTOR, STRING_TYPE_DESCRIPTOR);
}
@Override
public Map<String, Object> convert(Map<String, Object> claims) {
Assert.notNull(claims, "claims cannot be null");
Map<String, Object> mappedClaims = new HashMap<>(claims);
for (Map.Entry<String, Converter<Object, ?>> entry : this.claimTypeConverters.entrySet()) {
String claimName = entry.getKey();
Converter<Object, ?> converter = entry.getValue();
if (converter != null) {
Object claim = claims.get(claimName);
Object mappedClaim = converter.convert(claim);
mappedClaims.compute(claimName, (key, value) -> mappedClaim);
}
}
Instant issuedAt = (Instant) mappedClaims.get(JwtClaimNames.IAT);
Instant expiresAt = (Instant) mappedClaims.get(JwtClaimNames.EXP);
if (issuedAt == null && expiresAt != null) {
mappedClaims.put(JwtClaimNames.IAT, expiresAt.minusSeconds(1));
}
return mappedClaims;
}
}
| 7,040 | 40.417647 | 113 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimsSet.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.jwt;
import java.net.URL;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.util.Assert;
/**
* The {@link Jwt JWT} Claims Set is a JSON object representing the claims conveyed by a
* JSON Web Token.
*
* @author Anoop Garlapati
* @author Joe Grandja
* @since 5.6
* @see Jwt
* @see JwtClaimAccessor
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519#section-4">JWT Claims
* Set</a>
*/
public final class JwtClaimsSet implements JwtClaimAccessor {
private final Map<String, Object> claims;
private JwtClaimsSet(Map<String, Object> claims) {
this.claims = Collections.unmodifiableMap(new HashMap<>(claims));
}
@Override
public Map<String, Object> getClaims() {
return this.claims;
}
/**
* Returns a new {@link Builder}.
* @return the {@link Builder}
*/
public static Builder builder() {
return new Builder();
}
/**
* Returns a new {@link Builder}, initialized with the provided {@code claims}.
* @param claims a JWT claims set
* @return the {@link Builder}
*/
public static Builder from(JwtClaimsSet claims) {
return new Builder(claims);
}
/**
* A builder for {@link JwtClaimsSet}.
*/
public static final class Builder {
private final Map<String, Object> claims = new HashMap<>();
private Builder() {
}
private Builder(JwtClaimsSet claims) {
Assert.notNull(claims, "claims cannot be null");
this.claims.putAll(claims.getClaims());
}
/**
* Sets the issuer {@code (iss)} claim, which identifies the principal that issued
* the JWT.
* @param issuer the issuer identifier
* @return the {@link Builder}
*/
public Builder issuer(String issuer) {
return claim(JwtClaimNames.ISS, issuer);
}
/**
* Sets the subject {@code (sub)} claim, which identifies the principal that is
* the subject of the JWT.
* @param subject the subject identifier
* @return the {@link Builder}
*/
public Builder subject(String subject) {
return claim(JwtClaimNames.SUB, subject);
}
/**
* Sets the audience {@code (aud)} claim, which identifies the recipient(s) that
* the JWT is intended for.
* @param audience the audience that this JWT is intended for
* @return the {@link Builder}
*/
public Builder audience(List<String> audience) {
return claim(JwtClaimNames.AUD, audience);
}
/**
* Sets the expiration time {@code (exp)} claim, which identifies the time on or
* after which the JWT MUST NOT be accepted for processing.
* @param expiresAt the time on or after which the JWT MUST NOT be accepted for
* processing
* @return the {@link Builder}
*/
public Builder expiresAt(Instant expiresAt) {
return claim(JwtClaimNames.EXP, expiresAt);
}
/**
* Sets the not before {@code (nbf)} claim, which identifies the time before which
* the JWT MUST NOT be accepted for processing.
* @param notBefore the time before which the JWT MUST NOT be accepted for
* processing
* @return the {@link Builder}
*/
public Builder notBefore(Instant notBefore) {
return claim(JwtClaimNames.NBF, notBefore);
}
/**
* Sets the issued at {@code (iat)} claim, which identifies the time at which the
* JWT was issued.
* @param issuedAt the time at which the JWT was issued
* @return the {@link Builder}
*/
public Builder issuedAt(Instant issuedAt) {
return claim(JwtClaimNames.IAT, issuedAt);
}
/**
* Sets the JWT ID {@code (jti)} claim, which provides a unique identifier for the
* JWT.
* @param jti the unique identifier for the JWT
* @return the {@link Builder}
*/
public Builder id(String jti) {
return claim(JwtClaimNames.JTI, jti);
}
/**
* Sets the claim.
* @param name the claim name
* @param value the claim value
* @return the {@link Builder}
*/
public Builder claim(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.put(name, value);
return this;
}
/**
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
*/
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Builds a new {@link JwtClaimsSet}.
* @return a {@link JwtClaimsSet}
*/
public JwtClaimsSet build() {
Assert.notEmpty(this.claims, "claims cannot be empty");
// The value of the 'iss' claim is a String or URL (StringOrURI).
// Attempt to convert to URL.
Object issuer = this.claims.get(JwtClaimNames.ISS);
if (issuer != null) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class);
if (convertedValue != null) {
this.claims.put(JwtClaimNames.ISS, convertedValue);
}
}
return new JwtClaimsSet(this.claims);
}
}
}
| 5,810 | 27.346341 | 95 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtDecoder.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.jwt;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.crypto.SecretKey;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.RemoteKeySourceException;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.source.JWKSetCache;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.jwk.source.RemoteJWKSet;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.proc.SingleKeyJWSKeySelector;
import com.nimbusds.jose.util.Resource;
import com.nimbusds.jose.util.ResourceRetriever;
import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser;
import com.nimbusds.jwt.PlainJWT;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import com.nimbusds.jwt.proc.DefaultJWTProcessor;
import com.nimbusds.jwt.proc.JWTProcessor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.Cache;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* A low-level Nimbus implementation of {@link JwtDecoder} which takes a raw Nimbus
* configuration.
*
* @author Josh Cummings
* @author Joe Grandja
* @author Mykyta Bezverkhyi
* @since 5.2
*/
public final class NimbusJwtDecoder implements JwtDecoder {
private final Log logger = LogFactory.getLog(getClass());
private static final String DECODING_ERROR_MESSAGE_TEMPLATE = "An error occurred while attempting to decode the Jwt: %s";
private final JWTProcessor<SecurityContext> jwtProcessor;
private Converter<Map<String, Object>, Map<String, Object>> claimSetConverter = MappedJwtClaimSetConverter
.withDefaults(Collections.emptyMap());
private OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefault();
/**
* Configures a {@link NimbusJwtDecoder} with the given parameters
* @param jwtProcessor - the {@link JWTProcessor} to use
*/
public NimbusJwtDecoder(JWTProcessor<SecurityContext> jwtProcessor) {
Assert.notNull(jwtProcessor, "jwtProcessor cannot be null");
this.jwtProcessor = jwtProcessor;
}
/**
* Use this {@link Jwt} Validator
* @param jwtValidator - the Jwt Validator to use
*/
public void setJwtValidator(OAuth2TokenValidator<Jwt> jwtValidator) {
Assert.notNull(jwtValidator, "jwtValidator cannot be null");
this.jwtValidator = jwtValidator;
}
/**
* Use the following {@link Converter} for manipulating the JWT's claim set
* @param claimSetConverter the {@link Converter} to use
*/
public void setClaimSetConverter(Converter<Map<String, Object>, Map<String, Object>> claimSetConverter) {
Assert.notNull(claimSetConverter, "claimSetConverter cannot be null");
this.claimSetConverter = claimSetConverter;
}
/**
* Decode and validate the JWT from its compact claims representation format
* @param token the JWT value
* @return a validated {@link Jwt}
* @throws JwtException
*/
@Override
public Jwt decode(String token) throws JwtException {
JWT jwt = parse(token);
if (jwt instanceof PlainJWT) {
this.logger.trace("Failed to decode unsigned token");
throw new BadJwtException("Unsupported algorithm of " + jwt.getHeader().getAlgorithm());
}
Jwt createdJwt = createJwt(token, jwt);
return validateJwt(createdJwt);
}
private JWT parse(String token) {
try {
return JWTParser.parse(token);
}
catch (Exception ex) {
this.logger.trace("Failed to parse token", ex);
throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
}
}
private Jwt createJwt(String token, JWT parsedJwt) {
try {
// Verify the signature
JWTClaimsSet jwtClaimsSet = this.jwtProcessor.process(parsedJwt, null);
Map<String, Object> headers = new LinkedHashMap<>(parsedJwt.getHeader().toJSONObject());
Map<String, Object> claims = this.claimSetConverter.convert(jwtClaimsSet.getClaims());
// @formatter:off
return Jwt.withTokenValue(token)
.headers((h) -> h.putAll(headers))
.claims((c) -> c.putAll(claims))
.build();
// @formatter:on
}
catch (RemoteKeySourceException ex) {
this.logger.trace("Failed to retrieve JWK set", ex);
if (ex.getCause() instanceof ParseException) {
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed Jwk set"), ex);
}
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
}
catch (JOSEException ex) {
this.logger.trace("Failed to process JWT", ex);
throw new JwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
}
catch (Exception ex) {
this.logger.trace("Failed to process JWT", ex);
if (ex.getCause() instanceof ParseException) {
throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, "Malformed payload"), ex);
}
throw new BadJwtException(String.format(DECODING_ERROR_MESSAGE_TEMPLATE, ex.getMessage()), ex);
}
}
private Jwt validateJwt(Jwt jwt) {
OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt);
if (result.hasErrors()) {
Collection<OAuth2Error> errors = result.getErrors();
String validationErrorString = getJwtValidationExceptionMessage(errors);
throw new JwtValidationException(validationErrorString, errors);
}
return jwt;
}
private String getJwtValidationExceptionMessage(Collection<OAuth2Error> errors) {
for (OAuth2Error oAuth2Error : errors) {
if (StringUtils.hasLength(oAuth2Error.getDescription())) {
return String.format(DECODING_ERROR_MESSAGE_TEMPLATE, oAuth2Error.getDescription());
}
}
return "Unable to validate Jwt";
}
/**
* Use the given <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by making an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
* Provider Configuration Request</a> and using the values in the <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> to derive the needed
* <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a> uri.
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link JwkSetUriJwtDecoderBuilder} that will derive the JWK Set uri when
* {@link JwkSetUriJwtDecoderBuilder#build} is called
* @since 6.1
* @see JwtDecoders
*/
public static JwkSetUriJwtDecoderBuilder withIssuerLocation(String issuer) {
return new JwkSetUriJwtDecoderBuilder((rest) -> {
Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(issuer, rest);
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
return configuration.get("jwks_uri").toString();
}, JwtDecoderProviderConfigurationUtils::getJWSAlgorithms);
}
/**
* Use the given <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a>
* uri.
* @param jwkSetUri the JWK Set uri to use
* @return a {@link JwkSetUriJwtDecoderBuilder} for further configurations
*/
public static JwkSetUriJwtDecoderBuilder withJwkSetUri(String jwkSetUri) {
return new JwkSetUriJwtDecoderBuilder(jwkSetUri);
}
/**
* Use the given public key to validate JWTs
* @param key the public key to use
* @return a {@link PublicKeyJwtDecoderBuilder} for further configurations
*/
public static PublicKeyJwtDecoderBuilder withPublicKey(RSAPublicKey key) {
return new PublicKeyJwtDecoderBuilder(key);
}
/**
* Use the given {@code SecretKey} to validate the MAC on a JSON Web Signature (JWS).
* @param secretKey the {@code SecretKey} used to validate the MAC
* @return a {@link SecretKeyJwtDecoderBuilder} for further configurations
*/
public static SecretKeyJwtDecoderBuilder withSecretKey(SecretKey secretKey) {
return new SecretKeyJwtDecoderBuilder(secretKey);
}
/**
* A builder for creating {@link NimbusJwtDecoder} instances based on a
* <a target="_blank" href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a>
* uri.
*/
public static final class JwkSetUriJwtDecoderBuilder {
private Function<RestOperations, String> jwkSetUri;
private Function<JWKSource<SecurityContext>, Set<JWSAlgorithm>> defaultAlgorithms = (source) -> Set
.of(JWSAlgorithm.RS256);
private Set<SignatureAlgorithm> signatureAlgorithms = new HashSet<>();
private RestOperations restOperations = new RestTemplate();
private Cache cache;
private Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer;
private JwkSetUriJwtDecoderBuilder(String jwkSetUri) {
Assert.hasText(jwkSetUri, "jwkSetUri cannot be empty");
this.jwkSetUri = (rest) -> jwkSetUri;
this.jwtProcessorCustomizer = (processor) -> {
};
}
private JwkSetUriJwtDecoderBuilder(Function<RestOperations, String> jwkSetUri,
Function<JWKSource<SecurityContext>, Set<JWSAlgorithm>> defaultAlgorithms) {
Assert.notNull(jwkSetUri, "jwkSetUri function cannot be null");
Assert.notNull(defaultAlgorithms, "defaultAlgorithms function cannot be null");
this.jwkSetUri = jwkSetUri;
this.defaultAlgorithms = defaultAlgorithms;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Append the given signing
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a> to the set of algorithms to use.
* @param signatureAlgorithm the algorithm to use
* @return a {@link JwkSetUriJwtDecoderBuilder} for further configurations
*/
public JwkSetUriJwtDecoderBuilder jwsAlgorithm(SignatureAlgorithm signatureAlgorithm) {
Assert.notNull(signatureAlgorithm, "signatureAlgorithm cannot be null");
this.signatureAlgorithms.add(signatureAlgorithm);
return this;
}
/**
* Configure the list of
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithms</a> to use with the given {@link Consumer}.
* @param signatureAlgorithmsConsumer a {@link Consumer} for further configuring
* the algorithm list
* @return a {@link JwkSetUriJwtDecoderBuilder} for further configurations
*/
public JwkSetUriJwtDecoderBuilder jwsAlgorithms(Consumer<Set<SignatureAlgorithm>> signatureAlgorithmsConsumer) {
Assert.notNull(signatureAlgorithmsConsumer, "signatureAlgorithmsConsumer cannot be null");
signatureAlgorithmsConsumer.accept(this.signatureAlgorithms);
return this;
}
/**
* Use the given {@link RestOperations} to coordinate with the authorization
* servers indicated in the
* <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a> uri as well
* as the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>.
* @param restOperations
* @return
*/
public JwkSetUriJwtDecoderBuilder restOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
return this;
}
/**
* Use the given {@link Cache} to store
* <a href="https://tools.ietf.org/html/rfc7517#section-5">JWK Set</a>.
* @param cache the {@link Cache} to be used to store JWK Set
* @return a {@link JwkSetUriJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public JwkSetUriJwtDecoderBuilder cache(Cache cache) {
Assert.notNull(cache, "cache cannot be null");
this.cache = cache;
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link JwkSetUriJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public JwkSetUriJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
JWSKeySelector<SecurityContext> jwsKeySelector(JWKSource<SecurityContext> jwkSource) {
if (this.signatureAlgorithms.isEmpty()) {
return new JWSVerificationKeySelector<>(this.defaultAlgorithms.apply(jwkSource), jwkSource);
}
Set<JWSAlgorithm> jwsAlgorithms = new HashSet<>();
for (SignatureAlgorithm signatureAlgorithm : this.signatureAlgorithms) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(signatureAlgorithm.getName());
jwsAlgorithms.add(jwsAlgorithm);
}
return new JWSVerificationKeySelector<>(jwsAlgorithms, jwkSource);
}
JWKSource<SecurityContext> jwkSource(ResourceRetriever jwkSetRetriever, String jwkSetUri) {
if (this.cache == null) {
return new RemoteJWKSet<>(toURL(jwkSetUri), jwkSetRetriever);
}
JWKSetCache jwkSetCache = new SpringJWKSetCache(jwkSetUri, this.cache);
return new RemoteJWKSet<>(toURL(jwkSetUri), jwkSetRetriever, jwkSetCache);
}
JWTProcessor<SecurityContext> processor() {
ResourceRetriever jwkSetRetriever = new RestOperationsResourceRetriever(this.restOperations);
String jwkSetUri = this.jwkSetUri.apply(this.restOperations);
JWKSource<SecurityContext> jwkSource = jwkSource(jwkSetRetriever, jwkSetUri);
ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector(jwkSource));
// Spring Security validates the claim set independent from Nimbus
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return jwtProcessor;
}
/**
* Build the configured {@link NimbusJwtDecoder}.
* @return the configured {@link NimbusJwtDecoder}
*/
public NimbusJwtDecoder build() {
return new NimbusJwtDecoder(processor());
}
private static URL toURL(String url) {
try {
return new URL(url);
}
catch (MalformedURLException ex) {
throw new IllegalArgumentException("Invalid JWK Set URL \"" + url + "\" : " + ex.getMessage(), ex);
}
}
private static final class SpringJWKSetCache implements JWKSetCache {
private final String jwkSetUri;
private final Cache cache;
private JWKSet jwkSet;
SpringJWKSetCache(String jwkSetUri, Cache cache) {
this.jwkSetUri = jwkSetUri;
this.cache = cache;
this.updateJwkSetFromCache();
}
private void updateJwkSetFromCache() {
String cachedJwkSet = this.cache.get(this.jwkSetUri, String.class);
if (cachedJwkSet != null) {
try {
this.jwkSet = JWKSet.parse(cachedJwkSet);
}
catch (ParseException ignored) {
// Ignore invalid cache value
}
}
}
// Note: Only called from inside a synchronized block in RemoteJWKSet.
@Override
public void put(JWKSet jwkSet) {
this.jwkSet = jwkSet;
this.cache.put(this.jwkSetUri, jwkSet.toString(false));
}
@Override
public JWKSet get() {
return (!requiresRefresh()) ? this.jwkSet : null;
}
@Override
public boolean requiresRefresh() {
return this.cache.get(this.jwkSetUri) == null;
}
}
private static class RestOperationsResourceRetriever implements ResourceRetriever {
private static final MediaType APPLICATION_JWK_SET_JSON = new MediaType("application", "jwk-set+json");
private final RestOperations restOperations;
RestOperationsResourceRetriever(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
@Override
public Resource retrieveResource(URL url) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON));
ResponseEntity<String> response = getResponse(url, headers);
if (response.getStatusCode().value() != 200) {
throw new IOException(response.toString());
}
return new Resource(response.getBody(), "UTF-8");
}
private ResponseEntity<String> getResponse(URL url, HttpHeaders headers) throws IOException {
try {
RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, url.toURI());
return this.restOperations.exchange(request, String.class);
}
catch (Exception ex) {
throw new IOException(ex);
}
}
}
}
/**
* A builder for creating {@link NimbusJwtDecoder} instances based on a public key.
*/
public static final class PublicKeyJwtDecoderBuilder {
private JWSAlgorithm jwsAlgorithm;
private RSAPublicKey key;
private Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer;
private PublicKeyJwtDecoderBuilder(RSAPublicKey key) {
Assert.notNull(key, "key cannot be null");
this.jwsAlgorithm = JWSAlgorithm.RS256;
this.key = key;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Use the given signing
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a>.
*
* The value should be one of
* <a href="https://tools.ietf.org/html/rfc7518#section-3.3" target=
* "_blank">RS256, RS384, or RS512</a>.
* @param signatureAlgorithm the algorithm to use
* @return a {@link PublicKeyJwtDecoderBuilder} for further configurations
*/
public PublicKeyJwtDecoderBuilder signatureAlgorithm(SignatureAlgorithm signatureAlgorithm) {
Assert.notNull(signatureAlgorithm, "signatureAlgorithm cannot be null");
this.jwsAlgorithm = JWSAlgorithm.parse(signatureAlgorithm.getName());
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link PublicKeyJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public PublicKeyJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
JWTProcessor<SecurityContext> processor() {
Assert.state(JWSAlgorithm.Family.RSA.contains(this.jwsAlgorithm),
() -> "The provided key is of type RSA; however the signature algorithm is of some other type: "
+ this.jwsAlgorithm + ". Please indicate one of RS256, RS384, or RS512.");
JWSKeySelector<SecurityContext> jwsKeySelector = new SingleKeyJWSKeySelector<>(this.jwsAlgorithm, this.key);
DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
// Spring Security validates the claim set independent from Nimbus
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return jwtProcessor;
}
/**
* Build the configured {@link NimbusJwtDecoder}.
* @return the configured {@link NimbusJwtDecoder}
*/
public NimbusJwtDecoder build() {
return new NimbusJwtDecoder(processor());
}
}
/**
* A builder for creating {@link NimbusJwtDecoder} instances based on a
* {@code SecretKey}.
*/
public static final class SecretKeyJwtDecoderBuilder {
private final SecretKey secretKey;
private JWSAlgorithm jwsAlgorithm = JWSAlgorithm.HS256;
private Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer;
private SecretKeyJwtDecoderBuilder(SecretKey secretKey) {
Assert.notNull(secretKey, "secretKey cannot be null");
this.secretKey = secretKey;
this.jwtProcessorCustomizer = (processor) -> {
};
}
/**
* Use the given
* <a href="https://tools.ietf.org/html/rfc7515#section-4.1.1" target=
* "_blank">algorithm</a> when generating the MAC.
*
* The value should be one of
* <a href="https://tools.ietf.org/html/rfc7518#section-3.2" target=
* "_blank">HS256, HS384 or HS512</a>.
* @param macAlgorithm the MAC algorithm to use
* @return a {@link SecretKeyJwtDecoderBuilder} for further configurations
*/
public SecretKeyJwtDecoderBuilder macAlgorithm(MacAlgorithm macAlgorithm) {
Assert.notNull(macAlgorithm, "macAlgorithm cannot be null");
this.jwsAlgorithm = JWSAlgorithm.parse(macAlgorithm.getName());
return this;
}
/**
* Use the given {@link Consumer} to customize the {@link JWTProcessor
* ConfigurableJWTProcessor} before passing it to the build
* {@link NimbusJwtDecoder}.
* @param jwtProcessorCustomizer the callback used to alter the processor
* @return a {@link SecretKeyJwtDecoderBuilder} for further configurations
* @since 5.4
*/
public SecretKeyJwtDecoderBuilder jwtProcessorCustomizer(
Consumer<ConfigurableJWTProcessor<SecurityContext>> jwtProcessorCustomizer) {
Assert.notNull(jwtProcessorCustomizer, "jwtProcessorCustomizer cannot be null");
this.jwtProcessorCustomizer = jwtProcessorCustomizer;
return this;
}
/**
* Build the configured {@link NimbusJwtDecoder}.
* @return the configured {@link NimbusJwtDecoder}
*/
public NimbusJwtDecoder build() {
return new NimbusJwtDecoder(processor());
}
JWTProcessor<SecurityContext> processor() {
JWSKeySelector<SecurityContext> jwsKeySelector = new SingleKeyJWSKeySelector<>(this.jwsAlgorithm,
this.secretKey);
DefaultJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
jwtProcessor.setJWSKeySelector(jwsKeySelector);
// Spring Security validates the claim set independent from Nimbus
jwtProcessor.setJWTClaimsSetVerifier((claims, context) -> {
});
this.jwtProcessorCustomizer.accept(jwtProcessor);
return jwtProcessor;
}
}
}
| 23,845 | 35.970543 | 122 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJWKSource.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.jwt;
import java.util.List;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import reactor.core.publisher.Mono;
/**
* A reactive version of {@link com.nimbusds.jose.jwk.source.JWKSource}
*
* @author Rob Winch
* @since 5.1
*/
interface ReactiveJWKSource {
Mono<List<JWK>> get(JWKSelector jwkSelector);
}
| 1,009 | 27.055556 | 75 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JoseHeader.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.jwt;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.jose.JwaAlgorithm;
import org.springframework.util.Assert;
/**
* The JOSE header is a JSON object representing the header parameters of a JSON Web
* Token, whether the JWT is a JWS or JWE, that describe the cryptographic operations
* applied to the JWT and optionally, additional properties of the JWT.
*
* @author Anoop Garlapati
* @author Joe Grandja
* @since 5.6
* @see Jwt
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519#section-5">JWT JOSE
* Header</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JWS JOSE
* Header</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-4">JWE JOSE
* Header</a>
*/
class JoseHeader {
private final Map<String, Object> headers;
protected JoseHeader(Map<String, Object> headers) {
Assert.notEmpty(headers, "headers cannot be empty");
this.headers = Collections.unmodifiableMap(new HashMap<>(headers));
}
/**
* Returns the {@link JwaAlgorithm JWA algorithm} used to digitally sign the JWS or
* encrypt the JWE.
* @return the {@link JwaAlgorithm}
*/
@SuppressWarnings("unchecked")
public <T extends JwaAlgorithm> T getAlgorithm() {
return (T) getHeader(JoseHeaderNames.ALG);
}
/**
* Returns the JWK Set URL that refers to the resource of a set of JSON-encoded public
* keys, one of which corresponds to the key used to digitally sign the JWS or encrypt
* the JWE.
* @return the JWK Set URL
*/
public URL getJwkSetUrl() {
return getHeader(JoseHeaderNames.JKU);
}
/**
* Returns the JSON Web Key which is the public key that corresponds to the key used
* to digitally sign the JWS or encrypt the JWE.
* @return the JSON Web Key
*/
public Map<String, Object> getJwk() {
return getHeader(JoseHeaderNames.JWK);
}
/**
* Returns the key ID that is a hint indicating which key was used to secure the JWS
* or JWE.
* @return the key ID
*/
public String getKeyId() {
return getHeader(JoseHeaderNames.KID);
}
/**
* Returns the X.509 URL that refers to the resource for the X.509 public key
* certificate or certificate chain corresponding to the key used to digitally sign
* the JWS or encrypt the JWE.
* @return the X.509 URL
*/
public URL getX509Url() {
return getHeader(JoseHeaderNames.X5U);
}
/**
* Returns the X.509 certificate chain that contains the X.509 public key certificate
* or certificate chain corresponding to the key used to digitally sign the JWS or
* encrypt the JWE. The certificate or certificate chain is represented as a
* {@code List} of certificate value {@code String}s. Each {@code String} in the
* {@code List} is a Base64-encoded DER PKIX certificate value.
* @return the X.509 certificate chain
*/
public List<String> getX509CertificateChain() {
return getHeader(JoseHeaderNames.X5C);
}
/**
* Returns the X.509 certificate SHA-1 thumbprint that is a base64url-encoded SHA-1
* thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate
* corresponding to the key used to digitally sign the JWS or encrypt the JWE.
* @return the X.509 certificate SHA-1 thumbprint
*/
public String getX509SHA1Thumbprint() {
return getHeader(JoseHeaderNames.X5T);
}
/**
* Returns the X.509 certificate SHA-256 thumbprint that is a base64url-encoded
* SHA-256 thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate
* corresponding to the key used to digitally sign the JWS or encrypt the JWE.
* @return the X.509 certificate SHA-256 thumbprint
*/
public String getX509SHA256Thumbprint() {
return getHeader(JoseHeaderNames.X5T_S256);
}
/**
* Returns the type header that declares the media type of the JWS/JWE.
* @return the type header
*/
public String getType() {
return getHeader(JoseHeaderNames.TYP);
}
/**
* Returns the content type header that declares the media type of the secured content
* (the payload).
* @return the content type header
*/
public String getContentType() {
return getHeader(JoseHeaderNames.CTY);
}
/**
* Returns the critical headers that indicates which extensions to the JWS/JWE/JWA
* specifications are being used that MUST be understood and processed.
* @return the critical headers
*/
public Set<String> getCritical() {
return getHeader(JoseHeaderNames.CRIT);
}
/**
* Returns the headers.
* @return the headers
*/
public Map<String, Object> getHeaders() {
return this.headers;
}
/**
* Returns the header value.
* @param name the header name
* @param <T> the type of the header value
* @return the header value
*/
@SuppressWarnings("unchecked")
public <T> T getHeader(String name) {
Assert.hasText(name, "name cannot be empty");
return (T) getHeaders().get(name);
}
/**
* A builder for subclasses of {@link JoseHeader}.
*/
abstract static class AbstractBuilder<T extends JoseHeader, B extends AbstractBuilder<T, B>> {
private final Map<String, Object> headers = new HashMap<>();
protected AbstractBuilder() {
}
protected Map<String, Object> getHeaders() {
return this.headers;
}
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this; // avoid unchecked casts in subclasses by using "getThis()"
// instead of "(B) this"
}
/**
* Sets the {@link JwaAlgorithm JWA algorithm} used to digitally sign the JWS or
* encrypt the JWE.
* @param jwaAlgorithm the {@link JwaAlgorithm}
* @return the {@link AbstractBuilder}
*/
public B algorithm(JwaAlgorithm jwaAlgorithm) {
return header(JoseHeaderNames.ALG, jwaAlgorithm);
}
/**
* Sets the JWK Set URL that refers to the resource of a set of JSON-encoded
* public keys, one of which corresponds to the key used to digitally sign the JWS
* or encrypt the JWE.
* @param jwkSetUrl the JWK Set URL
* @return the {@link AbstractBuilder}
*/
public B jwkSetUrl(String jwkSetUrl) {
return header(JoseHeaderNames.JKU, convertAsURL(JoseHeaderNames.JKU, jwkSetUrl));
}
/**
* Sets the JSON Web Key which is the public key that corresponds to the key used
* to digitally sign the JWS or encrypt the JWE.
* @param jwk the JSON Web Key
* @return the {@link AbstractBuilder}
*/
public B jwk(Map<String, Object> jwk) {
return header(JoseHeaderNames.JWK, jwk);
}
/**
* Sets the key ID that is a hint indicating which key was used to secure the JWS
* or JWE.
* @param keyId the key ID
* @return the {@link AbstractBuilder}
*/
public B keyId(String keyId) {
return header(JoseHeaderNames.KID, keyId);
}
/**
* Sets the X.509 URL that refers to the resource for the X.509 public key
* certificate or certificate chain corresponding to the key used to digitally
* sign the JWS or encrypt the JWE.
* @param x509Url the X.509 URL
* @return the {@link AbstractBuilder}
*/
public B x509Url(String x509Url) {
return header(JoseHeaderNames.X5U, convertAsURL(JoseHeaderNames.X5U, x509Url));
}
/**
* Sets the X.509 certificate chain that contains the X.509 public key certificate
* or certificate chain corresponding to the key used to digitally sign the JWS or
* encrypt the JWE. The certificate or certificate chain is represented as a
* {@code List} of certificate value {@code String}s. Each {@code String} in the
* {@code List} is a Base64-encoded DER PKIX certificate value.
* @param x509CertificateChain the X.509 certificate chain
* @return the {@link AbstractBuilder}
*/
public B x509CertificateChain(List<String> x509CertificateChain) {
return header(JoseHeaderNames.X5C, x509CertificateChain);
}
/**
* Sets the X.509 certificate SHA-1 thumbprint that is a base64url-encoded SHA-1
* thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate
* corresponding to the key used to digitally sign the JWS or encrypt the JWE.
* @param x509SHA1Thumbprint the X.509 certificate SHA-1 thumbprint
* @return the {@link AbstractBuilder}
*/
public B x509SHA1Thumbprint(String x509SHA1Thumbprint) {
return header(JoseHeaderNames.X5T, x509SHA1Thumbprint);
}
/**
* Sets the X.509 certificate SHA-256 thumbprint that is a base64url-encoded
* SHA-256 thumbprint (a.k.a. digest) of the DER encoding of the X.509 certificate
* corresponding to the key used to digitally sign the JWS or encrypt the JWE.
* @param x509SHA256Thumbprint the X.509 certificate SHA-256 thumbprint
* @return the {@link AbstractBuilder}
*/
public B x509SHA256Thumbprint(String x509SHA256Thumbprint) {
return header(JoseHeaderNames.X5T_S256, x509SHA256Thumbprint);
}
/**
* Sets the type header that declares the media type of the JWS/JWE.
* @param type the type header
* @return the {@link AbstractBuilder}
*/
public B type(String type) {
return header(JoseHeaderNames.TYP, type);
}
/**
* Sets the content type header that declares the media type of the secured
* content (the payload).
* @param contentType the content type header
* @return the {@link AbstractBuilder}
*/
public B contentType(String contentType) {
return header(JoseHeaderNames.CTY, contentType);
}
/**
* Sets the critical header that indicates which extensions to the JWS/JWE/JWA
* specifications are being used that MUST be understood and processed.
* @param name the critical header name
* @param value the critical header value
* @return the {@link AbstractBuilder}
*/
@SuppressWarnings("unchecked")
public B criticalHeader(String name, Object value) {
header(name, value);
getHeaders().computeIfAbsent(JoseHeaderNames.CRIT, (k) -> new HashSet<String>());
((Set<String>) getHeaders().get(JoseHeaderNames.CRIT)).add(name);
return getThis();
}
/**
* Sets the header.
* @param name the header name
* @param value the header value
* @return the {@link AbstractBuilder}
*/
public B header(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.headers.put(name, value);
return getThis();
}
/**
* A {@code Consumer} to be provided access to the headers allowing the ability to
* add, replace, or remove.
* @param headersConsumer a {@code Consumer} of the headers
* @return the {@link AbstractBuilder}
*/
public B headers(Consumer<Map<String, Object>> headersConsumer) {
headersConsumer.accept(this.headers);
return getThis();
}
/**
* Builds a new {@link JoseHeader}.
* @return a {@link JoseHeader}
*/
public abstract T build();
private static URL convertAsURL(String header, String value) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(value, URL.class);
Assert.isTrue(convertedValue != null,
() -> "Unable to convert header '" + header + "' of type '" + value.getClass() + "' to URL.");
return convertedValue;
}
}
}
| 11,932 | 31.782967 | 99 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoderInitializationException.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.jwt;
/**
* An exception thrown when a {@link JwtDecoder} or {@link ReactiveJwtDecoder}'s lazy
* initialization fails.
*
* @author Josh Cummings
* @since 5.6
*/
public class JwtDecoderInitializationException extends RuntimeException {
public JwtDecoderInitializationException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,017 | 29.848485 | 85 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveRemoteJWKSource.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.jwt;
import java.text.ParseException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import com.nimbusds.jose.RemoteKeySourceException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.JWKSet;
import reactor.core.publisher.Mono;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author Rob Winch
* @since 5.1
*/
class ReactiveRemoteJWKSource implements ReactiveJWKSource {
/**
* The cached JWK set.
*/
private final AtomicReference<Mono<JWKSet>> cachedJWKSet = new AtomicReference<>(Mono.empty());
private WebClient webClient = WebClient.create();
private final Mono<String> jwkSetURL;
ReactiveRemoteJWKSource(String jwkSetURL) {
Assert.hasText(jwkSetURL, "jwkSetURL cannot be empty");
this.jwkSetURL = Mono.just(jwkSetURL);
}
ReactiveRemoteJWKSource(Mono<String> jwkSetURL) {
Assert.notNull(jwkSetURL, "jwkSetURL cannot be null");
this.jwkSetURL = jwkSetURL.cache();
}
@Override
public Mono<List<JWK>> get(JWKSelector jwkSelector) {
// @formatter:off
return this.cachedJWKSet.get()
.switchIfEmpty(Mono.defer(this::getJWKSet))
.flatMap((jwkSet) -> get(jwkSelector, jwkSet))
.switchIfEmpty(Mono.defer(() -> getJWKSet()
.map(jwkSelector::select))
);
// @formatter:on
}
private Mono<List<JWK>> get(JWKSelector jwkSelector, JWKSet jwkSet) {
return Mono.defer(() -> {
// Run the selector on the JWK set
List<JWK> matches = jwkSelector.select(jwkSet);
if (!matches.isEmpty()) {
// Success
return Mono.just(matches);
}
// Refresh the JWK set if the sought key ID is not in the cached JWK set
// Looking for JWK with specific ID?
String soughtKeyID = getFirstSpecifiedKeyID(jwkSelector.getMatcher());
if (soughtKeyID == null) {
// No key ID specified, return no matches
return Mono.just(Collections.emptyList());
}
if (jwkSet.getKeyByKeyId(soughtKeyID) != null) {
// The key ID exists in the cached JWK set, matching
// failed for some other reason, return no matches
return Mono.just(Collections.emptyList());
}
return Mono.empty();
});
}
/**
* Updates the cached JWK set from the configured URL.
* @return The updated JWK set.
* @throws RemoteKeySourceException If JWK retrieval failed.
*/
private Mono<JWKSet> getJWKSet() {
// @formatter:off
return this.jwkSetURL.flatMap((jwkSetURL) -> this.webClient.get()
.uri(jwkSetURL)
.retrieve()
.bodyToMono(String.class))
.map(this::parse)
.doOnNext((jwkSet) -> this.cachedJWKSet
.set(Mono.just(jwkSet))
)
.cache();
// @formatter:on
}
private JWKSet parse(String body) {
try {
return JWKSet.parse(body);
}
catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
/**
* Returns the first specified key ID (kid) for a JWK matcher.
* @param jwkMatcher The JWK matcher. Must not be {@code null}.
* @return The first key ID, {@code null} if none.
*/
protected static String getFirstSpecifiedKeyID(final JWKMatcher jwkMatcher) {
Set<String> keyIDs = jwkMatcher.getKeyIDs();
if (keyIDs == null || keyIDs.isEmpty()) {
return null;
}
for (String id : keyIDs) {
if (id != null) {
return id;
}
}
return null; // No kid in matcher
}
void setWebClient(WebClient webClient) {
this.webClient = webClient;
}
}
| 4,192 | 27.52381 | 96 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/SupplierReactiveJwtDecoder.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.jwt;
import java.time.Duration;
import java.util.function.Supplier;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
/**
* A {@link ReactiveJwtDecoder} that lazily initializes another {@link ReactiveJwtDecoder}
*
* @author Josh Cummings
* @since 5.6
*/
public final class SupplierReactiveJwtDecoder implements ReactiveJwtDecoder {
private static final Duration FOREVER = Duration.ofMillis(Long.MAX_VALUE);
private Mono<ReactiveJwtDecoder> jwtDecoderMono;
public SupplierReactiveJwtDecoder(Supplier<ReactiveJwtDecoder> supplier) {
// @formatter:off
this.jwtDecoderMono = Mono.fromSupplier(supplier)
.subscribeOn(Schedulers.boundedElastic())
.publishOn(Schedulers.parallel())
.onErrorMap(this::wrapException)
.cache((delegate) -> FOREVER, (ex) -> Duration.ZERO, () -> Duration.ZERO);
// @formatter:on
}
private JwtDecoderInitializationException wrapException(Throwable t) {
return new JwtDecoderInitializationException("Failed to lazily resolve the supplied JwtDecoder instance", t);
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Jwt> decode(String token) throws JwtException {
return this.jwtDecoderMono.flatMap((decoder) -> decoder.decode(token));
}
}
| 1,903 | 30.733333 | 111 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoders.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.jwt;
import java.util.Map;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.util.Assert;
/**
* Allows creating a {@link JwtDecoder} from an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID
* Provider Configuration</a> or
* <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server Metadata
* Request</a> based on provided issuer and method invoked.
*
* @author Josh Cummings
* @author Rafiullah Hamedy
* @since 5.1
*/
public final class JwtDecoders {
private JwtDecoders() {
}
/**
* Creates a {@link JwtDecoder} using the provided <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by making an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
* Provider Configuration Request</a> and using the values in the <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> to initialize the {@link JwtDecoder}.
* @param oidcIssuerLocation the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link JwtDecoder} that was initialized by the OpenID Provider
* Configuration.
*/
@SuppressWarnings("unchecked")
public static <T extends JwtDecoder> T fromOidcIssuerLocation(String oidcIssuerLocation) {
Assert.hasText(oidcIssuerLocation, "oidcIssuerLocation cannot be empty");
Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
.getConfigurationForOidcIssuerLocation(oidcIssuerLocation);
return (T) withProviderConfiguration(configuration, oidcIssuerLocation);
}
/**
* Creates a {@link JwtDecoder} using the provided <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by querying three different discovery endpoints serially, using the values in the
* first successful response to initialize. If an endpoint returns anything other than
* a 200 or a 4xx, the method will exit without attempting subsequent endpoints.
*
* The three endpoints are computed as follows, given that the {@code issuer} is
* composed of a {@code host} and a {@code path}:
*
* <ol>
* <li>{@code host/.well-known/openid-configuration/path}, as defined in
* <a href="https://tools.ietf.org/html/rfc8414#section-5">RFC 8414's Compatibility
* Notes</a>.</li>
* <li>{@code issuer/.well-known/openid-configuration}, as defined in <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">
* OpenID Provider Configuration</a>.</li>
* <li>{@code host/.well-known/oauth-authorization-server/path}, as defined in
* <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server
* Metadata Request</a>.</li>
* </ol>
*
* Note that the second endpoint is the equivalent of calling
* {@link JwtDecoders#fromOidcIssuerLocation(String)}
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link JwtDecoder} that was initialized by one of the described endpoints
*/
@SuppressWarnings("unchecked")
public static <T extends JwtDecoder> T fromIssuerLocation(String issuer) {
Assert.hasText(issuer, "issuer cannot be empty");
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();
OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
jwtDecoder.setJwtValidator(jwtValidator);
return (T) jwtDecoder;
}
/**
* Validate provided issuer and build {@link JwtDecoder} from <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> and
* <a href="https://tools.ietf.org/html/rfc8414#section-3.2">Authorization Server
* Metadata Response</a>.
* @param configuration the configuration values
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return {@link JwtDecoder}
*/
private static JwtDecoder withProviderConfiguration(Map<String, Object> configuration, String issuer) {
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
String jwkSetUri = configuration.get("jwks_uri").toString();
NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
.jwtProcessorCustomizer(JwtDecoderProviderConfigurationUtils::addJWSAlgorithms).build();
jwtDecoder.setJwtValidator(jwtValidator);
return jwtDecoder;
}
}
| 5,478 | 44.658333 | 104 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.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.jwt;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObjectType;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jose.produce.JWSSignerFactory;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jose.util.Base64URL;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* An implementation of a {@link JwtEncoder} that encodes a JSON Web Token (JWT) using the
* JSON Web Signature (JWS) Compact Serialization format. The private/secret key used for
* signing the JWS is supplied by the {@code com.nimbusds.jose.jwk.source.JWKSource}
* provided via the constructor.
*
* <p>
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK.
*
* @author Joe Grandja
* @since 5.6
* @see JwtEncoder
* @see com.nimbusds.jose.jwk.source.JWKSource
* @see com.nimbusds.jose.jwk.JWK
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS
* Compact Serialization</a>
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus
* JOSE + JWT SDK</a>
*/
public final class NimbusJwtEncoder implements JwtEncoder {
private static final String ENCODING_ERROR_MESSAGE_TEMPLATE = "An error occurred while attempting to encode the Jwt: %s";
private static final JwsHeader DEFAULT_JWS_HEADER = JwsHeader.with(SignatureAlgorithm.RS256).build();
private static final JWSSignerFactory JWS_SIGNER_FACTORY = new DefaultJWSSignerFactory();
private final Map<JWK, JWSSigner> jwsSigners = new ConcurrentHashMap<>();
private final JWKSource<SecurityContext> jwkSource;
/**
* Constructs a {@code NimbusJwtEncoder} using the provided parameters.
* @param jwkSource the {@code com.nimbusds.jose.jwk.source.JWKSource}
*/
public NimbusJwtEncoder(JWKSource<SecurityContext> jwkSource) {
Assert.notNull(jwkSource, "jwkSource cannot be null");
this.jwkSource = jwkSource;
}
@Override
public Jwt encode(JwtEncoderParameters parameters) throws JwtEncodingException {
Assert.notNull(parameters, "parameters cannot be null");
JwsHeader headers = parameters.getJwsHeader();
if (headers == null) {
headers = DEFAULT_JWS_HEADER;
}
JwtClaimsSet claims = parameters.getClaims();
JWK jwk = selectJwk(headers);
headers = addKeyIdentifierHeadersIfNecessary(headers, jwk);
String jws = serialize(headers, claims, jwk);
return new Jwt(jws, claims.getIssuedAt(), claims.getExpiresAt(), headers.getHeaders(), claims.getClaims());
}
private JWK selectJwk(JwsHeader headers) {
List<JWK> jwks;
try {
JWKSelector jwkSelector = new JWKSelector(createJwkMatcher(headers));
jwks = this.jwkSource.get(jwkSelector, null);
}
catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to select a JWK signing key -> " + ex.getMessage()), ex);
}
if (jwks.size() > 1) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Found multiple JWK signing keys for algorithm '" + headers.getAlgorithm().getName() + "'"));
}
if (jwks.isEmpty()) {
throw new JwtEncodingException(
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
}
return jwks.get(0);
}
private String serialize(JwsHeader headers, JwtClaimsSet claims, JWK jwk) {
JWSHeader jwsHeader = convert(headers);
JWTClaimsSet jwtClaimsSet = convert(claims);
JWSSigner jwsSigner = this.jwsSigners.computeIfAbsent(jwk, NimbusJwtEncoder::createSigner);
SignedJWT signedJwt = new SignedJWT(jwsHeader, jwtClaimsSet);
try {
signedJwt.sign(jwsSigner);
}
catch (JOSEException ex) {
throw new JwtEncodingException(
String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to sign the JWT -> " + ex.getMessage()), ex);
}
return signedJwt.serialize();
}
private static JWKMatcher createJwkMatcher(JwsHeader headers) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(headers.getAlgorithm().getName());
if (JWSAlgorithm.Family.RSA.contains(jwsAlgorithm) || JWSAlgorithm.Family.EC.contains(jwsAlgorithm)) {
// @formatter:off
return new JWKMatcher.Builder()
.keyType(KeyType.forAlgorithm(jwsAlgorithm))
.keyID(headers.getKeyId())
.keyUses(KeyUse.SIGNATURE, null)
.algorithms(jwsAlgorithm, null)
.x509CertSHA256Thumbprint(Base64URL.from(headers.getX509SHA256Thumbprint()))
.build();
// @formatter:on
}
else if (JWSAlgorithm.Family.HMAC_SHA.contains(jwsAlgorithm)) {
// @formatter:off
return new JWKMatcher.Builder()
.keyType(KeyType.forAlgorithm(jwsAlgorithm))
.keyID(headers.getKeyId())
.privateOnly(true)
.algorithms(jwsAlgorithm, null)
.build();
// @formatter:on
}
return null;
}
private static JwsHeader addKeyIdentifierHeadersIfNecessary(JwsHeader headers, JWK jwk) {
// Check if headers have already been added
if (StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(headers.getX509SHA256Thumbprint())) {
return headers;
}
// Check if headers can be added from JWK
if (!StringUtils.hasText(jwk.getKeyID()) && jwk.getX509CertSHA256Thumbprint() == null) {
return headers;
}
JwsHeader.Builder headersBuilder = JwsHeader.from(headers);
if (!StringUtils.hasText(headers.getKeyId()) && StringUtils.hasText(jwk.getKeyID())) {
headersBuilder.keyId(jwk.getKeyID());
}
if (!StringUtils.hasText(headers.getX509SHA256Thumbprint()) && jwk.getX509CertSHA256Thumbprint() != null) {
headersBuilder.x509SHA256Thumbprint(jwk.getX509CertSHA256Thumbprint().toString());
}
return headersBuilder.build();
}
private static JWSSigner createSigner(JWK jwk) {
try {
return JWS_SIGNER_FACTORY.createJWSSigner(jwk);
}
catch (JOSEException ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Failed to create a JWS Signer -> " + ex.getMessage()), ex);
}
}
private static JWSHeader convert(JwsHeader headers) {
JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(headers.getAlgorithm().getName()));
if (headers.getJwkSetUrl() != null) {
builder.jwkURL(convertAsURI(JoseHeaderNames.JKU, headers.getJwkSetUrl()));
}
Map<String, Object> jwk = headers.getJwk();
if (!CollectionUtils.isEmpty(jwk)) {
try {
builder.jwk(JWK.parse(jwk));
}
catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Unable to convert '" + JoseHeaderNames.JWK + "' JOSE header"), ex);
}
}
String keyId = headers.getKeyId();
if (StringUtils.hasText(keyId)) {
builder.keyID(keyId);
}
if (headers.getX509Url() != null) {
builder.x509CertURL(convertAsURI(JoseHeaderNames.X5U, headers.getX509Url()));
}
List<String> x509CertificateChain = headers.getX509CertificateChain();
if (!CollectionUtils.isEmpty(x509CertificateChain)) {
List<Base64> x5cList = new ArrayList<>();
x509CertificateChain.forEach((x5c) -> x5cList.add(new Base64(x5c)));
if (!x5cList.isEmpty()) {
builder.x509CertChain(x5cList);
}
}
String x509SHA1Thumbprint = headers.getX509SHA1Thumbprint();
if (StringUtils.hasText(x509SHA1Thumbprint)) {
builder.x509CertThumbprint(new Base64URL(x509SHA1Thumbprint));
}
String x509SHA256Thumbprint = headers.getX509SHA256Thumbprint();
if (StringUtils.hasText(x509SHA256Thumbprint)) {
builder.x509CertSHA256Thumbprint(new Base64URL(x509SHA256Thumbprint));
}
String type = headers.getType();
if (StringUtils.hasText(type)) {
builder.type(new JOSEObjectType(type));
}
String contentType = headers.getContentType();
if (StringUtils.hasText(contentType)) {
builder.contentType(contentType);
}
Set<String> critical = headers.getCritical();
if (!CollectionUtils.isEmpty(critical)) {
builder.criticalParams(critical);
}
Map<String, Object> customHeaders = new HashMap<>();
headers.getHeaders().forEach((name, value) -> {
if (!JWSHeader.getRegisteredParameterNames().contains(name)) {
customHeaders.put(name, value);
}
});
if (!customHeaders.isEmpty()) {
builder.customParams(customHeaders);
}
return builder.build();
}
private static JWTClaimsSet convert(JwtClaimsSet claims) {
JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
// NOTE: The value of the 'iss' claim is a String or URL (StringOrURI).
Object issuer = claims.getClaim(JwtClaimNames.ISS);
if (issuer != null) {
builder.issuer(issuer.toString());
}
String subject = claims.getSubject();
if (StringUtils.hasText(subject)) {
builder.subject(subject);
}
List<String> audience = claims.getAudience();
if (!CollectionUtils.isEmpty(audience)) {
builder.audience(audience);
}
Instant expiresAt = claims.getExpiresAt();
if (expiresAt != null) {
builder.expirationTime(Date.from(expiresAt));
}
Instant notBefore = claims.getNotBefore();
if (notBefore != null) {
builder.notBeforeTime(Date.from(notBefore));
}
Instant issuedAt = claims.getIssuedAt();
if (issuedAt != null) {
builder.issueTime(Date.from(issuedAt));
}
String jwtId = claims.getId();
if (StringUtils.hasText(jwtId)) {
builder.jwtID(jwtId);
}
Map<String, Object> customClaims = new HashMap<>();
claims.getClaims().forEach((name, value) -> {
if (!JWTClaimsSet.getRegisteredNames().contains(name)) {
customClaims.put(name, value);
}
});
if (!customClaims.isEmpty()) {
customClaims.forEach(builder::claim);
}
return builder.build();
}
private static URI convertAsURI(String header, URL url) {
try {
return url.toURI();
}
catch (Exception ex) {
throw new JwtEncodingException(String.format(ENCODING_ERROR_MESSAGE_TEMPLATE,
"Unable to convert '" + header + "' JOSE header to a URI"), ex);
}
}
}
| 11,523 | 31.645892 | 122 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwsHeader.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.jwt;
import java.util.Map;
import org.springframework.security.oauth2.jose.jws.JwsAlgorithm;
import org.springframework.util.Assert;
/**
* The JSON Web Signature (JWS) header is a JSON object representing the header parameters
* of a JSON Web Token, that describe the cryptographic operations used to digitally sign
* or create a MAC of the contents of the JWS Protected Header and JWS Payload.
*
* @author Joe Grandja
* @since 5.6
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-4">JWS JOSE
* Header</a>
*/
public final class JwsHeader extends JoseHeader {
private JwsHeader(Map<String, Object> headers) {
super(headers);
}
@SuppressWarnings("unchecked")
@Override
public JwsAlgorithm getAlgorithm() {
return super.getAlgorithm();
}
/**
* Returns a new {@link Builder}, initialized with the provided {@link JwsAlgorithm}.
* @param jwsAlgorithm the {@link JwsAlgorithm}
* @return the {@link Builder}
*/
public static Builder with(JwsAlgorithm jwsAlgorithm) {
return new Builder(jwsAlgorithm);
}
/**
* Returns a new {@link Builder}, initialized with the provided {@code headers}.
* @param headers the headers
* @return the {@link Builder}
*/
public static Builder from(JwsHeader headers) {
return new Builder(headers);
}
/**
* A builder for {@link JwsHeader}.
*/
public static final class Builder extends AbstractBuilder<JwsHeader, Builder> {
private Builder(JwsAlgorithm jwsAlgorithm) {
Assert.notNull(jwsAlgorithm, "jwsAlgorithm cannot be null");
algorithm(jwsAlgorithm);
}
private Builder(JwsHeader headers) {
Assert.notNull(headers, "headers cannot be null");
getHeaders().putAll(headers.getHeaders());
}
/**
* Builds a new {@link JwsHeader}.
* @return a {@link JwsHeader}
*/
@Override
public JwsHeader build() {
return new JwsHeader(getHeaders());
}
}
}
| 2,558 | 27.120879 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoderProviderConfigurationUtils.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.jwt;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.util.Assert;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Allows resolving configuration from an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID
* Provider Configuration</a> or
* <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server Metadata
* Request</a> based on provided issuer and method invoked.
*
* @author Thomas Vitale
* @author Rafiullah Hamedy
* @since 5.2
*/
final class JwtDecoderProviderConfigurationUtils {
private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";
private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
private static final RestTemplate rest = new RestTemplate();
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private JwtDecoderProviderConfigurationUtils() {
}
static Map<String, Object> getConfigurationForOidcIssuerLocation(String oidcIssuerLocation) {
return getConfiguration(oidcIssuerLocation, rest, oidc(URI.create(oidcIssuerLocation)));
}
static Map<String, Object> getConfigurationForIssuerLocation(String issuer, RestOperations rest) {
URI uri = URI.create(issuer);
return getConfiguration(issuer, rest, oidc(uri), oidcRfc8414(uri), oauth(uri));
}
static Map<String, Object> getConfigurationForIssuerLocation(String issuer) {
return getConfigurationForIssuerLocation(issuer, rest);
}
static void validateIssuer(Map<String, Object> configuration, String issuer) {
String metadataIssuer = getMetadataIssuer(configuration);
Assert.state(issuer.equals(metadataIssuer), () -> "The Issuer \"" + metadataIssuer
+ "\" provided in the configuration did not " + "match the requested issuer \"" + issuer + "\"");
}
static <C extends SecurityContext> void addJWSAlgorithms(ConfigurableJWTProcessor<C> jwtProcessor) {
JWSKeySelector<C> selector = jwtProcessor.getJWSKeySelector();
if (selector instanceof JWSVerificationKeySelector) {
JWKSource<C> jwkSource = ((JWSVerificationKeySelector<C>) selector).getJWKSource();
Set<JWSAlgorithm> algorithms = getJWSAlgorithms(jwkSource);
selector = new JWSVerificationKeySelector<>(algorithms, jwkSource);
jwtProcessor.setJWSKeySelector(selector);
}
}
static <C extends SecurityContext> Set<JWSAlgorithm> getJWSAlgorithms(JWKSource<C> jwkSource) {
JWKMatcher jwkMatcher = new JWKMatcher.Builder().publicOnly(true).keyUses(KeyUse.SIGNATURE, null)
.keyTypes(KeyType.RSA, KeyType.EC).build();
Set<JWSAlgorithm> jwsAlgorithms = new HashSet<>();
try {
List<? extends JWK> jwks = jwkSource.get(new JWKSelector(jwkMatcher), null);
for (JWK jwk : jwks) {
if (jwk.getAlgorithm() != null) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(jwk.getAlgorithm().getName());
jwsAlgorithms.add(jwsAlgorithm);
}
else {
if (jwk.getKeyType() == KeyType.RSA) {
jwsAlgorithms.addAll(JWSAlgorithm.Family.RSA);
}
else if (jwk.getKeyType() == KeyType.EC) {
jwsAlgorithms.addAll(JWSAlgorithm.Family.EC);
}
}
}
}
catch (KeySourceException ex) {
throw new IllegalStateException(ex);
}
Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set");
return jwsAlgorithms;
}
static Set<SignatureAlgorithm> getSignatureAlgorithms(JWKSource<SecurityContext> jwkSource) {
Set<JWSAlgorithm> jwsAlgorithms = getJWSAlgorithms(jwkSource);
Set<SignatureAlgorithm> signatureAlgorithms = new HashSet<>();
for (JWSAlgorithm jwsAlgorithm : jwsAlgorithms) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(jwsAlgorithm.getName());
if (signatureAlgorithm != null) {
signatureAlgorithms.add(signatureAlgorithm);
}
}
return signatureAlgorithms;
}
private static String getMetadataIssuer(Map<String, Object> configuration) {
if (configuration.containsKey("issuer")) {
return configuration.get("issuer").toString();
}
return "(unavailable)";
}
private static Map<String, Object> getConfiguration(String issuer, RestOperations rest, URI... uris) {
String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\"";
for (URI uri : uris) {
try {
RequestEntity<Void> request = RequestEntity.get(uri).build();
ResponseEntity<Map<String, Object>> response = rest.exchange(request, STRING_OBJECT_MAP);
Map<String, Object> configuration = response.getBody();
Assert.isTrue(configuration.get("jwks_uri") != null, "The public JWK set URI must not be null");
return configuration;
}
catch (IllegalArgumentException ex) {
throw ex;
}
catch (RuntimeException ex) {
if (!(ex instanceof HttpClientErrorException
&& ((HttpClientErrorException) ex).getStatusCode().is4xxClientError())) {
throw new IllegalArgumentException(errorMessage, ex);
}
// else try another endpoint
}
}
throw new IllegalArgumentException(errorMessage);
}
private static URI oidc(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(issuer.getPath() + OIDC_METADATA_PATH)
.build(Collections.emptyMap());
// @formatter:on
}
private static URI oidcRfc8414(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(OIDC_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
}
private static URI oauth(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(OAUTH_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
}
}
| 7,493 | 36.658291 | 145 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtIssuerValidator.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.jwt;
import java.util.function.Predicate;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.util.Assert;
/**
* Validates the "iss" claim in a {@link Jwt}, that is matches a configured value
*
* @author Josh Cummings
* @since 5.1
*/
public final class JwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
private final JwtClaimValidator<Object> validator;
/**
* Constructs a {@link JwtIssuerValidator} using the provided parameters
* @param issuer - The issuer that each {@link Jwt} should have.
*/
public JwtIssuerValidator(String issuer) {
Assert.notNull(issuer, "issuer cannot be null");
Predicate<Object> testClaimValue = (claimValue) -> (claimValue != null) && issuer.equals(claimValue.toString());
this.validator = new JwtClaimValidator<>(JwtClaimNames.ISS, testClaimValue);
}
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
return this.validator.validate(token);
}
}
| 1,769 | 32.396226 | 114 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoder.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.jwt;
import reactor.core.publisher.Mono;
/**
* Implementations of this interface are responsible for "decoding" a JSON Web
* Token (JWT) from it's compact claims representation format to a {@link Jwt}.
*
* <p>
* JWTs may be represented using the JWS Compact Serialization format for a JSON Web
* Signature (JWS) structure or JWE Compact Serialization format for a JSON Web Encryption
* (JWE) structure. Therefore, implementors are responsible for verifying a JWS and/or
* decrypting a JWE.
*
* @author Rob Winch
* @since 5.1
* @see Jwt
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516">JSON Web Encryption
* (JWE)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS
* Compact Serialization</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-3.1">JWE
* Compact Serialization</a>
*/
@FunctionalInterface
public interface ReactiveJwtDecoder {
/**
* Decodes the JWT from it's compact claims representation format and returns a
* {@link Jwt}.
* @param token the JWT value
* @return a {@link Jwt}
* @throws JwtException if an error occurs while attempting to decode the JWT
*/
Mono<Jwt> decode(String token) throws JwtException;
}
| 2,124 | 35.637931 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimNames.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.jwt;
/**
* The Registered Claim Names defined by the JSON Web Token (JWT) specification that may
* be contained in the JSON object JWT Claims Set.
*
* @author Joe Grandja
* @since 5.0
* @see JwtClaimAccessor
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519#section-4">JWT
* Claims</a>
*/
public final class JwtClaimNames {
/**
* {@code iss} - the Issuer claim identifies the principal that issued the JWT
*/
public static final String ISS = "iss";
/**
* {@code sub} - the Subject claim identifies the principal that is the subject of the
* JWT
*/
public static final String SUB = "sub";
/**
* {@code aud} - the Audience claim identifies the recipient(s) that the JWT is
* intended for
*/
public static final String AUD = "aud";
/**
* {@code exp} - the Expiration time claim identifies the expiration time on or after
* which the JWT MUST NOT be accepted for processing
*/
public static final String EXP = "exp";
/**
* {@code nbf} - the Not Before claim identifies the time before which the JWT MUST
* NOT be accepted for processing
*/
public static final String NBF = "nbf";
/**
* {@code iat} - The Issued at claim identifies the time at which the JWT was issued
*/
public static final String IAT = "iat";
/**
* {@code jti} - The JWT ID claim provides a unique identifier for the JWT
*/
public static final String JTI = "jti";
private JwtClaimNames() {
}
}
| 2,114 | 27.581081 | 88 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtValidators.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.jwt;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
/**
* Provides factory methods for creating {@code OAuth2TokenValidator<Jwt>}
*
* @author Josh Cummings
* @author Rob Winch
* @since 5.1
*/
public final class JwtValidators {
private JwtValidators() {
}
/**
* <p>
* Create a {@link Jwt} Validator that contains all standard validators when an issuer
* is known.
* </p>
* <p>
* User's wanting to leverage the defaults plus additional validation can add the
* result of this method to {@code DelegatingOAuth2TokenValidator} along with the
* additional validators.
* </p>
* @param issuer the issuer
* @return - a delegating validator containing all standard validators as well as any
* supplied
*/
public static OAuth2TokenValidator<Jwt> createDefaultWithIssuer(String issuer) {
List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
validators.add(new JwtTimestampValidator());
validators.add(new JwtIssuerValidator(issuer));
return new DelegatingOAuth2TokenValidator<>(validators);
}
/**
* <p>
* Create a {@link Jwt} Validator that contains all standard validators.
* </p>
* <p>
* User's wanting to leverage the defaults plus additional validation can add the
* result of this method to {@code DelegatingOAuth2TokenValidator} along with the
* additional validators.
* </p>
* @return - a delegating validator containing all standard validators as well as any
* supplied
*/
public static OAuth2TokenValidator<Jwt> createDefault() {
return new DelegatingOAuth2TokenValidator<>(Arrays.asList(new JwtTimestampValidator()));
}
}
| 2,457 | 31.342105 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtTimestampValidator.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.jwt;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.util.Assert;
/**
* An implementation of {@link OAuth2TokenValidator} for verifying claims in a Jwt-based
* access token
*
* <p>
* Because clocks can differ between the Jwt source, say the Authorization Server, and its
* destination, say the Resource Server, there is a default clock leeway exercised when
* deciding if the current time is within the Jwt's specified operating window
*
* @author Josh Cummings
* @since 5.1
* @see Jwt
* @see OAuth2TokenValidator
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
*/
public final class JwtTimestampValidator implements OAuth2TokenValidator<Jwt> {
private final Log logger = LogFactory.getLog(getClass());
private static final Duration DEFAULT_MAX_CLOCK_SKEW = Duration.of(60, ChronoUnit.SECONDS);
private final Duration clockSkew;
private Clock clock = Clock.systemUTC();
/**
* A basic instance with no custom verification and the default max clock skew
*/
public JwtTimestampValidator() {
this(DEFAULT_MAX_CLOCK_SKEW);
}
public JwtTimestampValidator(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
this.clockSkew = clockSkew;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt jwt) {
Assert.notNull(jwt, "jwt cannot be null");
Instant expiry = jwt.getExpiresAt();
if (expiry != null) {
if (Instant.now(this.clock).minus(this.clockSkew).isAfter(expiry)) {
OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt expired at %s", jwt.getExpiresAt()));
return OAuth2TokenValidatorResult.failure(oAuth2Error);
}
}
Instant notBefore = jwt.getNotBefore();
if (notBefore != null) {
if (Instant.now(this.clock).plus(this.clockSkew).isBefore(notBefore)) {
OAuth2Error oAuth2Error = createOAuth2Error(String.format("Jwt used before %s", jwt.getNotBefore()));
return OAuth2TokenValidatorResult.failure(oAuth2Error);
}
}
return OAuth2TokenValidatorResult.success();
}
private OAuth2Error createOAuth2Error(String reason) {
this.logger.debug(reason);
return new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, reason,
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
/**
* Use this {@link Clock} with {@link Instant#now()} for assessing timestamp validity
* @param clock
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
}
| 3,596 | 32.616822 | 105 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtDecoder.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.jwt;
/**
* Implementations of this interface are responsible for "decoding" a JSON Web
* Token (JWT) from it's compact claims representation format to a {@link Jwt}.
*
* <p>
* JWTs may be represented using the JWS Compact Serialization format for a JSON Web
* Signature (JWS) structure or JWE Compact Serialization format for a JSON Web Encryption
* (JWE) structure. Therefore, implementors are responsible for verifying a JWS and/or
* decrypting a JWE.
*
* @author Joe Grandja
* @since 5.0
* @see Jwt
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7519">JSON Web Token
* (JWT)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516">JSON Web Encryption
* (JWE)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515#section-3.1">JWS
* Compact Serialization</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516#section-3.1">JWE
* Compact Serialization</a>
*/
@FunctionalInterface
public interface JwtDecoder {
/**
* Decodes the JWT from it's compact claims representation format and returns a
* {@link Jwt}.
* @param token the JWT value
* @return a {@link Jwt}
* @throws JwtException if an error occurs while attempting to decode the JWT
*/
Jwt decode(String token) throws JwtException;
}
| 2,075 | 36.071429 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/BadJwtException.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.jwt;
/**
* An exception similar to
* {@link org.springframework.security.authentication.BadCredentialsException} that
* indicates a {@link Jwt} that is invalid in some way.
*
* @author Josh Cummings
* @since 5.3
*/
public class BadJwtException extends JwtException {
public BadJwtException(String message) {
super(message);
}
public BadJwtException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,097 | 27.894737 | 83 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJWKSourceAdapter.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.jwt;
import java.util.List;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import reactor.core.publisher.Mono;
/**
* Adapts a {@link JWKSource} to a {@link ReactiveJWKSource} which must be non-blocking.
*
* @author Rob Winch
* @since 5.1
*/
class ReactiveJWKSourceAdapter implements ReactiveJWKSource {
private final JWKSource<SecurityContext> source;
/**
* Creates a new instance
* @param source
*/
ReactiveJWKSourceAdapter(JWKSource<SecurityContext> source) {
this.source = source;
}
@Override
public Mono<List<JWK>> get(JWKSelector jwkSelector) {
return Mono.fromCallable(() -> this.source.get(jwkSelector, null));
}
}
| 1,441 | 27.27451 | 88 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/SupplierJwtDecoder.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.jwt;
import java.util.function.Supplier;
import org.springframework.util.function.SingletonSupplier;
/**
* A {@link JwtDecoder} that lazily initializes another {@link JwtDecoder}
*
* @author Josh Cummings
* @since 5.6
*/
public final class SupplierJwtDecoder implements JwtDecoder {
private final Supplier<JwtDecoder> delegate;
public SupplierJwtDecoder(Supplier<JwtDecoder> jwtDecoderSupplier) {
this.delegate = SingletonSupplier.of(() -> {
try {
return jwtDecoderSupplier.get();
}
catch (Exception ex) {
throw wrapException(ex);
}
});
}
/**
* {@inheritDoc}
*/
@Override
public Jwt decode(String token) throws JwtException {
return this.delegate.get().decode(token);
}
private JwtDecoderInitializationException wrapException(Exception ex) {
return new JwtDecoderInitializationException("Failed to lazily resolve the supplied JwtDecoder instance", ex);
}
}
| 1,578 | 26.701754 | 112 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtEncoderParameters.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.jwt;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* A holder of parameters containing the JWS headers and JWT Claims Set.
*
* @author Joe Grandja
* @since 5.6
* @see JwsHeader
* @see JwtClaimsSet
* @see JwtEncoder
*/
public final class JwtEncoderParameters {
private final JwsHeader jwsHeader;
private final JwtClaimsSet claims;
private JwtEncoderParameters(JwsHeader jwsHeader, JwtClaimsSet claims) {
this.jwsHeader = jwsHeader;
this.claims = claims;
}
/**
* Returns a new {@link JwtEncoderParameters}, initialized with the provided
* {@link JwtClaimsSet}.
* @param claims the {@link JwtClaimsSet}
* @return the {@link JwtEncoderParameters}
*/
public static JwtEncoderParameters from(JwtClaimsSet claims) {
Assert.notNull(claims, "claims cannot be null");
return new JwtEncoderParameters(null, claims);
}
/**
* Returns a new {@link JwtEncoderParameters}, initialized with the provided
* {@link JwsHeader} and {@link JwtClaimsSet}.
* @param jwsHeader the {@link JwsHeader}
* @param claims the {@link JwtClaimsSet}
* @return the {@link JwtEncoderParameters}
*/
public static JwtEncoderParameters from(JwsHeader jwsHeader, JwtClaimsSet claims) {
Assert.notNull(jwsHeader, "jwsHeader cannot be null");
Assert.notNull(claims, "claims cannot be null");
return new JwtEncoderParameters(jwsHeader, claims);
}
/**
* Returns the {@link JwsHeader JWS headers}.
* @return the {@link JwsHeader}, or {@code null} if not specified
*/
@Nullable
public JwsHeader getJwsHeader() {
return this.jwsHeader;
}
/**
* Returns the {@link JwtClaimsSet claims}.
* @return the {@link JwtClaimsSet}
*/
public JwtClaimsSet getClaims() {
return this.claims;
}
}
| 2,427 | 27.904762 | 84 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtEncodingException.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.jwt;
/**
* This exception is thrown when an error occurs while attempting to encode a JSON Web
* Token (JWT).
*
* @author Joe Grandja
* @since 5.6
*/
public class JwtEncodingException extends JwtException {
/**
* Constructs a {@code JwtEncodingException} using the provided parameters.
* @param message the detail message
*/
public JwtEncodingException(String message) {
super(message);
}
/**
* Constructs a {@code JwtEncodingException} using the provided parameters.
* @param message the detail message
* @param cause the root cause
*/
public JwtEncodingException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,328 | 27.891304 | 86 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.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.jwt;
import java.util.Map;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.util.Assert;
/**
* Allows creating a {@link ReactiveJwtDecoder} from an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig">OpenID
* Provider Configuration</a> or
* <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server Metadata
* Request</a> based on provided issuer and method invoked.
*
* @author Josh Cummings
* @since 5.1
*/
public final class ReactiveJwtDecoders {
private ReactiveJwtDecoders() {
}
/**
* Creates a {@link ReactiveJwtDecoder} using the provided <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by making an <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">OpenID
* Provider Configuration Request</a> and using the values in the <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> to initialize the {@link ReactiveJwtDecoder}.
* @param oidcIssuerLocation the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link ReactiveJwtDecoder} that was initialized by the OpenID Provider
* Configuration.
*/
public static ReactiveJwtDecoder fromOidcIssuerLocation(String oidcIssuerLocation) {
Assert.hasText(oidcIssuerLocation, "oidcIssuerLocation cannot be empty");
Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
.getConfigurationForOidcIssuerLocation(oidcIssuerLocation);
return withProviderConfiguration(configuration, oidcIssuerLocation);
}
/**
* Creates a {@link ReactiveJwtDecoder} using the provided <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* by querying three different discovery endpoints serially, using the values in the
* first successful response to initialize. If an endpoint returns anything other than
* a 200 or a 4xx, the method will exit without attempting subsequent endpoints.
*
* The three endpoints are computed as follows, given that the {@code issuer} is
* composed of a {@code host} and a {@code path}:
*
* <ol>
* <li>{@code host/.well-known/openid-configuration/path}, as defined in
* <a href="https://tools.ietf.org/html/rfc8414#section-5">RFC 8414's Compatibility
* Notes</a>.</li>
* <li>{@code issuer/.well-known/openid-configuration}, as defined in <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationRequest">
* OpenID Provider Configuration</a>.</li>
* <li>{@code host/.well-known/oauth-authorization-server/path}, as defined in
* <a href="https://tools.ietf.org/html/rfc8414#section-3.1">Authorization Server
* Metadata Request</a>.</li>
* </ol>
*
* Note that the second endpoint is the equivalent of calling
* {@link ReactiveJwtDecoders#fromOidcIssuerLocation(String)}
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link ReactiveJwtDecoder} that was initialized by one of the described
* endpoints
*/
public static ReactiveJwtDecoder fromIssuerLocation(String issuer) {
Assert.hasText(issuer, "issuer cannot be empty");
Map<String, Object> configuration = JwtDecoderProviderConfigurationUtils
.getConfigurationForIssuerLocation(issuer);
return withProviderConfiguration(configuration, issuer);
}
/**
* Build {@link ReactiveJwtDecoder} from <a href=
* "https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse">OpenID
* Provider Configuration Response</a> and
* <a href="https://tools.ietf.org/html/rfc8414#section-3.2">Authorization Server
* Metadata Response</a>.
* @param configuration the configuration values
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return {@link ReactiveJwtDecoder}
*/
private static ReactiveJwtDecoder withProviderConfiguration(Map<String, Object> configuration, String issuer) {
JwtDecoderProviderConfigurationUtils.validateIssuer(configuration, issuer);
OAuth2TokenValidator<Jwt> jwtValidator = JwtValidators.createDefaultWithIssuer(issuer);
String jwkSetUri = configuration.get("jwks_uri").toString();
NimbusReactiveJwtDecoder jwtDecoder = NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri)
.jwtProcessorCustomizer(ReactiveJwtDecoderProviderConfigurationUtils::addJWSAlgorithms).build();
jwtDecoder.setJwtValidator(jwtValidator);
return jwtDecoder;
}
}
| 5,403 | 45.188034 | 112 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/ReactiveJwtDecoderProviderConfigurationUtils.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.jwt;
import java.net.URI;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKMatcher;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.JWSVerificationKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.proc.ConfigurableJWTProcessor;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.util.UriComponentsBuilder;
final class ReactiveJwtDecoderProviderConfigurationUtils {
private static final String OIDC_METADATA_PATH = "/.well-known/openid-configuration";
private static final String OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
static <C extends SecurityContext> Mono<ConfigurableJWTProcessor<C>> addJWSAlgorithms(
ReactiveRemoteJWKSource jwkSource, ConfigurableJWTProcessor<C> jwtProcessor) {
JWSKeySelector<C> selector = jwtProcessor.getJWSKeySelector();
if (!(selector instanceof JWSVerificationKeySelector)) {
return Mono.just(jwtProcessor);
}
JWKSource<C> delegate = ((JWSVerificationKeySelector<C>) selector).getJWKSource();
return getJWSAlgorithms(jwkSource).map((algorithms) -> new JWSVerificationKeySelector<>(algorithms, delegate))
.map((replacement) -> {
jwtProcessor.setJWSKeySelector(replacement);
return jwtProcessor;
});
}
static Mono<Set<JWSAlgorithm>> getJWSAlgorithms(ReactiveRemoteJWKSource jwkSource) {
JWKMatcher jwkMatcher = new JWKMatcher.Builder().publicOnly(true).keyUses(KeyUse.SIGNATURE, null)
.keyTypes(KeyType.RSA, KeyType.EC).build();
return jwkSource.get(new JWKSelector(jwkMatcher)).map((jwks) -> {
Set<JWSAlgorithm> jwsAlgorithms = new HashSet<>();
for (JWK jwk : jwks) {
if (jwk.getAlgorithm() != null) {
JWSAlgorithm jwsAlgorithm = JWSAlgorithm.parse(jwk.getAlgorithm().getName());
jwsAlgorithms.add(jwsAlgorithm);
}
else {
if (jwk.getKeyType() == KeyType.RSA) {
jwsAlgorithms.addAll(JWSAlgorithm.Family.RSA);
}
else if (jwk.getKeyType() == KeyType.EC) {
jwsAlgorithms.addAll(JWSAlgorithm.Family.EC);
}
}
}
Assert.notEmpty(jwsAlgorithms, "Failed to find any algorithms from the JWK set");
return jwsAlgorithms;
}).onErrorMap(KeySourceException.class, IllegalStateException::new);
}
static Mono<Map<String, Object>> getConfigurationForIssuerLocation(String issuer, WebClient web) {
URI uri = URI.create(issuer);
return getConfiguration(issuer, web, oidc(uri), oidcRfc8414(uri), oauth(uri));
}
private static URI oidc(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(issuer.getPath() + OIDC_METADATA_PATH)
.build(Collections.emptyMap());
// @formatter:on
}
private static URI oidcRfc8414(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(OIDC_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
}
private static URI oauth(URI issuer) {
// @formatter:off
return UriComponentsBuilder.fromUri(issuer)
.replacePath(OAUTH_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
}
private static Mono<Map<String, Object>> getConfiguration(String issuer, WebClient web, URI... uris) {
String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\"";
return Flux.just(uris).concatMap((uri) -> web.get().uri(uri).retrieve().bodyToMono(STRING_OBJECT_MAP))
.flatMap((configuration) -> {
if (configuration.get("jwks_uri") == null) {
return Mono
.error(() -> new IllegalArgumentException("The public JWK set URI must not be null"));
}
return Mono.just(configuration);
})
.onErrorContinue(
(ex) -> ex instanceof WebClientResponseException
&& ((WebClientResponseException) ex).getStatusCode().is4xxClientError(),
(ex, object) -> {
})
.onErrorMap(RuntimeException.class,
(ex) -> (ex instanceof IllegalArgumentException) ? ex
: new IllegalArgumentException(errorMessage, ex))
.next().switchIfEmpty(Mono.error(() -> new IllegalArgumentException(errorMessage)));
}
private ReactiveJwtDecoderProviderConfigurationUtils() {
}
}
| 5,678 | 37.632653 | 145 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtValidationException.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.jwt;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult;
import org.springframework.util.Assert;
/**
* An exception that results from an unsuccessful {@link OAuth2TokenValidatorResult}
*
* @author Josh Cummings
* @since 5.1
*/
public class JwtValidationException extends BadJwtException {
private final Collection<OAuth2Error> errors;
/**
* Constructs a {@link JwtValidationException} using the provided parameters
*
* While each {@link OAuth2Error} does contain an error description, this constructor
* can take an overarching description that encapsulates the composition of failures
*
* That said, it is appropriate to pass one of the messages from the error list in as
* the exception description, for example:
*
* <pre>
* if ( result.hasErrors() ) {
* Collection<OAuth2Error> errors = result.getErrors();
* throw new JwtValidationException(errors.iterator().next().getDescription(), errors);
* }
* </pre>
* @param message - the exception message
* @param errors - a list of {@link OAuth2Error}s with extra detail about the
* validation result
*/
public JwtValidationException(String message, Collection<OAuth2Error> errors) {
super(message);
Assert.notEmpty(errors, "errors cannot be empty");
this.errors = new ArrayList<>(errors);
}
/**
* Return the list of {@link OAuth2Error}s associated with this exception
* @return the list of {@link OAuth2Error}s associated with this exception
*/
public Collection<OAuth2Error> getErrors() {
return this.errors;
}
}
| 2,352 | 32.614286 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JwtClaimAccessor.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.jwt;
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 may be contained in the JSON
* object JWT Claims Set of a JSON Web Token (JWT).
*
* @author Joe Grandja
* @since 5.0
* @see ClaimAccessor
* @see JwtClaimNames
* @see Jwt
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7519#section-4.1">Registered Claim Names</a>
*/
public interface JwtClaimAccessor extends ClaimAccessor {
/**
* Returns the Issuer {@code (iss)} claim which identifies the principal that issued
* the JWT.
* @return the Issuer identifier
*/
default URL getIssuer() {
return this.getClaimAsURL(JwtClaimNames.ISS);
}
/**
* Returns the Subject {@code (sub)} claim which identifies the principal that is the
* subject of the JWT.
* @return the Subject identifier
*/
default String getSubject() {
return this.getClaimAsString(JwtClaimNames.SUB);
}
/**
* Returns the Audience {@code (aud)} claim which identifies the recipient(s) that the
* JWT is intended for.
* @return the Audience(s) that this JWT intended for
*/
default List<String> getAudience() {
return this.getClaimAsStringList(JwtClaimNames.AUD);
}
/**
* Returns the Expiration time {@code (exp)} claim which identifies the expiration
* time on or after which the JWT MUST NOT be accepted for processing.
* @return the Expiration time on or after which the JWT MUST NOT be accepted for
* processing
*/
default Instant getExpiresAt() {
return this.getClaimAsInstant(JwtClaimNames.EXP);
}
/**
* Returns the Not Before {@code (nbf)} claim which identifies the time before which
* the JWT MUST NOT be accepted for processing.
* @return the Not Before time before which the JWT MUST NOT be accepted for
* processing
*/
default Instant getNotBefore() {
return this.getClaimAsInstant(JwtClaimNames.NBF);
}
/**
* Returns the Issued at {@code (iat)} claim which identifies the time at which the
* JWT was issued.
* @return the Issued at claim which identifies the time at which the JWT was issued
*/
default Instant getIssuedAt() {
return this.getClaimAsInstant(JwtClaimNames.IAT);
}
/**
* Returns the JWT ID {@code (jti)} claim which provides a unique identifier for the
* JWT.
* @return the JWT ID claim which provides a unique identifier for the JWT
*/
default String getId() {
return this.getClaimAsString(JwtClaimNames.JTI);
}
}
| 3,199 | 29.47619 | 87 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/JwaAlgorithm.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.jose;
/**
* Super interface for cryptographic algorithms defined by the JSON Web Algorithms (JWA)
* specification and used by JSON Web Signature (JWS) to digitally sign or create a MAC of
* the contents and JSON Web Encryption (JWE) to encrypt the contents.
*
* @author Joe Grandja
* @since 5.5
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms
* (JWA)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7516">JSON Web Encryption
* (JWE)</a>
*/
public interface JwaAlgorithm {
/**
* Returns the algorithm name.
* @return the algorithm name
*/
String getName();
}
| 1,409 | 32.571429 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/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 JSON Web Signature (JWS).
*/
package org.springframework.security.oauth2.jose.jws;
| 764 | 35.428571 | 78 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/SignatureAlgorithm.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.jose.jws;
/**
* An enumeration of the cryptographic algorithms defined by the JSON Web Algorithms (JWA)
* specification and used by JSON Web Signature (JWS) to digitally sign the contents of
* the JWS Protected Header and JWS Payload.
*
* @author Joe Grandja
* @since 5.2
* @see JwsAlgorithm
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms
* (JWA)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7518#section-3">Cryptographic Algorithms for Digital
* Signatures and MACs</a>
*/
public enum SignatureAlgorithm implements JwsAlgorithm {
/**
* RSASSA-PKCS1-v1_5 using SHA-256 (Recommended)
*/
RS256(JwsAlgorithms.RS256),
/**
* RSASSA-PKCS1-v1_5 using SHA-384 (Optional)
*/
RS384(JwsAlgorithms.RS384),
/**
* RSASSA-PKCS1-v1_5 using SHA-512 (Optional)
*/
RS512(JwsAlgorithms.RS512),
/**
* ECDSA using P-256 and SHA-256 (Recommended+)
*/
ES256(JwsAlgorithms.ES256),
/**
* ECDSA using P-384 and SHA-384 (Optional)
*/
ES384(JwsAlgorithms.ES384),
/**
* ECDSA using P-521 and SHA-512 (Optional)
*/
ES512(JwsAlgorithms.ES512),
/**
* RSASSA-PSS using SHA-256 and MGF1 with SHA-256 (Optional)
*/
PS256(JwsAlgorithms.PS256),
/**
* RSASSA-PSS using SHA-384 and MGF1 with SHA-384 (Optional)
*/
PS384(JwsAlgorithms.PS384),
/**
* RSASSA-PSS using SHA-512 and MGF1 with SHA-512 (Optional)
*/
PS512(JwsAlgorithms.PS512);
private final String name;
SignatureAlgorithm(String name) {
this.name = name;
}
/**
* Returns the algorithm name.
* @return the algorithm name
*/
@Override
public String getName() {
return this.name;
}
/**
* Attempt to resolve the provided algorithm name to a {@code SignatureAlgorithm}.
* @param name the algorithm name
* @return the resolved {@code SignatureAlgorithm}, or {@code null} if not found
*/
public static SignatureAlgorithm from(String name) {
for (SignatureAlgorithm value : values()) {
if (value.getName().equals(name)) {
return value;
}
}
return null;
}
}
| 2,832 | 24.294643 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/JwsAlgorithm.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.jose.jws;
import org.springframework.security.oauth2.jose.JwaAlgorithm;
/**
* Super interface for cryptographic algorithms defined by the JSON Web Algorithms (JWA)
* specification and used by JSON Web Signature (JWS) to digitally sign or create a MAC of
* the contents of the JWS Protected Header and JWS Payload.
*
* @author Joe Grandja
* @since 5.2
* @see JwaAlgorithm
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms
* (JWA)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7518#section-3">Cryptographic Algorithms for Digital
* Signatures and MACs</a>
*/
public interface JwsAlgorithm extends JwaAlgorithm {
}
| 1,460 | 35.525 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/JwsAlgorithms.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.jose.jws;
/**
* The cryptographic algorithms defined by the JSON Web Algorithms (JWA) specification and
* used by JSON Web Signature (JWS) to digitally sign or create a MAC of the contents of
* the JWS Protected Header and JWS Payload.
*
* @author Joe Grandja
* @since 5.0
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms
* (JWA)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7518#section-3">Cryptographic Algorithms for Digital
* Signatures and MACs</a>
*/
public final class JwsAlgorithms {
/**
* HMAC using SHA-256 (Required)
*/
public static final String HS256 = "HS256";
/**
* HMAC using SHA-384 (Optional)
*/
public static final String HS384 = "HS384";
/**
* HMAC using SHA-512 (Optional)
*/
public static final String HS512 = "HS512";
/**
* RSASSA-PKCS1-v1_5 using SHA-256 (Recommended)
*/
public static final String RS256 = "RS256";
/**
* RSASSA-PKCS1-v1_5 using SHA-384 (Optional)
*/
public static final String RS384 = "RS384";
/**
* RSASSA-PKCS1-v1_5 using SHA-512 (Optional)
*/
public static final String RS512 = "RS512";
/**
* ECDSA using P-256 and SHA-256 (Recommended+)
*/
public static final String ES256 = "ES256";
/**
* ECDSA using P-384 and SHA-384 (Optional)
*/
public static final String ES384 = "ES384";
/**
* ECDSA using P-521 and SHA-512 (Optional)
*/
public static final String ES512 = "ES512";
/**
* RSASSA-PSS using SHA-256 and MGF1 with SHA-256 (Optional)
*/
public static final String PS256 = "PS256";
/**
* RSASSA-PSS using SHA-384 and MGF1 with SHA-384 (Optional)
*/
public static final String PS384 = "PS384";
/**
* RSASSA-PSS using SHA-512 and MGF1 with SHA-512 (Optional)
*/
public static final String PS512 = "PS512";
private JwsAlgorithms() {
}
}
| 2,616 | 25.17 | 90 | java |
null | spring-security-main/oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/MacAlgorithm.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.jose.jws;
/**
* An enumeration of the cryptographic algorithms defined by the JSON Web Algorithms (JWA)
* specification and used by JSON Web Signature (JWS) to create a MAC of the contents of
* the JWS Protected Header and JWS Payload.
*
* @author Joe Grandja
* @since 5.2
* @see JwsAlgorithm
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms
* (JWA)</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature
* (JWS)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc7518#section-3">Cryptographic Algorithms for Digital
* Signatures and MACs</a>
*/
public enum MacAlgorithm implements JwsAlgorithm {
/**
* HMAC using SHA-256 (Required)
*/
HS256(JwsAlgorithms.HS256),
/**
* HMAC using SHA-384 (Optional)
*/
HS384(JwsAlgorithms.HS384),
/**
* HMAC using SHA-512 (Optional)
*/
HS512(JwsAlgorithms.HS512);
private final String name;
MacAlgorithm(String name) {
this.name = name;
}
/**
* Returns the algorithm name.
* @return the algorithm name
*/
@Override
public String getName() {
return this.name;
}
/**
* Attempt to resolve the provided algorithm name to a {@code MacAlgorithm}.
* @param name the algorithm name
* @return the resolved {@code MacAlgorithm}, or {@code null} if not found
*/
public static MacAlgorithm from(String name) {
for (MacAlgorithm algorithm : values()) {
if (algorithm.getName().equals(name)) {
return algorithm;
}
}
return null;
}
}
| 2,202 | 25.865854 | 90 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/core/TestOAuth2AuthenticatedPrincipals.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.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
/**
* Test values of {@link OAuth2AuthenticatedPrincipal}s
*
* @author Josh Cummings
*/
public final class TestOAuth2AuthenticatedPrincipals {
private TestOAuth2AuthenticatedPrincipals() {
}
public static OAuth2AuthenticatedPrincipal active() {
return active((attributes) -> {
});
}
public static OAuth2AuthenticatedPrincipal active(Consumer<Map<String, Object>> attributesConsumer) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true);
attributes.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource"));
attributes.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4");
attributes.put(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238));
attributes.put(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L));
attributes.put(OAuth2TokenIntrospectionClaimNames.ISS, url("https://server.example.com/"));
attributes.put(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin"));
attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis");
attributes.put(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe");
attributesConsumer.accept(attributes);
Collection<GrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("SCOPE_read"),
new SimpleGrantedAuthority("SCOPE_write"), new SimpleGrantedAuthority("SCOPE_dolphin"));
return new OAuth2IntrospectionAuthenticatedPrincipal(attributes, authorities);
}
private static URL url(String url) {
try {
return new URL(url);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
| 2,903 | 37.72 | 115 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/DefaultAuthenticationEventPublisherBearerTokenTests.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.server.resource;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.authentication.DefaultAuthenticationEventPublisher;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.TestJwts;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link DefaultAuthenticationEventPublisher}'s bearer token use cases
*
* {@see DefaultAuthenticationEventPublisher}
*/
public class DefaultAuthenticationEventPublisherBearerTokenTests {
DefaultAuthenticationEventPublisher publisher;
@Test
public void publishAuthenticationFailureWhenInvalidBearerTokenExceptionThenMaps() {
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
Authentication authentication = new JwtAuthenticationToken(TestJwts.jwt().build());
Exception cause = new Exception();
this.publisher = new DefaultAuthenticationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new InvalidBearerTokenException("invalid"), authentication);
this.publisher.publishAuthenticationFailure(new InvalidBearerTokenException("invalid", cause), authentication);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
}
| 2,309 | 41.777778 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorsTests.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.server.resource;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat;
public class BearerTokenErrorsTests {
@Test
public void invalidRequestWhenMessageGivenThenBearerTokenErrorReturned() {
String message = "message";
BearerTokenError error = BearerTokenErrors.invalidRequest(message);
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_REQUEST);
assertThat(error.getDescription()).isSameAs(message);
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.BAD_REQUEST);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Test
public void invalidRequestWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() {
String message = "has \"invalid\" chars";
BearerTokenError error = BearerTokenErrors.invalidRequest(message);
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_REQUEST);
assertThat(error.getDescription()).isEqualTo("Invalid request");
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.BAD_REQUEST);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Test
public void invalidTokenWhenMessageGivenThenBearerTokenErrorReturned() {
String message = "message";
BearerTokenError error = BearerTokenErrors.invalidToken(message);
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_TOKEN);
assertThat(error.getDescription()).isSameAs(message);
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.UNAUTHORIZED);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Test
public void invalidTokenWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() {
String message = "has \"invalid\" chars";
BearerTokenError error = BearerTokenErrors.invalidToken(message);
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INVALID_TOKEN);
assertThat(error.getDescription()).isEqualTo("Invalid token");
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.UNAUTHORIZED);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Test
public void insufficientScopeWhenMessageGivenThenBearerTokenErrorReturned() {
String message = "message";
String scope = "scope";
BearerTokenError error = BearerTokenErrors.insufficientScope(message, scope);
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
assertThat(error.getDescription()).isSameAs(message);
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.FORBIDDEN);
assertThat(error.getScope()).isSameAs(scope);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Test
public void insufficientScopeWhenInvalidMessageGivenThenDefaultBearerTokenErrorReturned() {
String message = "has \"invalid\" chars";
BearerTokenError error = BearerTokenErrors.insufficientScope(message, "scope");
assertThat(error.getErrorCode()).isSameAs(BearerTokenErrorCodes.INSUFFICIENT_SCOPE);
assertThat(error.getDescription()).isSameAs("Insufficient scope");
assertThat(error.getHttpStatus()).isSameAs(HttpStatus.FORBIDDEN);
assertThat(error.getScope()).isNull();
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
}
}
| 4,046 | 43.472527 | 92 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorTests.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.server.resource;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link BearerTokenError}
*
* @author Vedran Pavic
* @author Josh Cummings
*/
public class BearerTokenErrorTests {
private static final String TEST_ERROR_CODE = "test-code";
private static final HttpStatus TEST_HTTP_STATUS = HttpStatus.UNAUTHORIZED;
private static final String TEST_DESCRIPTION = "test-description";
private static final String TEST_URI = "https://example.com";
private static final String TEST_SCOPE = "test-scope";
@Test
public void constructorWithErrorCodeWhenErrorCodeIsValidThenCreated() {
BearerTokenError error = new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, null, null);
assertThat(error.getErrorCode()).isEqualTo(TEST_ERROR_CODE);
assertThat(error.getHttpStatus()).isEqualTo(TEST_HTTP_STATUS);
assertThat(error.getDescription()).isNull();
assertThat(error.getUri()).isNull();
assertThat(error.getScope()).isNull();
}
@Test
public void constructorWithErrorCodeAndHttpStatusWhenErrorCodeIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(null, TEST_HTTP_STATUS, null, null))
.withMessage("errorCode cannot be empty");
// @formatter:on
}
@Test
public void constructorWithErrorCodeAndHttpStatusWhenErrorCodeIsEmptyThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError("", TEST_HTTP_STATUS, null, null))
.withMessage("errorCode cannot be empty");
// @formatter:on
}
@Test
public void constructorWithErrorCodeAndHttpStatusWhenHttpStatusIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, null, null, null))
.withMessage("httpStatus cannot be null");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenAllParametersAreValidThenCreated() {
BearerTokenError error = new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI,
TEST_SCOPE);
assertThat(error.getErrorCode()).isEqualTo(TEST_ERROR_CODE);
assertThat(error.getHttpStatus()).isEqualTo(TEST_HTTP_STATUS);
assertThat(error.getDescription()).isEqualTo(TEST_DESCRIPTION);
assertThat(error.getUri()).isEqualTo(TEST_URI);
assertThat(error.getScope()).isEqualTo(TEST_SCOPE);
}
@Test
public void constructorWithAllParametersWhenErrorCodeIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(null, TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE))
.withMessage("errorCode cannot be empty");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenErrorCodeIsEmptyThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError("", TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE))
.withMessage("errorCode cannot be empty");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenHttpStatusIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, null, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE))
.withMessage("httpStatus cannot be null");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenErrorCodeIsInvalidThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE + "\"",
TEST_HTTP_STATUS, TEST_DESCRIPTION, TEST_URI, TEST_SCOPE)
)
.withMessageContaining("errorCode")
.withMessageContaining("RFC 6750");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenDescriptionIsInvalidThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS,
TEST_DESCRIPTION + "\"", TEST_URI, TEST_SCOPE)
)
.withMessageContaining("description")
.withMessageContaining("RFC 6750");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenErrorUriIsInvalidThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS, TEST_DESCRIPTION,
TEST_URI + "\"", TEST_SCOPE)
)
.withMessageContaining("errorUri")
.withMessageContaining("RFC 6750");
// @formatter:on
}
@Test
public void constructorWithAllParametersWhenScopeIsInvalidThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenError(TEST_ERROR_CODE, TEST_HTTP_STATUS,
TEST_DESCRIPTION, TEST_URI, TEST_SCOPE + "\"")
)
.withMessageContaining("scope")
.withMessageContaining("RFC 6750");
// @formatter:on
}
}
| 5,940 | 34.363095 | 110 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolverTests.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.server.resource.web;
import java.util.Base64;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link DefaultBearerTokenResolver}.
*
* @author Vedran Pavic
*/
public class DefaultBearerTokenResolverTests {
private static final String CUSTOM_HEADER = "custom-header";
private static final String TEST_TOKEN = "test-token";
private DefaultBearerTokenResolver resolver;
@BeforeEach
public void setUp() {
this.resolver = new DefaultBearerTokenResolver();
}
@Test
public void resolveWhenValidHeaderIsPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
// gh-8502
@Test
public void resolveWhenHeaderEndsWithPaddingIndicatorThenTokenIsResolved() {
String token = TEST_TOKEN + "==";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + token);
assertThat(this.resolver.resolve(request)).isEqualTo(token);
}
@Test
public void resolveWhenCustomDefinedHeaderIsValidAndPresentThenTokenIsResolved() {
this.resolver.setBearerTokenHeaderName(CUSTOM_HEADER);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CUSTOM_HEADER, "Bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenLowercaseHeaderIsPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("authorization", "bearer " + TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenNoHeaderIsPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("test:test".getBytes()));
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer ");
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining(("Bearer token is malformed"));
}
@Test
public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer an\"invalid\"token");
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining(("Bearer token is malformed"));
}
@Test
public void resolveWhenValidHeaderIsPresentTogetherWithFormParameterThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + TEST_TOKEN);
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining("Found multiple bearer tokens in the request");
}
@Test
public void resolveWhenValidHeaderIsPresentTogetherWithQueryParameterThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("Authorization", "Bearer " + TEST_TOKEN);
request.setMethod("GET");
request.setQueryString("access_token=" + TEST_TOKEN);
request.addParameter("access_token", TEST_TOKEN);
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining("Found multiple bearer tokens in the request");
}
// gh-10326
@Test
public void resolveWhenRequestContainsTwoAccessTokenQueryParametersThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.addParameter("access_token", "token1", "token2");
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining("Found multiple bearer tokens in the request");
}
// gh-10326
@Test
public void resolveWhenRequestContainsTwoAccessTokenFormParametersThenAuthenticationExceptionIsThrown() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", "token1", "token2");
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.resolver.resolve(request))
.withMessageContaining("Found multiple bearer tokens in the request");
}
// gh-10326
@Test
public void resolveWhenParameterIsPresentInMultipartRequestAndFormParameterSupportedThenTokenIsNotResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("multipart/form-data");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenPostAndFormParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenPutAndFormParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("PUT");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenPatchAndFormParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("PATCH");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenDeleteAndFormParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("DELETE");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenGetAndFormParameterIsPresentAndSupportedThenTokenIsNotResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenPostAndFormParameterIsSupportedAndQueryParameterIsPresentThenTokenIsNotResolved() {
this.resolver.setAllowFormEncodedBodyParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.setQueryString("access_token=" + TEST_TOKEN);
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenFormParameterIsPresentAndNotSupportedThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("POST");
request.setContentType("application/x-www-form-urlencoded");
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
@Test
public void resolveWhenQueryParameterIsPresentAndSupportedThenTokenIsResolved() {
this.resolver.setAllowUriQueryParameter(true);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setQueryString("access_token=" + TEST_TOKEN);
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenQueryParameterIsPresentAndNotSupportedThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setQueryString("access_token=" + TEST_TOKEN);
request.addParameter("access_token", TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isNull();
}
}
| 10,404 | 38.71374 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPointTests.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.server.resource.web;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link BearerTokenAuthenticationEntryPoint}.
*
* @author Vedran Pavic
* @author Josh Cummings
*/
public class BearerTokenAuthenticationEntryPointTests {
private BearerTokenAuthenticationEntryPoint authenticationEntryPoint;
@BeforeEach
public void setUp() {
this.authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint();
}
@Test
public void commenceWhenNoBearerTokenErrorThenStatus401AndAuthHeader() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("test"));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer");
}
@Test
public void commenceWhenNoBearerTokenErrorAndRealmSetThenStatus401AndAuthHeaderWithRealm() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
this.authenticationEntryPoint.setRealmName("test");
this.authenticationEntryPoint.commence(request, response, new BadCredentialsException("test"));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer realm=\"test\"");
}
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"invalid_request\"");
}
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithErrorDetails() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
"The access token expired", null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"invalid_request\", error_description=\"The access token expired\"");
}
@Test
public void commenceWhenInvalidRequestErrorThenStatus400AndHeaderWithErrorUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
null, "https://example.com", null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(400);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"invalid_request\", error_uri=\"https://example.com\"");
}
@Test
public void commenceWhenInvalidTokenErrorThenStatus401AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(401);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"invalid_token\"");
}
@Test
public void commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithError() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
null, null);
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer error=\"insufficient_scope\"");
}
@Test
public void commenceWhenInsufficientScopeErrorThenStatus403AndHeaderWithErrorAndScope() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
null, null, "test.read test.write");
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("Bearer error=\"insufficient_scope\", scope=\"test.read test.write\"");
}
@Test
public void commenceWhenInsufficientScopeAndRealmSetThenStatus403AndHeaderWithErrorAndAllDetails()
throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN,
"Insufficient scope", "https://example.com", "test.read test.write");
this.authenticationEntryPoint.setRealmName("test");
this.authenticationEntryPoint.commence(request, response, new OAuth2AuthenticationException(error));
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo(
"Bearer realm=\"test\", error=\"insufficient_scope\", error_description=\"Insufficient scope\", "
+ "error_uri=\"https://example.com\", scope=\"test.read test.write\"");
}
@Test
public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() {
this.authenticationEntryPoint.setRealmName(null);
}
}
| 7,681 | 48.24359 | 111 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/MockExchangeFunction.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.server.resource.web;
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,684 | 26.622951 | 75 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolverTests.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.server.resource.web;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for {@link HeaderBearerTokenResolver}
*
* @author Elena Felder
*/
public class HeaderBearerTokenResolverTests {
private static final String TEST_TOKEN = "test-token";
private static final String CORRECT_HEADER = "jwt-assertion";
private HeaderBearerTokenResolver resolver = new HeaderBearerTokenResolver(CORRECT_HEADER);
@Test
public void constructorWhenHeaderNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new HeaderBearerTokenResolver(null))
.withMessage("header cannot be empty");
// @formatter:on
}
@Test
public void constructorWhenHeaderEmptyThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new HeaderBearerTokenResolver(""))
.withMessage("header cannot be empty");
// @formatter:on
}
@Test
public void resolveWhenTokenPresentThenTokenIsResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(CORRECT_HEADER, TEST_TOKEN);
assertThat(this.resolver.resolve(request)).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenTokenNotPresentThenTokenIsNotResolved() {
MockHttpServletRequest request = new MockHttpServletRequest();
assertThat(this.resolver.resolve(request)).isNull();
}
}
| 2,258 | 30.816901 | 92 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunctionTests.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.server.resource.web.reactive.function.client;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.util.context.Context;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.web.MockExchangeFunction;
import org.springframework.web.reactive.function.client.ClientRequest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ServletBearerExchangeFilterFunction}
*
* @author Josh Cummings
*/
@ExtendWith(MockitoExtension.class)
public class ServletBearerExchangeFilterFunctionTests {
private ServletBearerExchangeFilterFunction function = new ServletBearerExchangeFilterFunction();
private MockExchangeFunction exchange = new MockExchangeFunction();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
private Authentication authentication = new AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken>(
this.accessToken) {
@Override
public Map<String, Object> getTokenAttributes() {
return Collections.emptyMap();
}
};
@Test
public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
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();
}
// gh-7353
@Test
public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() {
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).contextWrite(context(token)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthenticatedThenAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).contextWrite(context(this.authentication)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
@Test
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing").build();
this.function.filter(request, this.exchange).contextWrite(context(this.authentication)).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}
private Context context(Authentication authentication) {
Map<Class<?>, Object> contextAttributes = new HashMap<>();
contextAttributes.put(Authentication.class, authentication);
return Context.of(ServletBearerExchangeFilterFunction.SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY,
contextAttributes);
}
}
| 4,504 | 41.5 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.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.server.resource.web.reactive.function.client;
import java.net.URI;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.web.MockExchangeFunction;
import org.springframework.web.reactive.function.client.ClientRequest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ServerBearerExchangeFilterFunction}
*
* @author Josh Cummings
*/
public class ServerBearerExchangeFilterFunctionTests {
private ServerBearerExchangeFilterFunction function = new ServerBearerExchangeFilterFunction();
private MockExchangeFunction exchange = new MockExchangeFunction();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
private Authentication authentication = new AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken>(
this.accessToken) {
@Override
public Map<String, Object> getTokenAttributes() {
return Collections.emptyMap();
}
};
@Test
public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
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 filterWhenAuthenticatedThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-7353
@Test
public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(token)).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing").build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication)).block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}
}
| 4,248 | 42.357143 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.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.server.resource.web.access;
import java.util.Collections;
import java.util.Map;
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.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link BearerTokenAccessDeniedHandlerTests}
*
* @author Josh Cummings
*/
public class BearerTokenAccessDeniedHandlerTests {
private BearerTokenAccessDeniedHandler accessDeniedHandler;
@BeforeEach
public void setUp() {
this.accessDeniedHandler = new BearerTokenAccessDeniedHandler();
}
@Test
public void handleWhenNotOAuth2AuthenticatedThenStatus403() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setUserPrincipal(authentication);
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer");
}
@Test
public void handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication authentication = new TestingAuthenticationToken("user", "pass");
request.setUserPrincipal(authentication);
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
assertThat(response.getHeader("WWW-Authenticate")).isEqualTo("Bearer realm=\"test\"");
}
@Test
public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute()
throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
request.setUserPrincipal(token);
this.accessDeniedHandler.handle(request, response, null);
assertThat(response.getStatus()).isEqualTo(403);
// @formatter:off
assertThat(response.getHeader("WWW-Authenticate"))
.isEqualTo("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\"");
// @formatter:on
}
@Test
public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() {
this.accessDeniedHandler.setRealmName(null);
}
static class TestingOAuth2TokenAuthenticationToken
extends AbstractOAuth2TokenAuthenticationToken<TestingOAuth2TokenAuthenticationToken.TestingOAuth2Token> {
private Map<String, Object> attributes;
protected TestingOAuth2TokenAuthenticationToken(Map<String, Object> attributes) {
super(new TestingOAuth2Token("token"));
this.attributes = attributes;
}
@Override
public Map<String, Object> getTokenAttributes() {
return this.attributes;
}
static class TestingOAuth2Token extends AbstractOAuth2Token {
TestingOAuth2Token(String tokenValue) {
super(tokenValue);
}
}
}
}
| 4,387 | 35.87395 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandlerTests.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.server.resource.web.access.server;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AbstractOAuth2Token;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.web.server.ServerWebExchange;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
public class BearerTokenServerAccessDeniedHandlerTests {
private BearerTokenServerAccessDeniedHandler accessDeniedHandler;
@BeforeEach
public void setUp() {
this.accessDeniedHandler = new BearerTokenServerAccessDeniedHandler();
}
@Test
public void handleWhenNotOAuth2AuthenticatedThenStatus403() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate")).isEqualTo(Arrays.asList("Bearer"));
}
@Test
public void handleWhenNotOAuth2AuthenticatedAndRealmSetThenStatus403AndAuthHeaderWithRealm() {
Authentication token = new TestingAuthenticationToken("user", "pass");
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.setRealmName("test");
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate"))
.isEqualTo(Arrays.asList("Bearer realm=\"test\""));
}
@Test
public void handleWhenOAuth2AuthenticatedThenStatus403AndAuthHeaderWithInsufficientScopeErrorAttribute() {
Authentication token = new TestingOAuth2TokenAuthenticationToken(Collections.emptyMap());
ServerWebExchange exchange = mock(ServerWebExchange.class);
given(exchange.getPrincipal()).willReturn(Mono.just(token));
given(exchange.getResponse()).willReturn(new MockServerHttpResponse());
this.accessDeniedHandler.handle(exchange, null).block();
assertThat(exchange.getResponse().getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
// @formatter:off
assertThat(exchange.getResponse().getHeaders().get("WWW-Authenticate"))
.isEqualTo(Arrays.asList("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\""));
// @formatter:on
}
@Test
public void setRealmNameWhenNullRealmNameThenNoExceptionThrown() {
this.accessDeniedHandler.setRealmName(null);
}
static class TestingOAuth2TokenAuthenticationToken
extends AbstractOAuth2TokenAuthenticationToken<TestingOAuth2TokenAuthenticationToken.TestingOAuth2Token> {
private Map<String, Object> attributes;
protected TestingOAuth2TokenAuthenticationToken(Map<String, Object> attributes) {
super(new TestingOAuth2TokenAuthenticationToken.TestingOAuth2Token("token"));
this.attributes = attributes;
}
@Override
public Map<String, Object> getTokenAttributes() {
return this.attributes;
}
static class TestingOAuth2Token extends AbstractOAuth2Token {
TestingOAuth2Token(String tokenValue) {
super(tokenValue);
}
}
}
}
| 4,777 | 39.151261 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/authentication/BearerTokenAuthenticationFilterTests.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.server.resource.web.authentication;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
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.authentication.AuthenticationManagerResolver;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
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.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests {@link BearerTokenAuthenticationFilterTests}
*
* @author Josh Cummings
*/
@ExtendWith(MockitoExtension.class)
public class BearerTokenAuthenticationFilterTests {
@Mock
AuthenticationEntryPoint authenticationEntryPoint;
@Mock
AuthenticationFailureHandler authenticationFailureHandler;
@Mock
AuthenticationManager authenticationManager;
@Mock
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver;
@Mock
BearerTokenResolver bearerTokenResolver;
@Mock
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain filterChain;
@BeforeEach
public void httpMocks() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.filterChain = new MockFilterChain();
}
@Test
public void doFilterWhenBearerTokenPresentThenAuthenticates() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
}
@Test
public void doFilterWhenSecurityContextRepositoryThenSaves() throws ServletException, IOException {
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
String token = "token";
given(this.bearerTokenResolver.resolve(this.request)).willReturn(token);
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("test", "password");
given(this.authenticationManager.authenticate(any())).willReturn(expectedAuthentication);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setSecurityContextRepository(securityContextRepository);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo(token);
ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class);
verify(securityContextRepository).saveContext(contextArg.capture(), eq(this.request), eq(this.response));
assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo(expectedAuthentication.getName());
}
@Test
public void doFilterWhenUsingAuthenticationManagerResolverThenAuthenticates() throws Exception {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManagerResolver));
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
}
@Test
public void doFilterWhenNoBearerTokenPresentThenDoesNotAuthenticate() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn(null);
dontAuthenticate();
}
@Test
public void doFilterWhenMalformedBearerTokenThenPropagatesError() throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willThrow(exception);
dontAuthenticate();
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationFailsWithDefaultHandlerThenPropagatesError()
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationFailsWithCustomHandlerThenPropagatesError()
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationFailureHandler).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationServiceExceptionThenRethrows() {
AuthenticationServiceException exception = new AuthenticationServiceException("message");
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any())).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
assertThatExceptionOfType(AuthenticationServiceException.class)
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.filterChain));
}
@Test
public void doFilterWhenCustomEntryPointAndAuthenticationErrorThenUses() throws ServletException, IOException {
AuthenticationException exception = new InvalidBearerTokenException("message");
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any())).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
AuthenticationEntryPoint entrypoint = mock(AuthenticationEntryPoint.class);
filter.setAuthenticationEntryPoint(entrypoint);
filter.doFilter(this.request, this.response, this.filterChain);
verify(entrypoint).commence(any(), any(), any(InvalidBearerTokenException.class));
}
@Test
public void doFilterWhenCustomAuthenticationDetailsSourceThenUses() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationDetailsSource).buildDetails(this.request);
}
@Test
public void doFilterWhenCustomSecurityContextHolderStrategyThenUses() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
filter.setSecurityContextHolderStrategy(strategy);
filter.doFilter(this.request, this.response, this.filterChain);
verify(strategy).setContext(any());
}
@Test
public void setAuthenticationEntryPointWhenNullThenThrowsException() {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setAuthenticationEntryPoint(null))
.withMessageContaining("authenticationEntryPoint cannot be null");
// @formatter:on
}
@Test
public void setBearerTokenResolverWhenNullThenThrowsException() {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setBearerTokenResolver(null))
.withMessageContaining("bearerTokenResolver cannot be null");
// @formatter:on
}
@Test
public void setAuthenticationConverterWhenNullThenThrowsException() {
// @formatter:off
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setAuthenticationDetailsSource(null))
.withMessageContaining("authenticationDetailsSource cannot be null");
// @formatter:on
}
@Test
public void constructorWhenNullAuthenticationManagerThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationFilter((AuthenticationManager) null))
.withMessageContaining("authenticationManager cannot be null");
// @formatter:on
}
@Test
public void constructorWhenNullAuthenticationManagerResolverThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationFilter((AuthenticationManagerResolver<HttpServletRequest>) null))
.withMessageContaining("authenticationManagerResolver cannot be null");
// @formatter:on
}
private BearerTokenAuthenticationFilter addMocks(BearerTokenAuthenticationFilter filter) {
filter.setAuthenticationEntryPoint(this.authenticationEntryPoint);
filter.setBearerTokenResolver(this.bearerTokenResolver);
filter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
return filter;
}
private void dontAuthenticate() throws ServletException, IOException {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verifyNoMoreInteractions(this.authenticationManager);
}
}
| 14,638 | 46.996721 | 116 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPointTests.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.server.resource.web.server;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.http.server.reactive.MockServerHttpResponse;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 5.1
*/
public class BearerTokenServerAuthenticationEntryPointTests {
private BearerTokenServerAuthenticationEntryPoint entryPoint = new BearerTokenServerAuthenticationEntryPoint();
private MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
@Test
public void commenceWhenNotOAuth2AuthenticationExceptionThenBearer() {
this.entryPoint.commence(this.exchange, new BadCredentialsException("")).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo("Bearer");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void commenceWhenRealmNameThenHasRealmName() {
this.entryPoint.setRealmName("Realm");
this.entryPoint.commence(this.exchange, new BadCredentialsException("")).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE))
.isEqualTo("Bearer realm=\"Realm\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void commenceWhenOAuth2AuthenticationExceptionThenContainsErrorInformation() {
OAuth2Error oauthError = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE))
.isEqualTo("Bearer error=\"invalid_request\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void commenceWhenOAuth2ErrorCompleteThenContainsErrorInformation() {
OAuth2Error oauthError = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST, "Oops", "https://example.com");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo(
"Bearer error=\"invalid_request\", error_description=\"Oops\", error_uri=\"https://example.com\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
}
@Test
public void commenceWhenBearerTokenThenErrorInformation() {
OAuth2Error oauthError = new BearerTokenError(OAuth2ErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, "Oops",
"https://example.com");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(oauthError);
this.entryPoint.commence(this.exchange, exception).block();
assertThat(getResponse().getHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE)).isEqualTo(
"Bearer error=\"invalid_request\", error_description=\"Oops\", error_uri=\"https://example.com\"");
assertThat(getResponse().getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
public void commenceWhenNoSubscriberThenNothingHappens() {
this.entryPoint.commence(this.exchange, new BadCredentialsException(""));
assertThat(getResponse().getHeaders()).isEmpty();
assertThat(getResponse().getStatusCode()).isNull();
}
private MockServerHttpResponse getResponse() {
return this.exchange.getResponse();
}
}
| 4,675 | 44.398058 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/server/authentication/ServerBearerTokenAuthenticationConverterTests.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.server.resource.web.server.authentication;
import java.util.Base64;
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.mock.http.server.reactive.MockServerHttpRequest;
import org.springframework.mock.web.server.MockServerWebExchange;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.resource.BearerTokenError;
import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
* @since 5.1
*/
public class ServerBearerTokenAuthenticationConverterTests {
private static final String CUSTOM_HEADER = "custom-header";
private static final String TEST_TOKEN = "test-token";
private ServerBearerTokenAuthenticationConverter converter;
@BeforeEach
public void setup() {
this.converter = new ServerBearerTokenAuthenticationConverter();
}
@Test
public void resolveWhenValidHeaderIsPresentThenTokenIsResolved() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_TOKEN);
// @formatter:on
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
// gh-8502
@Test
public void resolveWhenHeaderEndsWithPaddingIndicatorThenTokenIsResolved() {
String token = TEST_TOKEN + "==";
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token);
// @formatter:on
assertThat(convertToToken(request).getToken()).isEqualTo(token);
}
@Test
public void resolveWhenCustomDefinedHeaderIsValidAndPresentThenTokenIsResolved() {
this.converter.setBearerTokenHeaderName(CUSTOM_HEADER);
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(CUSTOM_HEADER, "Bearer " + TEST_TOKEN);
// @formatter:on
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
// gh-7011
@Test
public void resolveWhenValidHeaderIsEmptyStringThenTokenIsResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").header(HttpHeaders.AUTHORIZATION,
"Bearer ");
// @formatter:off
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> convertToToken(request))
.satisfies((ex) -> {
BearerTokenError error = (BearerTokenError) ex.getError();
assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED);
});
// @formatter:on
}
@Test
public void resolveWhenLowercaseHeaderIsPresentThenTokenIsResolved() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "bearer " + TEST_TOKEN);
// @formatter:on
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
@Test
public void resolveWhenNoHeaderIsPresentThenTokenIsNotResolved() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/");
assertThat(convertToToken(request)).isNull();
}
@Test
public void resolveWhenHeaderWithWrongSchemeIsPresentThenTokenIsNotResolved() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64.getEncoder().encodeToString("test:test".getBytes()));
// @formatter:on
assertThat(convertToToken(request)).isNull();
}
@Test
public void resolveWhenHeaderWithMissingTokenIsPresentThenAuthenticationExceptionIsThrown() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer ");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> convertToToken(request))
.withMessageContaining(("Bearer token is malformed"));
// @formatter:on
}
@Test
public void resolveWhenHeaderWithInvalidCharactersIsPresentThenAuthenticationExceptionIsThrown() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer an\"invalid\"token");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> convertToToken(request))
.withMessageContaining(("Bearer token is malformed"));
// @formatter:on
}
// gh-8865
@Test
public void resolveWhenHeaderWithInvalidCharactersIsPresentAndNotSubscribedThenNoneExceptionIsThrown() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.header(HttpHeaders.AUTHORIZATION, "Bearer an\"invalid\"token");
// @formatter:on
this.converter.convert(MockServerWebExchange.from(request));
}
@Test
public void resolveWhenValidHeaderIsPresentTogetherWithQueryParameterThenAuthenticationExceptionIsThrown() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.queryParam("access_token", TEST_TOKEN)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + TEST_TOKEN);
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> convertToToken(request))
.withMessageContaining("Found multiple bearer tokens in the request");
// @formatter:on
}
@Test
public void resolveWhenQueryParameterIsPresentAndSupportedThenTokenIsResolved() {
this.converter.setAllowUriQueryParameter(true);
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.queryParam("access_token", TEST_TOKEN);
// @formatter:on
assertThat(convertToToken(request).getToken()).isEqualTo(TEST_TOKEN);
}
// gh-7011
@Test
public void resolveWhenQueryParameterIsEmptyAndSupportedThenOAuth2AuthenticationException() {
this.converter.setAllowUriQueryParameter(true);
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.queryParam("access_token", "");
assertThatExceptionOfType(OAuth2AuthenticationException.class)
.isThrownBy(() -> convertToToken(request))
.satisfies((ex) -> {
BearerTokenError error = (BearerTokenError) ex.getError();
assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.UNAUTHORIZED);
});
// @formatter:on
}
@Test
public void resolveWhenQueryParameterIsPresentAndNotSupportedThenTokenIsNotResolved() {
// @formatter:off
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/")
.queryParam("access_token", TEST_TOKEN);
// @formatter:on
assertThat(convertToToken(request)).isNull();
}
@Test
void resolveWhenQueryParameterHasMultipleAccessTokensThenOAuth2AuthenticationException() {
MockServerHttpRequest.BaseBuilder<?> request = MockServerHttpRequest.get("/").queryParam("access_token",
TEST_TOKEN, TEST_TOKEN);
assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> convertToToken(request))
.satisfies((ex) -> {
BearerTokenError error = (BearerTokenError) ex.getError();
assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_REQUEST);
assertThat(error.getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST);
});
}
private BearerTokenAuthenticationToken convertToToken(MockServerHttpRequest.BaseBuilder<?> request) {
return convertToToken(request.build());
}
private BearerTokenAuthenticationToken convertToToken(MockServerHttpRequest request) {
MockServerWebExchange exchange = MockServerWebExchange.from(request);
// @formatter:off
return this.converter.convert(exchange)
.cast(BearerTokenAuthenticationToken.class)
.block();
// @formatter:on
}
}
| 9,148 | 38.098291 | 113 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/SpringReactiveOpaqueTokenIntrospectorTests.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.server.resource.introspection;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
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.Test;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.web.reactive.function.client.ClientResponse;
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.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* Tests for {@link SpringReactiveOpaqueTokenIntrospector}
*/
public class SpringReactiveOpaqueTokenIntrospectorTests {
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private static final String INTROSPECTION_URL = "https://server.example.com";
private static final String CLIENT_ID = "client";
private static final String CLIENT_SECRET = "secret";
// @formatter:off
private static final String ACTIVE_RESPONSE = "{\n"
+ " \"active\": true,\n"
+ " \"client_id\": \"l238j323ds-23ij4\",\n"
+ " \"username\": \"jdoe\",\n"
+ " \"scope\": \"read write dolphin\",\n"
+ " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n"
+ " \"aud\": \"https://protected.example.net/resource\",\n"
+ " \"iss\": \"https://server.example.com/\",\n"
+ " \"exp\": 1419356238,\n"
+ " \"iat\": 1419350238,\n"
+ " \"extension_field\": \"twenty-seven\"\n"
+ " }";
// @formatter:on
// @formatter:off
private static final String INACTIVE_RESPONSE = "{\n"
+ " \"active\": false\n"
+ " }";
// @formatter:on
// @formatter:off
private static final String INVALID_RESPONSE = "{\n"
+ " \"client_id\": \"l238j323ds-23ij4\",\n"
+ " \"username\": \"jdoe\",\n"
+ " \"scope\": \"read write dolphin\",\n"
+ " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n"
+ " \"aud\": \"https://protected.example.net/resource\",\n"
+ " \"iss\": \"https://server.example.com/\",\n"
+ " \"exp\": 1419356238,\n"
+ " \"iat\": 1419350238,\n"
+ " \"extension_field\": \"twenty-seven\"\n"
+ " }";
// @formatter:on
private final ObjectMapper mapper = new ObjectMapper();
@Test
public void authenticateWhenActiveTokenThenOk() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, CLIENT_SECRET);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
assertThat(authority).isNotNull();
// @formatter:off
assertThat(authority.getAttributes())
.isNotNull()
.containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2TokenIntrospectionClaimNames.AUD,
Arrays.asList("https://protected.example.net/resource"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4")
.containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238))
.containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, "https://server.example.com/")
.containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis")
.containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe")
.containsEntry("extension_field", "twenty-seven");
// @formatter:on
}
}
@Test
public void authenticateWhenBadClientCredentialsThenAuthenticationException() throws IOException {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, "wrong");
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
}
}
@Test
public void authenticateWhenInactiveTokenThenInvalidToken() {
WebClient webClient = mockResponse(INACTIVE_RESPONSE);
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatExceptionOfType(BadOpaqueTokenException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block())
.withMessage("Provided token isn't active");
}
@Test
public void authenticateWhenActiveTokenThenParsesValuesInResponse() {
Map<String, Object> introspectedValues = new HashMap<>();
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true);
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"));
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L);
WebClient webClient = mockResponse(introspectedValues);
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
assertThat(authority).isNotNull();
// @formatter:off
assertThat(authority.getAttributes())
.isNotNull()
.containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L))
.doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID)
.doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
// @formatter:on
}
@Test
public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() {
WebClient webClient = mockResponse(new IllegalStateException("server was unresponsive"));
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
// @formatter:off
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block())
.withMessage("server was unresponsive");
// @formatter:on
}
@Test
public void authenticateWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() {
WebClient webClient = mockResponse(INVALID_RESPONSE);
SpringReactiveOpaqueTokenIntrospector introspectionClient = new SpringReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
// @formatter:off
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
// @formatter:on
}
@Test
public void constructorWhenIntrospectionUriIsEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new SpringReactiveOpaqueTokenIntrospector("", CLIENT_ID, CLIENT_SECRET));
}
@Test
public void constructorWhenClientIdIsEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new SpringReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, "", CLIENT_SECRET));
}
@Test
public void constructorWhenClientSecretIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new SpringReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null));
}
@Test
public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new SpringReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, null));
}
private WebClient mockResponse(String response) {
return mockResponse(toMap(response));
}
private WebClient mockResponse(Map<String, Object> response) {
WebClient real = WebClient.builder().build();
WebClient.RequestBodyUriSpec spec = spy(real.post());
WebClient webClient = spy(WebClient.class);
given(webClient.post()).willReturn(spec);
ClientResponse clientResponse = mock(ClientResponse.class);
given(clientResponse.statusCode()).willReturn(HttpStatus.OK);
given(clientResponse.bodyToMono(STRING_OBJECT_MAP)).willReturn(Mono.just(response));
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.contentType()).willReturn(Optional.of(MediaType.APPLICATION_JSON));
given(clientResponse.headers()).willReturn(headers);
given(spec.exchange()).willReturn(Mono.just(clientResponse));
return webClient;
}
@SuppressWarnings("unchecked")
private Map<String, Object> toMap(String string) {
try {
return this.mapper.readValue(string, Map.class);
}
catch (Exception ex) {
throw new IllegalArgumentException(ex);
}
}
private WebClient mockResponse(Throwable ex) {
WebClient real = WebClient.builder().build();
WebClient.RequestBodyUriSpec spec = spy(real.post());
WebClient webClient = spy(WebClient.class);
given(webClient.post()).willReturn(spec);
given(spec.exchange()).willThrow(ex);
return webClient;
}
private static Dispatcher requiresAuth(String username, String password, String response) {
return new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// @formatter:off
return Optional.ofNullable(authorization)
.filter((a) -> isAuthorized(authorization, username, password))
.map((a) -> ok(response))
.orElse(unauthorized());
// @formatter:on
}
};
}
private static boolean isAuthorized(String authorization, String username, String password) {
String[] values = new String(Base64.getDecoder().decode(authorization.substring(6))).split(":");
return username.equals(values[0]) && password.equals(values[1]);
}
private static MockResponse ok(String response) {
// @formatter:off
return new MockResponse().setBody(response)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
private static MockResponse unauthorized() {
return new MockResponse().setResponseCode(401);
}
}
| 11,899 | 40.034483 | 145 | java |
null | spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospectorTests.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.server.resource.introspection;
import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import net.minidev.json.JSONObject;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.web.reactive.function.client.ClientResponse;
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.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
/**
* Tests for {@link NimbusReactiveOpaqueTokenIntrospector}
*/
public class NimbusReactiveOpaqueTokenIntrospectorTests {
private static final String INTROSPECTION_URL = "https://server.example.com";
private static final String CLIENT_ID = "client";
private static final String CLIENT_SECRET = "secret";
// @formatter:off
private static final String ACTIVE_RESPONSE = "{\n"
+ " \"active\": true,\n"
+ " \"client_id\": \"l238j323ds-23ij4\",\n"
+ " \"username\": \"jdoe\",\n"
+ " \"scope\": \"read write dolphin\",\n"
+ " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n"
+ " \"aud\": \"https://protected.example.net/resource\",\n"
+ " \"iss\": \"https://server.example.com/\",\n"
+ " \"exp\": 1419356238,\n"
+ " \"iat\": 1419350238,\n"
+ " \"extension_field\": \"twenty-seven\"\n"
+ " }";
// @formatter:on
// @formatter:off
private static final String INACTIVE_RESPONSE = "{\n"
+ " \"active\": false\n"
+ " }";
// @formatter:on
// @formatter:off
private static final String INVALID_RESPONSE = "{\n"
+ " \"client_id\": \"l238j323ds-23ij4\",\n"
+ " \"username\": \"jdoe\",\n"
+ " \"scope\": \"read write dolphin\",\n"
+ " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n"
+ " \"aud\": \"https://protected.example.net/resource\",\n"
+ " \"iss\": \"https://server.example.com/\",\n"
+ " \"exp\": 1419356238,\n"
+ " \"iat\": 1419350238,\n"
+ " \"extension_field\": \"twenty-seven\"\n"
+ " }";
// @formatter:on
// @formatter:off
private static final String MALFORMED_ISSUER_RESPONSE = "{\n"
+ " \"active\" : \"true\",\n"
+ " \"iss\" : \"badissuer\"\n"
+ " }";
// @formatter:on
@Test
public void authenticateWhenActiveTokenThenOk() throws Exception {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, CLIENT_SECRET);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
// @formatter:off
assertThat(authority.getAttributes())
.isNotNull()
.containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2TokenIntrospectionClaimNames.AUD,
Arrays.asList("https://protected.example.net/resource"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4")
.containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238))
.containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, "https://server.example.com/")
.containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis")
.containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe")
.containsEntry("extension_field", "twenty-seven");
// @formatter:on
}
}
@Test
public void authenticateWhenBadClientCredentialsThenAuthenticationException() throws IOException {
try (MockWebServer server = new MockWebServer()) {
server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE));
String introspectUri = server.url("/introspect").toString();
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
introspectUri, CLIENT_ID, "wrong");
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
}
}
@Test
public void authenticateWhenInactiveTokenThenInvalidToken() {
WebClient webClient = mockResponse(INACTIVE_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatExceptionOfType(BadOpaqueTokenException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block())
.withMessage("Provided token isn't active");
}
@Test
public void authenticateWhenActiveTokenThenParsesValuesInResponse() {
Map<String, Object> introspectedValues = new HashMap<>();
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true);
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"));
introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L);
WebClient webClient = mockResponse(new JSONObject(introspectedValues).toJSONString());
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token").block();
// @formatter:off
assertThat(authority.getAttributes())
.isNotNull()
.containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true)
.containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud"))
.containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L))
.doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID)
.doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE);
// @formatter:on
}
@Test
public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() {
WebClient webClient = mockResponse(new IllegalStateException("server was unresponsive"));
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
// @formatter:off
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block())
.withMessage("server was unresponsive");
// @formatter:on
}
@Test
public void authenticateWhenIntrospectionEndpointReturnsMalformedResponseThenInvalidToken() {
WebClient webClient = mockResponse("malformed");
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
}
@Test
public void authenticateWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() {
WebClient webClient = mockResponse(INVALID_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
// @formatter:off
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
// @formatter:on
}
@Test
public void authenticateWhenIntrospectionTokenReturnsMalformedIssuerResponseThenInvalidToken() {
WebClient webClient = mockResponse(MALFORMED_ISSUER_RESPONSE);
NimbusReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, webClient);
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("token").block());
}
@Test
public void constructorWhenIntrospectionUriIsEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector("", CLIENT_ID, CLIENT_SECRET));
}
@Test
public void constructorWhenClientIdIsEmptyThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, "", CLIENT_SECRET));
}
@Test
public void constructorWhenClientSecretIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null));
}
@Test
public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() {
assertThatIllegalArgumentException()
.isThrownBy(() -> new NimbusReactiveOpaqueTokenIntrospector(INTROSPECTION_URL, null));
}
@Test
public void handleMissingContentType() {
WebClient client = mockResponse(ACTIVE_RESPONSE, null);
ReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, client);
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("sometokenhere").block());
}
@ParameterizedTest(name = "{displayName} when Content-Type={0}")
@ValueSource(strings = { MediaType.APPLICATION_CBOR_VALUE, MediaType.TEXT_MARKDOWN_VALUE,
MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE })
public void handleNonJsonContentType(String type) {
WebClient client = mockResponse(ACTIVE_RESPONSE, type);
ReactiveOpaqueTokenIntrospector introspectionClient = new NimbusReactiveOpaqueTokenIntrospector(
INTROSPECTION_URL, client);
assertThatExceptionOfType(OAuth2IntrospectionException.class)
.isThrownBy(() -> introspectionClient.introspect("sometokenhere").block());
}
private WebClient mockResponse(String response) {
return mockResponse(response, MediaType.APPLICATION_JSON_VALUE);
}
private WebClient mockResponse(String response, String mediaType) {
WebClient real = WebClient.builder().build();
WebClient.RequestBodyUriSpec spec = spy(real.post());
WebClient webClient = spy(WebClient.class);
given(webClient.post()).willReturn(spec);
ClientResponse clientResponse = mock(ClientResponse.class);
given(clientResponse.statusCode()).willReturn(HttpStatus.OK);
given(clientResponse.bodyToMono(String.class)).willReturn(Mono.just(response));
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.contentType()).willReturn(Optional.ofNullable(mediaType).map(MediaType::parseMediaType));
given(clientResponse.headers()).willReturn(headers);
given(spec.exchange()).willReturn(Mono.just(clientResponse));
return webClient;
}
private WebClient mockResponse(Throwable ex) {
WebClient real = WebClient.builder().build();
WebClient.RequestBodyUriSpec spec = spy(real.post());
WebClient webClient = spy(WebClient.class);
given(webClient.post()).willReturn(spec);
given(spec.exchange()).willThrow(ex);
return webClient;
}
private static Dispatcher requiresAuth(String username, String password, String response) {
return new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// @formatter:off
return Optional.ofNullable(authorization)
.filter((a) -> isAuthorized(authorization, username, password))
.map((a) -> ok(response))
.orElse(unauthorized());
// @formatter:on
}
};
}
private static boolean isAuthorized(String authorization, String username, String password) {
String[] values = new String(Base64.getDecoder().decode(authorization.substring(6))).split(":");
return username.equals(values[0]) && password.equals(values[1]);
}
private static MockResponse ok(String response) {
// @formatter:off
return new MockResponse().setBody(response)
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
// @formatter:on
}
private static MockResponse unauthorized() {
return new MockResponse().setResponseCode(401);
}
}
| 13,590 | 41.077399 | 105 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.