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/userinfo/DefaultReactiveOAuth2UserService.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.userinfo;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse;
import net.minidev.json.JSONObject;
import reactor.core.publisher.Mono;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.UnsupportedMediaTypeException;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
/**
* An implementation of an {@link ReactiveOAuth2UserService} that supports standard OAuth
* 2.0 Provider's.
* <p>
* For standard OAuth 2.0 Provider's, the attribute name used to access the user's name
* from the UserInfo response is required and therefore must be available via
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint#getUserNameAttributeName()
* UserInfoEndpoint.getUserNameAttributeName()}.
* <p>
* <b>NOTE:</b> Attribute names are <b>not</b> standardized between providers and
* therefore will vary. Please consult the provider's API documentation for the set of
* supported user attribute names.
*
* @author Rob Winch
* @since 5.1
* @see ReactiveOAuth2UserService
* @see OAuth2UserRequest
* @see OAuth2User
* @see DefaultOAuth2User
*/
public class DefaultReactiveOAuth2UserService implements ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> {
private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri";
private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute";
private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
};
private static final ParameterizedTypeReference<Map<String, String>> STRING_STRING_MAP = new ParameterizedTypeReference<Map<String, String>>() {
};
private WebClient webClient = WebClient.create();
@Override
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
return Mono.defer(() -> {
Assert.notNull(userRequest, "userRequest cannot be null");
String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
.getUri();
if (!StringUtils.hasText(userInfoUri)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
"Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails()
.getUserInfoEndpoint().getUserNameAttributeName();
if (!StringUtils.hasText(userNameAttributeName)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
"Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails()
.getUserInfoEndpoint().getAuthenticationMethod();
WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri,
authenticationMethod);
// @formatter:off
Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve()
.onStatus(HttpStatusCode::isError, (response) ->
parse(response)
.map((userInfoErrorResponse) -> {
String description = userInfoErrorResponse.getErrorObject().getDescription();
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description,
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
})
)
.bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
return userAttributes.map((attrs) -> {
GrantedAuthority authority = new OAuth2UserAuthority(attrs);
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(authority);
OAuth2AccessToken token = userRequest.getAccessToken();
for (String scope : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}
return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
})
.onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException ||
ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
String contentType = (ex instanceof UnsupportedMediaTypeException) ?
((UnsupportedMediaTypeException) ex).getContentType().toString() :
((UnsupportedMediaTypeException) ex.getCause()).getContentType().toString();
String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '"
+ userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
.getUri()
+ "': response contains invalid content type '" + contentType + "'. "
+ "The UserInfo Response should return a JSON object (content type 'application/json') "
+ "that contains a collection of name and value pairs of the claims about the authenticated End-User. "
+ "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '"
+ userRequest.getClientRegistration().getRegistrationId()
+ "' conforms to the UserInfo Endpoint, "
+ "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage,
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
})
.onErrorMap((ex) -> {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
"An error occurred reading the UserInfo response: " + ex.getMessage(), null);
return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
});
});
// @formatter:on
}
private WebClient.RequestHeadersSpec<?> getRequestHeaderSpec(OAuth2UserRequest userRequest, String userInfoUri,
AuthenticationMethod authenticationMethod) {
if (AuthenticationMethod.FORM.equals(authenticationMethod)) {
// @formatter:off
return this.webClient.post()
.uri(userInfoUri)
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.bodyValue("access_token=" + userRequest.getAccessToken().getTokenValue());
// @formatter:on
}
// @formatter:off
return this.webClient.get()
.uri(userInfoUri)
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.headers((headers) -> headers
.setBearerAuth(userRequest.getAccessToken().getTokenValue())
);
// @formatter:on
}
/**
* Sets the {@link WebClient} used for retrieving the user endpoint
* @param webClient the client to use
*/
public void setWebClient(WebClient webClient) {
Assert.notNull(webClient, "webClient cannot be null");
this.webClient = webClient;
}
private static Mono<UserInfoErrorResponse> parse(ClientResponse httpResponse) {
String wwwAuth = httpResponse.headers().asHttpHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE);
if (StringUtils.hasLength(wwwAuth)) {
// Bearer token error?
return Mono.fromCallable(() -> UserInfoErrorResponse.parse(wwwAuth));
}
// Other error?
return httpResponse.bodyToMono(STRING_STRING_MAP)
.map((body) -> new UserInfoErrorResponse(ErrorObject.parse(new JSONObject(body))));
}
}
| 9,514 | 46.10396 | 145 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/OAuth2UserService.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.userinfo;
import org.springframework.security.core.AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
/**
* Implementations of this interface are responsible for obtaining the user attributes of
* the End-User (Resource Owner) from the UserInfo Endpoint using the
* {@link OAuth2UserRequest#getAccessToken() Access Token} granted to the
* {@link OAuth2UserRequest#getClientRegistration() Client} and returning an
* {@link AuthenticatedPrincipal} in the form of an {@link OAuth2User}.
*
* @param <R> The type of OAuth 2.0 User Request
* @param <U> The type of OAuth 2.0 User
* @author Joe Grandja
* @since 5.0
* @see OAuth2UserRequest
* @see OAuth2User
* @see AuthenticatedPrincipal
*/
@FunctionalInterface
public interface OAuth2UserService<R extends OAuth2UserRequest, U extends OAuth2User> {
/**
* Returns an {@link OAuth2User} after obtaining the user attributes of the End-User
* from the UserInfo Endpoint.
* @param userRequest the user request
* @return an {@link OAuth2User}
* @throws OAuth2AuthenticationException if an error occurs while attempting to obtain
* the user attributes from the UserInfo Endpoint
*/
U loadUser(R userRequest) throws OAuth2AuthenticationException;
}
| 2,011 | 37.692308 | 89 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/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.
*/
/**
* Classes and interfaces that provide support for
* {@link org.springframework.security.oauth2.client.registration.ClientRegistration}.
*/
package org.springframework.security.oauth2.client.registration;
| 834 | 36.954545 | 86 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistration.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogMessage;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A representation of a client registration with an OAuth 2.0 or OpenID Connect 1.0
* Provider.
*
* @author Joe Grandja
* @author Michael Sosa
* @since 5.0
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-2">Section 2
* Client Registration</a>
*/
public final class ClientRegistration implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String registrationId;
private String clientId;
private String clientSecret;
private ClientAuthenticationMethod clientAuthenticationMethod;
private AuthorizationGrantType authorizationGrantType;
private String redirectUri;
private Set<String> scopes = Collections.emptySet();
private ProviderDetails providerDetails = new ProviderDetails();
private String clientName;
private ClientRegistration() {
}
/**
* Returns the identifier for the registration.
* @return the identifier for the registration
*/
public String getRegistrationId() {
return this.registrationId;
}
/**
* Returns the client identifier.
* @return the client identifier
*/
public String getClientId() {
return this.clientId;
}
/**
* Returns the client secret.
* @return the client secret
*/
public String getClientSecret() {
return this.clientSecret;
}
/**
* Returns the {@link ClientAuthenticationMethod authentication method} used when
* authenticating the client with the authorization server.
* @return the {@link ClientAuthenticationMethod}
*/
public ClientAuthenticationMethod getClientAuthenticationMethod() {
return this.clientAuthenticationMethod;
}
/**
* Returns the {@link AuthorizationGrantType authorization grant type} used for the
* client.
* @return the {@link AuthorizationGrantType}
*/
public AuthorizationGrantType getAuthorizationGrantType() {
return this.authorizationGrantType;
}
/**
* Returns the uri (or uri template) for the redirection endpoint.
*
* <br />
* The supported uri template variables are: {baseScheme}, {baseHost}, {basePort},
* {basePath} and {registrationId}.
*
* <br />
* <b>NOTE:</b> {baseUrl} is also supported, which is the same as
* {baseScheme}://{baseHost}{basePort}{basePath}.
*
* <br />
* Configuring uri template variables is especially useful when the client is running
* behind a Proxy Server. This ensures that the X-Forwarded-* headers are used when
* expanding the redirect-uri.
* @return the uri (or uri template) for the redirection endpoint
* @since 5.4
*/
public String getRedirectUri() {
return this.redirectUri;
}
/**
* Returns the scope(s) used for the client.
* @return the {@code Set} of scope(s)
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the details of the provider.
* @return the {@link ProviderDetails}
*/
public ProviderDetails getProviderDetails() {
return this.providerDetails;
}
/**
* Returns the logical name of the client or registration.
* @return the client or registration name
*/
public String getClientName() {
return this.clientName;
}
@Override
public String toString() {
// @formatter:off
return "ClientRegistration{"
+ "registrationId='" + this.registrationId + '\''
+ ", clientId='" + this.clientId + '\''
+ ", clientSecret='" + this.clientSecret + '\''
+ ", clientAuthenticationMethod=" + this.clientAuthenticationMethod
+ ", authorizationGrantType=" + this.authorizationGrantType
+ ", redirectUri='" + this.redirectUri
+ '\'' + ", scopes=" + this.scopes
+ ", providerDetails=" + this.providerDetails
+ ", clientName='" + this.clientName + '\''
+ '}';
// @formatter:on
}
/**
* Returns a new {@link Builder}, initialized with the provided registration
* identifier.
* @param registrationId the identifier for the registration
* @return the {@link Builder}
*/
public static Builder withRegistrationId(String registrationId) {
Assert.hasText(registrationId, "registrationId cannot be empty");
return new Builder(registrationId);
}
/**
* Returns a new {@link Builder}, initialized with the provided
* {@link ClientRegistration}.
* @param clientRegistration the {@link ClientRegistration} to copy from
* @return the {@link Builder}
*/
public static Builder withClientRegistration(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
return new Builder(clientRegistration);
}
/**
* Details of the Provider.
*/
public class ProviderDetails implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String authorizationUri;
private String tokenUri;
private UserInfoEndpoint userInfoEndpoint = new UserInfoEndpoint();
private String jwkSetUri;
private String issuerUri;
private Map<String, Object> configurationMetadata = Collections.emptyMap();
ProviderDetails() {
}
/**
* Returns the uri for the authorization endpoint.
* @return the uri for the authorization endpoint
*/
public String getAuthorizationUri() {
return this.authorizationUri;
}
/**
* Returns the uri for the token endpoint.
* @return the uri for the token endpoint
*/
public String getTokenUri() {
return this.tokenUri;
}
/**
* Returns the details of the {@link UserInfoEndpoint UserInfo Endpoint}.
* @return the {@link UserInfoEndpoint}
*/
public UserInfoEndpoint getUserInfoEndpoint() {
return this.userInfoEndpoint;
}
/**
* Returns the uri for the JSON Web Key (JWK) Set endpoint.
* @return the uri for the JSON Web Key (JWK) Set endpoint
*/
public String getJwkSetUri() {
return this.jwkSetUri;
}
/**
* Returns the issuer identifier uri for the OpenID Connect 1.0 provider or the
* OAuth 2.0 Authorization Server.
* @return the issuer identifier uri for the OpenID Connect 1.0 provider or the
* OAuth 2.0 Authorization Server
* @since 5.4
*/
public String getIssuerUri() {
return this.issuerUri;
}
/**
* Returns a {@code Map} of the metadata describing the provider's configuration.
* @return a {@code Map} of the metadata describing the provider's configuration
* @since 5.1
*/
public Map<String, Object> getConfigurationMetadata() {
return this.configurationMetadata;
}
/**
* Details of the UserInfo Endpoint.
*/
public class UserInfoEndpoint implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private String uri;
private AuthenticationMethod authenticationMethod = AuthenticationMethod.HEADER;
private String userNameAttributeName;
UserInfoEndpoint() {
}
/**
* Returns the uri for the user info endpoint.
* @return the uri for the user info endpoint
*/
public String getUri() {
return this.uri;
}
/**
* Returns the authentication method for the user info endpoint.
* @return the {@link AuthenticationMethod} for the user info endpoint.
* @since 5.1
*/
public AuthenticationMethod getAuthenticationMethod() {
return this.authenticationMethod;
}
/**
* Returns the attribute name used to access the user's name from the user
* info response.
* @return the attribute name used to access the user's name from the user
* info response
*/
public String getUserNameAttributeName() {
return this.userNameAttributeName;
}
}
}
/**
* A builder for {@link ClientRegistration}.
*/
public static final class Builder implements Serializable {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private static final Log logger = LogFactory.getLog(Builder.class);
private static final List<AuthorizationGrantType> AUTHORIZATION_GRANT_TYPES = Arrays.asList(
AuthorizationGrantType.AUTHORIZATION_CODE, AuthorizationGrantType.CLIENT_CREDENTIALS,
AuthorizationGrantType.REFRESH_TOKEN, AuthorizationGrantType.PASSWORD);
private String registrationId;
private String clientId;
private String clientSecret;
private ClientAuthenticationMethod clientAuthenticationMethod;
private AuthorizationGrantType authorizationGrantType;
private String redirectUri;
private Set<String> scopes;
private String authorizationUri;
private String tokenUri;
private String userInfoUri;
private AuthenticationMethod userInfoAuthenticationMethod = AuthenticationMethod.HEADER;
private String userNameAttributeName;
private String jwkSetUri;
private String issuerUri;
private Map<String, Object> configurationMetadata = Collections.emptyMap();
private String clientName;
private Builder(String registrationId) {
this.registrationId = registrationId;
}
private Builder(ClientRegistration clientRegistration) {
this.registrationId = clientRegistration.registrationId;
this.clientId = clientRegistration.clientId;
this.clientSecret = clientRegistration.clientSecret;
this.clientAuthenticationMethod = clientRegistration.clientAuthenticationMethod;
this.authorizationGrantType = clientRegistration.authorizationGrantType;
this.redirectUri = clientRegistration.redirectUri;
this.scopes = (clientRegistration.scopes != null) ? new HashSet<>(clientRegistration.scopes) : null;
this.authorizationUri = clientRegistration.providerDetails.authorizationUri;
this.tokenUri = clientRegistration.providerDetails.tokenUri;
this.userInfoUri = clientRegistration.providerDetails.userInfoEndpoint.uri;
this.userInfoAuthenticationMethod = clientRegistration.providerDetails.userInfoEndpoint.authenticationMethod;
this.userNameAttributeName = clientRegistration.providerDetails.userInfoEndpoint.userNameAttributeName;
this.jwkSetUri = clientRegistration.providerDetails.jwkSetUri;
this.issuerUri = clientRegistration.providerDetails.issuerUri;
Map<String, Object> configurationMetadata = clientRegistration.providerDetails.configurationMetadata;
if (configurationMetadata != Collections.EMPTY_MAP) {
this.configurationMetadata = new HashMap<>(configurationMetadata);
}
this.clientName = clientRegistration.clientName;
}
/**
* Sets the registration id.
* @param registrationId the registration id
* @return the {@link Builder}
*/
public Builder registrationId(String registrationId) {
this.registrationId = registrationId;
return this;
}
/**
* Sets the client identifier.
* @param clientId the client identifier
* @return the {@link Builder}
*/
public Builder clientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* Sets the client secret.
* @param clientSecret the client secret
* @return the {@link Builder}
*/
public Builder clientSecret(String clientSecret) {
this.clientSecret = clientSecret;
return this;
}
/**
* Sets the {@link ClientAuthenticationMethod authentication method} used when
* authenticating the client with the authorization server.
* @param clientAuthenticationMethod the authentication method used for the client
* @return the {@link Builder}
*/
public Builder clientAuthenticationMethod(ClientAuthenticationMethod clientAuthenticationMethod) {
this.clientAuthenticationMethod = clientAuthenticationMethod;
return this;
}
/**
* Sets the {@link AuthorizationGrantType authorization grant type} used for the
* client.
* @param authorizationGrantType the authorization grant type used for the client
* @return the {@link Builder}
*/
public Builder authorizationGrantType(AuthorizationGrantType authorizationGrantType) {
this.authorizationGrantType = authorizationGrantType;
return this;
}
/**
* Sets the uri (or uri template) for the redirection endpoint.
*
* <br />
* The supported uri template variables are: {baseScheme}, {baseHost}, {basePort},
* {basePath} and {registrationId}.
*
* <br />
* <b>NOTE:</b> {baseUrl} is also supported, which is the same as
* {baseScheme}://{baseHost}{basePort}{basePath}.
*
* <br />
* Configuring uri template variables is especially useful when the client is
* running behind a Proxy Server. This ensures that the X-Forwarded-* headers are
* used when expanding the redirect-uri.
* @param redirectUri the uri (or uri template) for the redirection endpoint
* @return the {@link Builder}
* @since 5.4
*/
public Builder redirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
/**
* Sets the scope(s) used for the client.
* @param scope the scope(s) used for the client
* @return the {@link Builder}
*/
public Builder scope(String... scope) {
if (scope != null && scope.length > 0) {
this.scopes = Collections.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(scope)));
}
return this;
}
/**
* Sets the scope(s) used for the client.
* @param scope the scope(s) used for the client
* @return the {@link Builder}
*/
public Builder scope(Collection<String> scope) {
if (scope != null && !scope.isEmpty()) {
this.scopes = Collections.unmodifiableSet(new LinkedHashSet<>(scope));
}
return this;
}
/**
* Sets the uri for the authorization endpoint.
* @param authorizationUri the uri for the authorization endpoint
* @return the {@link Builder}
*/
public Builder authorizationUri(String authorizationUri) {
this.authorizationUri = authorizationUri;
return this;
}
/**
* Sets the uri for the token endpoint.
* @param tokenUri the uri for the token endpoint
* @return the {@link Builder}
*/
public Builder tokenUri(String tokenUri) {
this.tokenUri = tokenUri;
return this;
}
/**
* Sets the uri for the user info endpoint.
* @param userInfoUri the uri for the user info endpoint
* @return the {@link Builder}
*/
public Builder userInfoUri(String userInfoUri) {
this.userInfoUri = userInfoUri;
return this;
}
/**
* Sets the authentication method for the user info endpoint.
* @param userInfoAuthenticationMethod the authentication method for the user info
* endpoint
* @return the {@link Builder}
* @since 5.1
*/
public Builder userInfoAuthenticationMethod(AuthenticationMethod userInfoAuthenticationMethod) {
this.userInfoAuthenticationMethod = userInfoAuthenticationMethod;
return this;
}
/**
* Sets the attribute name used to access the user's name from the user info
* response.
* @param userNameAttributeName the attribute name used to access the user's name
* from the user info response
* @return the {@link Builder}
*/
public Builder userNameAttributeName(String userNameAttributeName) {
this.userNameAttributeName = userNameAttributeName;
return this;
}
/**
* Sets the uri for the JSON Web Key (JWK) Set endpoint.
* @param jwkSetUri the uri for the JSON Web Key (JWK) Set endpoint
* @return the {@link Builder}
*/
public Builder jwkSetUri(String jwkSetUri) {
this.jwkSetUri = jwkSetUri;
return this;
}
/**
* Sets the issuer identifier uri for the OpenID Connect 1.0 provider or the OAuth
* 2.0 Authorization Server.
* @param issuerUri the issuer identifier uri for the OpenID Connect 1.0 provider
* or the OAuth 2.0 Authorization Server
* @return the {@link Builder}
* @since 5.4
*/
public Builder issuerUri(String issuerUri) {
this.issuerUri = issuerUri;
return this;
}
/**
* Sets the metadata describing the provider's configuration.
* @param configurationMetadata the metadata describing the provider's
* configuration
* @return the {@link Builder}
* @since 5.1
*/
public Builder providerConfigurationMetadata(Map<String, Object> configurationMetadata) {
if (configurationMetadata != null) {
this.configurationMetadata = new LinkedHashMap<>(configurationMetadata);
}
return this;
}
/**
* Sets the logical name of the client or registration.
* @param clientName the client or registration name
* @return the {@link Builder}
*/
public Builder clientName(String clientName) {
this.clientName = clientName;
return this;
}
/**
* Builds a new {@link ClientRegistration}.
* @return a {@link ClientRegistration}
*/
public ClientRegistration build() {
Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null");
if (AuthorizationGrantType.CLIENT_CREDENTIALS.equals(this.authorizationGrantType)) {
this.validateClientCredentialsGrantType();
}
else if (AuthorizationGrantType.PASSWORD.equals(this.authorizationGrantType)) {
this.validatePasswordGrantType();
}
else if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(this.authorizationGrantType)) {
this.validateAuthorizationCodeGrantType();
}
this.validateAuthorizationGrantTypes();
this.validateScopes();
return this.create();
}
private ClientRegistration create() {
ClientRegistration clientRegistration = new ClientRegistration();
clientRegistration.registrationId = this.registrationId;
clientRegistration.clientId = this.clientId;
clientRegistration.clientSecret = StringUtils.hasText(this.clientSecret) ? this.clientSecret : "";
clientRegistration.clientAuthenticationMethod = (this.clientAuthenticationMethod != null)
? this.clientAuthenticationMethod : deduceClientAuthenticationMethod(clientRegistration);
clientRegistration.authorizationGrantType = this.authorizationGrantType;
clientRegistration.redirectUri = this.redirectUri;
clientRegistration.scopes = this.scopes;
clientRegistration.providerDetails = createProviderDetails(clientRegistration);
clientRegistration.clientName = StringUtils.hasText(this.clientName) ? this.clientName
: this.registrationId;
return clientRegistration;
}
private ClientAuthenticationMethod deduceClientAuthenticationMethod(ClientRegistration clientRegistration) {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(this.authorizationGrantType)
&& !StringUtils.hasText(this.clientSecret)) {
return ClientAuthenticationMethod.NONE;
}
return ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
}
private ProviderDetails createProviderDetails(ClientRegistration clientRegistration) {
ProviderDetails providerDetails = clientRegistration.new ProviderDetails();
providerDetails.authorizationUri = this.authorizationUri;
providerDetails.tokenUri = this.tokenUri;
providerDetails.userInfoEndpoint.uri = this.userInfoUri;
providerDetails.userInfoEndpoint.authenticationMethod = this.userInfoAuthenticationMethod;
providerDetails.userInfoEndpoint.userNameAttributeName = this.userNameAttributeName;
providerDetails.jwkSetUri = this.jwkSetUri;
providerDetails.issuerUri = this.issuerUri;
providerDetails.configurationMetadata = Collections.unmodifiableMap(this.configurationMetadata);
return providerDetails;
}
private void validateAuthorizationCodeGrantType() {
Assert.isTrue(AuthorizationGrantType.AUTHORIZATION_CODE.equals(this.authorizationGrantType),
() -> "authorizationGrantType must be " + AuthorizationGrantType.AUTHORIZATION_CODE.getValue());
Assert.hasText(this.registrationId, "registrationId cannot be empty");
Assert.hasText(this.clientId, "clientId cannot be empty");
Assert.hasText(this.redirectUri, "redirectUri cannot be empty");
Assert.hasText(this.authorizationUri, "authorizationUri cannot be empty");
Assert.hasText(this.tokenUri, "tokenUri cannot be empty");
}
private void validateClientCredentialsGrantType() {
Assert.isTrue(AuthorizationGrantType.CLIENT_CREDENTIALS.equals(this.authorizationGrantType),
() -> "authorizationGrantType must be " + AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
Assert.hasText(this.registrationId, "registrationId cannot be empty");
Assert.hasText(this.clientId, "clientId cannot be empty");
Assert.hasText(this.tokenUri, "tokenUri cannot be empty");
}
private void validatePasswordGrantType() {
Assert.isTrue(AuthorizationGrantType.PASSWORD.equals(this.authorizationGrantType),
() -> "authorizationGrantType must be " + AuthorizationGrantType.PASSWORD.getValue());
Assert.hasText(this.registrationId, "registrationId cannot be empty");
Assert.hasText(this.clientId, "clientId cannot be empty");
Assert.hasText(this.tokenUri, "tokenUri cannot be empty");
}
private void validateAuthorizationGrantTypes() {
for (AuthorizationGrantType authorizationGrantType : AUTHORIZATION_GRANT_TYPES) {
if (authorizationGrantType.getValue().equalsIgnoreCase(this.authorizationGrantType.getValue())
&& !authorizationGrantType.equals(this.authorizationGrantType)) {
logger.warn(LogMessage.format(
"AuthorizationGrantType: %s does not match the pre-defined constant %s and won't match a valid OAuth2AuthorizedClientProvider",
this.authorizationGrantType, authorizationGrantType));
}
}
}
private void validateScopes() {
if (this.scopes == null) {
return;
}
for (String scope : this.scopes) {
Assert.isTrue(validateScope(scope), "scope \"" + scope + "\" contains invalid characters");
}
}
private static boolean validateScope(String scope) {
return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x21, 0x21)
|| withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
}
private static boolean withinTheRangeOf(int c, int min, int max) {
return c >= min && c <= max;
}
}
}
| 23,126 | 31.481742 | 134 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/InMemoryReactiveClientRegistrationRepository.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import reactor.core.publisher.Mono;
import org.springframework.util.Assert;
/**
* A Reactive {@link ClientRegistrationRepository} that stores
* {@link ClientRegistration}(s) in-memory.
*
* @author Rob Winch
* @author Ebert Toribio
* @since 5.1
* @see ClientRegistrationRepository
* @see ClientRegistration
*/
public final class InMemoryReactiveClientRegistrationRepository
implements ReactiveClientRegistrationRepository, Iterable<ClientRegistration> {
private final Map<String, ClientRegistration> clientIdToClientRegistration;
/**
* Constructs an {@code InMemoryReactiveClientRegistrationRepository} using the
* provided parameters.
* @param registrations the client registration(s)
*/
public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) {
this(toList(registrations));
}
private static List<ClientRegistration> toList(ClientRegistration... registrations) {
Assert.notEmpty(registrations, "registrations cannot be null or empty");
return Arrays.asList(registrations);
}
/**
* Constructs an {@code InMemoryReactiveClientRegistrationRepository} using the
* provided parameters.
* @param registrations the client registration(s)
*/
public InMemoryReactiveClientRegistrationRepository(List<ClientRegistration> registrations) {
this.clientIdToClientRegistration = toUnmodifiableConcurrentMap(registrations);
}
@Override
public Mono<ClientRegistration> findByRegistrationId(String registrationId) {
return Mono.justOrEmpty(this.clientIdToClientRegistration.get(registrationId));
}
/**
* Returns an {@code Iterator} of {@link ClientRegistration}.
* @return an {@code Iterator<ClientRegistration>}
*/
@Override
public Iterator<ClientRegistration> iterator() {
return this.clientIdToClientRegistration.values().iterator();
}
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be null or empty");
ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>();
for (ClientRegistration registration : registrations) {
Assert.notNull(registration, "no registration can be null");
if (result.containsKey(registration.getRegistrationId())) {
throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId()));
}
result.put(registration.getRegistrationId(), registration);
}
return Collections.unmodifiableMap(result);
}
}
| 3,380 | 34.21875 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistrationRepository.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
/**
* A repository for OAuth 2.0 / OpenID Connect 1.0 {@link ClientRegistration}(s).
*
* <p>
* <b>NOTE:</b> Client registration information is ultimately stored and owned by the
* associated Authorization Server. Therefore, this repository provides the capability to
* store a sub-set copy of the <i>primary</i> client registration information externally
* from the Authorization Server.
*
* @author Joe Grandja
* @since 5.0
* @see ClientRegistration
*/
public interface ClientRegistrationRepository {
/**
* Returns the client registration identified by the provided {@code registrationId},
* or {@code null} if not found.
* @param registrationId the registration identifier
* @return the {@link ClientRegistration} if found, otherwise {@code null}
*/
ClientRegistration findByRegistrationId(String registrationId);
}
| 1,533 | 34.674419 | 89 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/SupplierClientRegistrationRepository.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import java.util.Iterator;
import java.util.function.Supplier;
import org.springframework.util.Assert;
import org.springframework.util.function.SingletonSupplier;
/**
* A {@link ClientRegistrationRepository} that lazily calls to retrieve
* {@link ClientRegistration}(s) when requested.
*
* @author Justin Tay
* @since 6.2
* @see ClientRegistrationRepository
* @see ClientRegistration
*/
public final class SupplierClientRegistrationRepository
implements ClientRegistrationRepository, Iterable<ClientRegistration> {
private final Supplier<? extends ClientRegistrationRepository> repositorySupplier;
/**
* Constructs an {@code SupplierClientRegistrationRepository} using the provided
* parameters.
* @param repositorySupplier the client registration repository supplier
*/
public <T extends ClientRegistrationRepository & Iterable<ClientRegistration>> SupplierClientRegistrationRepository(
Supplier<T> repositorySupplier) {
Assert.notNull(repositorySupplier, "repositorySupplier cannot be null");
this.repositorySupplier = SingletonSupplier.of(repositorySupplier);
}
@Override
public ClientRegistration findByRegistrationId(String registrationId) {
Assert.hasText(registrationId, "registrationId cannot be empty");
return this.repositorySupplier.get().findByRegistrationId(registrationId);
}
/**
* Returns an {@code Iterator} of {@link ClientRegistration}.
* @return an {@code Iterator<ClientRegistration>}
*/
@Override
public Iterator<ClientRegistration> iterator() {
return ((Iterable<ClientRegistration>) this.repositorySupplier.get()).iterator();
}
}
| 2,297 | 33.818182 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ReactiveClientRegistrationRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import reactor.core.publisher.Mono;
/**
* A reactive repository for OAuth 2.0 / OpenID Connect 1.0 {@link ClientRegistration}(s).
*
* <p>
* <b>NOTE:</b> Client registration information is ultimately stored and owned by the
* associated Authorization Server. Therefore, this repository provides the capability to
* store a sub-set copy of the <i>primary</i> client registration information externally
* from the Authorization Server.
*
* @author Rob Winch
* @since 5.1
* @see ClientRegistration
*/
public interface ReactiveClientRegistrationRepository {
/**
* Returns the client registration identified by the provided {@code registrationId},
* or {@code null} if not found.
* @param registrationId the registration identifier
* @return the {@link ClientRegistration} if found, otherwise {@code null}
*/
Mono<ClientRegistration> findByRegistrationId(String registrationId);
}
| 1,591 | 34.377778 | 90 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/InMemoryClientRegistrationRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.util.Assert;
/**
* A {@link ClientRegistrationRepository} that stores {@link ClientRegistration}(s)
* in-memory.
*
* @author Joe Grandja
* @author Rob Winch
* @author Vedran Pavic
* @since 5.0
* @see ClientRegistrationRepository
* @see ClientRegistration
*/
public final class InMemoryClientRegistrationRepository
implements ClientRegistrationRepository, Iterable<ClientRegistration> {
private final Map<String, ClientRegistration> registrations;
/**
* Constructs an {@code InMemoryClientRegistrationRepository} using the provided
* parameters.
* @param registrations the client registration(s)
*/
public InMemoryClientRegistrationRepository(ClientRegistration... registrations) {
this(Arrays.asList(registrations));
}
/**
* Constructs an {@code InMemoryClientRegistrationRepository} using the provided
* parameters.
* @param registrations the client registration(s)
*/
public InMemoryClientRegistrationRepository(List<ClientRegistration> registrations) {
this(createRegistrationsMap(registrations));
}
private static Map<String, ClientRegistration> createRegistrationsMap(List<ClientRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be empty");
return toUnmodifiableConcurrentMap(registrations);
}
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) {
ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>();
for (ClientRegistration registration : registrations) {
Assert.state(!result.containsKey(registration.getRegistrationId()),
() -> String.format("Duplicate key %s", registration.getRegistrationId()));
result.put(registration.getRegistrationId(), registration);
}
return Collections.unmodifiableMap(result);
}
/**
* Constructs an {@code InMemoryClientRegistrationRepository} using the provided
* {@code Map} of {@link ClientRegistration#getRegistrationId() registration id} to
* {@link ClientRegistration}.
* @param registrations the {@code Map} of client registration(s)
* @since 5.2
*/
public InMemoryClientRegistrationRepository(Map<String, ClientRegistration> registrations) {
Assert.notNull(registrations, "registrations cannot be null");
this.registrations = registrations;
}
@Override
public ClientRegistration findByRegistrationId(String registrationId) {
Assert.hasText(registrationId, "registrationId cannot be empty");
return this.registrations.get(registrationId);
}
/**
* Returns an {@code Iterator} of {@link ClientRegistration}.
* @return an {@code Iterator<ClientRegistration>}
*/
@Override
public Iterator<ClientRegistration> iterator() {
return this.registrations.values().iterator();
}
}
| 3,642 | 33.695238 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistrations.java | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.registration;
import java.net.URI;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.as.AuthorizationServerMetadata;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import net.minidev.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.RequestEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.util.Assert;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Allows creating a {@link ClientRegistration.Builder} 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">Authorization Server
* Metadata</a> based on provided issuer.
*
* @author Rob Winch
* @author Josh Cummings
* @author Rafiullah Hamedy
* @since 5.1
*/
public final class ClientRegistrations {
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();
static {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(30_000);
requestFactory.setReadTimeout(30_000);
rest.setRequestFactory(requestFactory);
}
private static final ParameterizedTypeReference<Map<String, Object>> typeReference = new ParameterizedTypeReference<Map<String, Object>>() {
};
private ClientRegistrations() {
}
/**
* Creates a {@link ClientRegistration.Builder} 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 ClientRegistration.Builder}.
*
* <p>
* For example, if the issuer provided is "https://example.com", then an "OpenID
* Provider Configuration Request" will be made to
* "https://example.com/.well-known/openid-configuration". The result is expected to
* be an "OpenID Provider Configuration Response".
* </p>
*
* <p>
* Example usage:
* </p>
* <pre>
* ClientRegistration registration = ClientRegistrations.fromOidcIssuerLocation("https://example.com")
* .clientId("client-id")
* .clientSecret("client-secret")
* .build();
* </pre>
* @param issuer the <a href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a>
* @return a {@link ClientRegistration.Builder} that was initialized by the OpenID
* Provider Configuration.
*/
public static ClientRegistration.Builder fromOidcIssuerLocation(String issuer) {
Assert.hasText(issuer, "issuer cannot be empty");
return getBuilder(issuer, oidc(URI.create(issuer)));
}
/**
* Creates a {@link ClientRegistration.Builder} 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 ClientRegistrations#fromOidcIssuerLocation(String)}.
*
* <p>
* Example usage:
* </p>
* <pre>
* ClientRegistration registration = ClientRegistrations.fromIssuerLocation("https://example.com")
* .clientId("client-id")
* .clientSecret("client-secret")
* .build();
* </pre>
* @param issuer
* @return a {@link ClientRegistration.Builder} that was initialized by one of the
* described endpoints
*/
public static ClientRegistration.Builder fromIssuerLocation(String issuer) {
Assert.hasText(issuer, "issuer cannot be empty");
URI uri = URI.create(issuer);
return getBuilder(issuer, oidc(uri), oidcRfc8414(uri), oauth(uri));
}
private static Supplier<ClientRegistration.Builder> oidc(URI issuer) {
// @formatter:off
URI uri = UriComponentsBuilder.fromUri(issuer)
.replacePath(issuer.getPath() + OIDC_METADATA_PATH)
.build(Collections.emptyMap());
// @formatter:on
return () -> {
RequestEntity<Void> request = RequestEntity.get(uri).build();
Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
OIDCProviderMetadata metadata = parse(configuration, OIDCProviderMetadata::parse);
ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer.toASCIIString())
.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
if (metadata.getUserInfoEndpointURI() != null) {
builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
}
return builder;
};
}
private static Supplier<ClientRegistration.Builder> oidcRfc8414(URI issuer) {
// @formatter:off
URI uri = UriComponentsBuilder.fromUri(issuer)
.replacePath(OIDC_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
return getRfc8414Builder(issuer, uri);
}
private static Supplier<ClientRegistration.Builder> oauth(URI issuer) {
// @formatter:off
URI uri = UriComponentsBuilder.fromUri(issuer)
.replacePath(OAUTH_METADATA_PATH + issuer.getPath())
.build(Collections.emptyMap());
// @formatter:on
return getRfc8414Builder(issuer, uri);
}
private static Supplier<ClientRegistration.Builder> getRfc8414Builder(URI issuer, URI uri) {
return () -> {
RequestEntity<Void> request = RequestEntity.get(uri).build();
Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
AuthorizationServerMetadata metadata = parse(configuration, AuthorizationServerMetadata::parse);
ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer.toASCIIString());
URI jwkSetUri = metadata.getJWKSetURI();
if (jwkSetUri != null) {
builder.jwkSetUri(jwkSetUri.toASCIIString());
}
String userinfoEndpoint = (String) configuration.get("userinfo_endpoint");
if (userinfoEndpoint != null) {
builder.userInfoUri(userinfoEndpoint);
}
return builder;
};
}
@SafeVarargs
private static ClientRegistration.Builder getBuilder(String issuer,
Supplier<ClientRegistration.Builder>... suppliers) {
String errorMessage = "Unable to resolve Configuration with the provided Issuer of \"" + issuer + "\"";
for (Supplier<ClientRegistration.Builder> supplier : suppliers) {
try {
return supplier.get();
}
catch (HttpClientErrorException ex) {
if (!ex.getStatusCode().is4xxClientError()) {
throw ex;
}
// else try another endpoint
}
catch (IllegalArgumentException | IllegalStateException ex) {
throw ex;
}
catch (RuntimeException ex) {
throw new IllegalArgumentException(errorMessage, ex);
}
}
throw new IllegalArgumentException(errorMessage);
}
private static <T> T parse(Map<String, Object> body, ThrowingFunction<JSONObject, T, ParseException> parser) {
try {
return parser.apply(new JSONObject(body));
}
catch (ParseException ex) {
throw new RuntimeException(ex);
}
}
private static ClientRegistration.Builder withProviderConfiguration(AuthorizationServerMetadata metadata,
String issuer) {
String metadataIssuer = metadata.getIssuer().getValue();
Assert.state(issuer.equals(metadataIssuer),
() -> "The Issuer \"" + metadataIssuer + "\" provided in the configuration metadata did "
+ "not match the requested issuer \"" + issuer + "\"");
String name = URI.create(issuer).getHost();
ClientAuthenticationMethod method = getClientAuthenticationMethod(metadata.getTokenEndpointAuthMethods());
Map<String, Object> configurationMetadata = new LinkedHashMap<>(metadata.toJSONObject());
// @formatter:off
return ClientRegistration.withRegistrationId(name)
.userNameAttributeName(IdTokenClaimNames.SUB)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.clientAuthenticationMethod(method)
.redirectUri("{baseUrl}/{action}/oauth2/code/{registrationId}")
.authorizationUri((metadata.getAuthorizationEndpointURI() != null) ? metadata.getAuthorizationEndpointURI().toASCIIString() : null)
.providerConfigurationMetadata(configurationMetadata)
.tokenUri(metadata.getTokenEndpointURI().toASCIIString())
.issuerUri(issuer)
.clientName(issuer);
// @formatter:on
}
private static ClientAuthenticationMethod getClientAuthenticationMethod(
List<com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod> metadataAuthMethods) {
if (metadataAuthMethods == null || metadataAuthMethods
.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_BASIC)) {
// If null, the default includes client_secret_basic
return ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
}
if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
return ClientAuthenticationMethod.CLIENT_SECRET_POST;
}
if (metadataAuthMethods.contains(com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod.NONE)) {
return ClientAuthenticationMethod.NONE;
}
return null;
}
private interface ThrowingFunction<S, T, E extends Throwable> {
T apply(S src) throws E;
}
}
| 11,599 | 39.138408 | 141 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2LoginAuthenticationFilter.java | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
/**
* An implementation of an {@link AbstractAuthenticationProcessingFilter} for OAuth 2.0
* Login.
*
* <p>
* This authentication {@code Filter} handles the processing of an OAuth 2.0 Authorization
* Response for the authorization code grant flow and delegates an
* {@link OAuth2LoginAuthenticationToken} to the {@link AuthenticationManager} to log in
* the End-User.
*
* <p>
* The OAuth 2.0 Authorization Response is processed as follows:
*
* <ul>
* <li>Assuming the End-User (Resource Owner) has granted access to the Client, the
* Authorization Server will append the {@link OAuth2ParameterNames#CODE code} and
* {@link OAuth2ParameterNames#STATE state} parameters to the
* {@link OAuth2ParameterNames#REDIRECT_URI redirect_uri} (provided in the Authorization
* Request) and redirect the End-User's user-agent back to this {@code Filter} (the
* Client).</li>
* <li>This {@code Filter} will then create an {@link OAuth2LoginAuthenticationToken} with
* the {@link OAuth2ParameterNames#CODE code} received and delegate it to the
* {@link AuthenticationManager} to authenticate.</li>
* <li>Upon a successful authentication, an {@link OAuth2AuthenticationToken} is created
* (representing the End-User {@code Principal}) and associated to the
* {@link OAuth2AuthorizedClient Authorized Client} using the
* {@link OAuth2AuthorizedClientRepository}.</li>
* <li>Finally, the {@link OAuth2AuthenticationToken} is returned and ultimately stored in
* the {@link SecurityContextRepository} to complete the authentication processing.</li>
* </ul>
*
* @author Joe Grandja
* @since 5.0
* @see AbstractAuthenticationProcessingFilter
* @see OAuth2LoginAuthenticationToken
* @see OAuth2AuthenticationToken
* @see OAuth2LoginAuthenticationProvider
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationResponse
* @see AuthorizationRequestRepository
* @see OAuth2AuthorizationRequestRedirectFilter
* @see ClientRegistrationRepository
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientRepository
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization
* Response</a>
*/
public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
/**
* The default {@code URI} where this {@code Filter} processes authentication
* requests.
*/
public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*";
private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found";
private ClientRegistrationRepository clientRegistrationRepository;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
private Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter = this::createAuthenticationResult;
/**
* Constructs an {@code OAuth2LoginAuthenticationFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientService the authorized client service
*/
public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientService authorizedClientService) {
this(clientRegistrationRepository, authorizedClientService, DEFAULT_FILTER_PROCESSES_URI);
}
/**
* Constructs an {@code OAuth2LoginAuthenticationFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientService the authorized client service
* @param filterProcessesUrl the {@code URI} where this {@code Filter} will process
* the authentication requests
*/
public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientService authorizedClientService, String filterProcessesUrl) {
this(clientRegistrationRepository,
new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService),
filterProcessesUrl);
}
/**
* Constructs an {@code OAuth2LoginAuthenticationFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the authorized client repository
* @param filterProcessesUrl the {@code URI} where this {@code Filter} will process
* the authentication requests
* @since 5.1
*/
public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository, String filterProcessesUrl) {
super(filterProcessesUrl);
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientRepository = authorizedClientRepository;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) {
OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
if (authorizationRequest == null) {
OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
if (clientRegistration == null) {
OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE,
"Client Registration not found with Id: " + registrationId, null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
// @formatter:off
String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replaceQuery(null)
.build()
.toUriString();
// @formatter:on
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params,
redirectUri);
Object authenticationDetails = this.authenticationDetailsSource.buildDetails(request);
OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration,
new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
authenticationRequest.setDetails(authenticationDetails);
OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) this
.getAuthenticationManager().authenticate(authenticationRequest);
OAuth2AuthenticationToken oauth2Authentication = this.authenticationResultConverter
.convert(authenticationResult);
Assert.notNull(oauth2Authentication, "authentication result cannot be null");
oauth2Authentication.setDetails(authenticationDetails);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), oauth2Authentication.getName(),
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);
return oauth2Authentication;
}
/**
* Sets the repository for stored {@link OAuth2AuthorizationRequest}'s.
* @param authorizationRequestRepository the repository for stored
* {@link OAuth2AuthorizationRequest}'s
*/
public final void setAuthorizationRequestRepository(
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
/**
* Sets the converter responsible for converting from
* {@link OAuth2LoginAuthenticationToken} to {@link OAuth2AuthenticationToken}
* authentication result.
* @param authenticationResultConverter the converter for
* {@link OAuth2AuthenticationToken}'s
* @since 5.6
*/
public final void setAuthenticationResultConverter(
Converter<OAuth2LoginAuthenticationToken, OAuth2AuthenticationToken> authenticationResultConverter) {
Assert.notNull(authenticationResultConverter, "authenticationResultConverter cannot be null");
this.authenticationResultConverter = authenticationResultConverter;
}
private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) {
return new OAuth2AuthenticationToken(authenticationResult.getPrincipal(), authenticationResult.getAuthorities(),
authenticationResult.getClientRegistration().getRegistrationId());
}
}
| 12,200 | 50.050209 | 155 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/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.
*/
/**
* OAuth 2.0 Client {@code Filter}'s and supporting classes and interfaces.
*/
package org.springframework.security.oauth2.client.web;
| 763 | 35.380952 | 75 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizationRequestRepository.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AuthorizationRequestRepository} that stores
* {@link OAuth2AuthorizationRequest} in the {@code HttpSession}.
*
* @author Joe Grandja
* @author Rob Winch
* @author Craig Andrews
* @since 5.0
* @see AuthorizationRequestRepository
* @see OAuth2AuthorizationRequest
*/
public final class HttpSessionOAuth2AuthorizationRequestRepository
implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {
private static final String DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME = HttpSessionOAuth2AuthorizationRequestRepository.class
.getName() + ".AUTHORIZATION_REQUEST";
private final String sessionAttributeName = DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME;
@Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
Assert.notNull(request, "request cannot be null");
String stateParameter = getStateParameter(request);
if (stateParameter == null) {
return null;
}
OAuth2AuthorizationRequest authorizationRequest = getAuthorizationRequest(request);
return (authorizationRequest != null && stateParameter.equals(authorizationRequest.getState()))
? authorizationRequest : null;
}
@Override
public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request,
HttpServletResponse response) {
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
if (authorizationRequest == null) {
removeAuthorizationRequest(request, response);
return;
}
String state = authorizationRequest.getState();
Assert.hasText(state, "authorizationRequest.state cannot be empty");
request.getSession().setAttribute(this.sessionAttributeName, authorizationRequest);
}
@Override
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request,
HttpServletResponse response) {
Assert.notNull(response, "response cannot be null");
OAuth2AuthorizationRequest authorizationRequest = loadAuthorizationRequest(request);
if (authorizationRequest != null) {
request.getSession().removeAttribute(this.sessionAttributeName);
}
return authorizationRequest;
}
/**
* Gets the state parameter from the {@link HttpServletRequest}
* @param request the request to use
* @return the state parameter or null if not found
*/
private String getStateParameter(HttpServletRequest request) {
return request.getParameter(OAuth2ParameterNames.STATE);
}
private OAuth2AuthorizationRequest getAuthorizationRequest(HttpServletRequest request) {
HttpSession session = request.getSession(false);
return (session != null) ? (OAuth2AuthorizationRequest) session.getAttribute(this.sessionAttributeName) : null;
}
}
| 3,776 | 37.540816 | 124 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestResolver.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
/**
* Implementations of this interface are capable of resolving an
* {@link OAuth2AuthorizationRequest} from the provided {@code HttpServletRequest}. Used
* by the {@link OAuth2AuthorizationRequestRedirectFilter} for resolving Authorization
* Requests.
*
* @author Joe Grandja
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationRequestRedirectFilter
*/
public interface OAuth2AuthorizationRequestResolver {
/**
* Returns the {@link OAuth2AuthorizationRequest} resolved from the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param request the {@code HttpServletRequest}
* @return the resolved {@link OAuth2AuthorizationRequest} or {@code null} if not
* available
*/
OAuth2AuthorizationRequest resolve(HttpServletRequest request);
/**
* Returns the {@link OAuth2AuthorizationRequest} resolved from the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param request the {@code HttpServletRequest}
* @param clientRegistrationId the clientRegistrationId to use
* @return the resolved {@link OAuth2AuthorizationRequest} or {@code null} if not
* available
*/
OAuth2AuthorizationRequest resolve(HttpServletRequest request, String clientRegistrationId);
}
| 2,104 | 35.929825 | 93 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationCodeGrantFilter.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A {@code Filter} for the OAuth 2.0 Authorization Code Grant, which handles the
* processing of the OAuth 2.0 Authorization Response.
*
* <p>
* The OAuth 2.0 Authorization Response is processed as follows:
*
* <ul>
* <li>Assuming the End-User (Resource Owner) has granted access to the Client, the
* Authorization Server will append the {@link OAuth2ParameterNames#CODE code} and
* {@link OAuth2ParameterNames#STATE state} parameters to the
* {@link OAuth2ParameterNames#REDIRECT_URI redirect_uri} (provided in the Authorization
* Request) and redirect the End-User's user-agent back to this {@code Filter} (the
* Client).</li>
* <li>This {@code Filter} will then create an
* {@link OAuth2AuthorizationCodeAuthenticationToken} with the
* {@link OAuth2ParameterNames#CODE code} received and delegate it to the
* {@link AuthenticationManager} to authenticate.</li>
* <li>Upon a successful authentication, an {@link OAuth2AuthorizedClient Authorized
* Client} is created by associating the
* {@link OAuth2AuthorizationCodeAuthenticationToken#getClientRegistration() client} to
* the {@link OAuth2AuthorizationCodeAuthenticationToken#getAccessToken() access token}
* and current {@code Principal} and saving it via the
* {@link OAuth2AuthorizedClientRepository}.</li>
* </ul>
*
* @author Joe Grandja
* @author Parikshit Dutta
* @since 5.1
* @see OAuth2AuthorizationCodeAuthenticationToken
* @see OAuth2AuthorizationCodeAuthenticationProvider
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationResponse
* @see AuthorizationRequestRepository
* @see OAuth2AuthorizationRequestRedirectFilter
* @see ClientRegistrationRepository
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientRepository
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization
* Response</a>
*/
public class OAuth2AuthorizationCodeGrantFilter extends OncePerRequestFilter {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private final ClientRegistrationRepository clientRegistrationRepository;
private final OAuth2AuthorizedClientRepository authorizedClientRepository;
private final AuthenticationManager authenticationManager;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
private final AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
private RequestCache requestCache = new HttpSessionRequestCache();
/**
* Constructs an {@code OAuth2AuthorizationCodeGrantFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the authorized client repository
* @param authenticationManager the authentication manager
*/
public OAuth2AuthorizationCodeGrantFilter(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository, AuthenticationManager authenticationManager) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientRepository = authorizedClientRepository;
this.authenticationManager = authenticationManager;
}
/**
* Sets the repository for stored {@link OAuth2AuthorizationRequest}'s.
* @param authorizationRequestRepository the repository for stored
* {@link OAuth2AuthorizationRequest}'s
*/
public final void setAuthorizationRequestRepository(
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
/**
* Sets the {@link RequestCache} used for loading a previously saved request (if
* available) and replaying it after completing the processing of the OAuth 2.0
* Authorization Response.
* @param requestCache the cache used for loading a previously saved request (if
* available)
* @since 5.4
*/
public final void setRequestCache(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if (matchesAuthorizationResponse(request)) {
processAuthorizationResponse(request, response);
return;
}
filterChain.doFilter(request, response);
}
private boolean matchesAuthorizationResponse(HttpServletRequest request) {
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) {
return false;
}
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
.loadAuthorizationRequest(request);
if (authorizationRequest == null) {
return false;
}
// Compare redirect_uri
UriComponents requestUri = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request)).build();
UriComponents redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri()).build();
Set<Map.Entry<String, List<String>>> requestUriParameters = new LinkedHashSet<>(
requestUri.getQueryParams().entrySet());
Set<Map.Entry<String, List<String>>> redirectUriParameters = new LinkedHashSet<>(
redirectUri.getQueryParams().entrySet());
// Remove the additional request parameters (if any) from the authorization
// response (request)
// before doing an exact comparison with the authorizationRequest.getRedirectUri()
// parameters (if any)
requestUriParameters.retainAll(redirectUriParameters);
if (Objects.equals(requestUri.getScheme(), redirectUri.getScheme())
&& Objects.equals(requestUri.getUserInfo(), redirectUri.getUserInfo())
&& Objects.equals(requestUri.getHost(), redirectUri.getHost())
&& Objects.equals(requestUri.getPort(), redirectUri.getPort())
&& Objects.equals(requestUri.getPath(), redirectUri.getPath())
&& Objects.equals(requestUriParameters.toString(), redirectUriParameters.toString())) {
return true;
}
return false;
}
private void processAuthorizationResponse(HttpServletRequest request, HttpServletResponse response)
throws IOException {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository
.removeAuthorizationRequest(request, response);
String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
String redirectUri = UrlUtils.buildFullRequestUrl(request);
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params,
redirectUri);
OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(
clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
try {
authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationManager
.authenticate(authenticationRequest);
}
catch (OAuth2AuthorizationException ex) {
OAuth2Error error = ex.getError();
UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri())
.queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
if (StringUtils.hasLength(error.getDescription())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
}
if (StringUtils.hasLength(error.getUri())) {
uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
}
this.redirectStrategy.sendRedirect(request, response, uriBuilder.build().encode().toString());
return;
}
Authentication currentAuthentication = this.securityContextHolderStrategy.getContext().getAuthentication();
String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser";
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(),
authenticationResult.getRefreshToken());
this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, currentAuthentication, request,
response);
String redirectUrl = authorizationRequest.getRedirectUri();
SavedRequest savedRequest = this.requestCache.getRequest(request, response);
if (savedRequest != null) {
redirectUrl = savedRequest.getRedirectUrl();
this.requestCache.removeRequest(request, response);
}
this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
}
| 13,363 | 49.052434 | 155 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/HttpSessionOAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientRepository} that stores
* {@link OAuth2AuthorizedClient}'s in the {@code HttpSession}.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizedClientRepository
* @see OAuth2AuthorizedClient
*/
public final class HttpSessionOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = HttpSessionOAuth2AuthorizedClientRepository.class
.getName() + ".AUTHORIZED_CLIENTS";
private final String sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME;
@SuppressWarnings("unchecked")
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(request, "request cannot be null");
return (T) this.getAuthorizedClients(request).get(clientRegistrationId);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(request, "request cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
if (!authorizedClients.isEmpty()) {
if (authorizedClients.remove(clientRegistrationId) != null) {
if (!authorizedClients.isEmpty()) {
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
else {
request.getSession().removeAttribute(this.sessionAttributeName);
}
}
}
}
@SuppressWarnings("unchecked")
private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(HttpServletRequest request) {
HttpSession session = request.getSession(false);
Map<String, OAuth2AuthorizedClient> authorizedClients = (session != null)
? (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName) : null;
if (authorizedClients == null) {
authorizedClients = new HashMap<>();
}
return authorizedClients;
}
}
| 3,900 | 39.635417 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestRedirectFilter.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
/**
* This {@code Filter} initiates the authorization code grant flow by redirecting the
* End-User's user-agent to the Authorization Server's Authorization Endpoint.
*
* <p>
* It builds the OAuth 2.0 Authorization Request, which is used as the redirect
* {@code URI} to the Authorization Endpoint. The redirect {@code URI} will include the
* client identifier, requested scope(s), state, response type, and a redirection URI
* which the authorization server will send the user-agent back to once access is granted
* (or denied) by the End-User (Resource Owner).
*
* <p>
* By default, this {@code Filter} responds to authorization requests at the {@code URI}
* {@code /oauth2/authorization/{registrationId}} using the default
* {@link OAuth2AuthorizationRequestResolver}. The {@code URI} template variable
* {@code {registrationId}} represents the {@link ClientRegistration#getRegistrationId()
* registration identifier} of the client that is used for initiating the OAuth 2.0
* Authorization Request.
*
* <p>
* The default base {@code URI} {@code /oauth2/authorization} may be overridden via the
* constructor
* {@link #OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository, String)},
* or alternatively, an {@code OAuth2AuthorizationRequestResolver} may be provided to the
* constructor
* {@link #OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver)}
* to override the resolving of authorization requests.
*
* @author Joe Grandja
* @author Rob Winch
* @since 5.0
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationRequestResolver
* @see AuthorizationRequestRepository
* @see ClientRegistration
* @see ClientRegistrationRepository
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request
* (Authorization Code)</a>
*/
public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter {
/**
* The default base {@code URI} used for authorization requests.
*/
public static final String DEFAULT_AUTHORIZATION_REQUEST_BASE_URI = "/oauth2/authorization";
private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
private RedirectStrategy authorizationRedirectStrategy = new DefaultRedirectStrategy();
private OAuth2AuthorizationRequestResolver authorizationRequestResolver;
private AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository();
private RequestCache requestCache = new HttpSessionRequestCache();
/**
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
*/
public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository) {
this(clientRegistrationRepository, DEFAULT_AUTHORIZATION_REQUEST_BASE_URI);
}
/**
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizationRequestBaseUri the base {@code URI} used for authorization
* requests
*/
public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository,
String authorizationRequestBaseUri) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty");
this.authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository,
authorizationRequestBaseUri);
}
/**
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided
* parameters.
* @param authorizationRequestResolver the resolver used for resolving authorization
* requests
* @since 5.1
*/
public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver) {
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
this.authorizationRequestResolver = authorizationRequestResolver;
}
/**
* Sets the redirect strategy for Authorization Endpoint redirect URI.
* @param authorizationRedirectStrategy the redirect strategy
*/
public void setAuthorizationRedirectStrategy(RedirectStrategy authorizationRedirectStrategy) {
Assert.notNull(authorizationRedirectStrategy, "authorizationRedirectStrategy cannot be null");
this.authorizationRedirectStrategy = authorizationRedirectStrategy;
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
* @param authorizationRequestRepository the repository used for storing
* {@link OAuth2AuthorizationRequest}'s
*/
public final void setAuthorizationRequestRepository(
AuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
/**
* Sets the {@link RequestCache} used for storing the current request before
* redirecting the OAuth 2.0 Authorization Request.
* @param requestCache the cache used for storing the current request
*/
public final void setRequestCache(RequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request);
if (authorizationRequest != null) {
this.sendRedirectForAuthorization(request, response, authorizationRequest);
return;
}
}
catch (Exception ex) {
this.unsuccessfulRedirectForAuthorization(request, response, ex);
return;
}
try {
filterChain.doFilter(request, response);
}
catch (IOException ex) {
throw ex;
}
catch (Exception ex) {
// Check to see if we need to handle ClientAuthorizationRequiredException
Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);
ClientAuthorizationRequiredException authzEx = (ClientAuthorizationRequiredException) this.throwableAnalyzer
.getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain);
if (authzEx != null) {
try {
OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request,
authzEx.getClientRegistrationId());
if (authorizationRequest == null) {
throw authzEx;
}
this.requestCache.saveRequest(request, response);
this.sendRedirectForAuthorization(request, response, authorizationRequest);
}
catch (Exception failed) {
this.unsuccessfulRedirectForAuthorization(request, response, failed);
}
return;
}
if (ex instanceof ServletException) {
throw (ServletException) ex;
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new RuntimeException(ex);
}
}
private void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response,
OAuth2AuthorizationRequest authorizationRequest) throws IOException {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) {
this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response);
}
this.authorizationRedirectStrategy.sendRedirect(request, response,
authorizationRequest.getAuthorizationRequestUri());
}
private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response,
Exception ex) throws IOException {
LogMessage message = LogMessage.format("Authorization Request failed: %s", ex);
if (InvalidClientRegistrationIdException.class.isAssignableFrom(ex.getClass())) {
// Log an invalid registrationId at WARN level to allow these errors to be
// tuned separately from other errors
this.logger.warn(message, ex);
}
else {
this.logger.error(message, ex);
}
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer {
@Override
protected void initExtractorMap() {
super.initExtractorMap();
registerExtractor(ServletException.class, (throwable) -> {
ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class);
return ((ServletException) throwable).getRootCause();
});
}
}
}
| 10,817 | 41.590551 | 155 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationResponseUtils.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.util.Map;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* Utility methods for an OAuth 2.0 Authorization Response.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizationResponse
*/
final class OAuth2AuthorizationResponseUtils {
private OAuth2AuthorizationResponseUtils() {
}
static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size());
map.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
params.add(key, value);
}
}
});
return params;
}
static boolean isAuthorizationResponse(MultiValueMap<String, String> request) {
return isAuthorizationResponseSuccess(request) || isAuthorizationResponseError(request);
}
static boolean isAuthorizationResponseSuccess(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.CODE))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static boolean isAuthorizationResponseError(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.ERROR))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static OAuth2AuthorizationResponse convert(MultiValueMap<String, String> request, String redirectUri) {
String code = request.getFirst(OAuth2ParameterNames.CODE);
String errorCode = request.getFirst(OAuth2ParameterNames.ERROR);
String state = request.getFirst(OAuth2ParameterNames.STATE);
if (StringUtils.hasText(code)) {
return OAuth2AuthorizationResponse.success(code).redirectUri(redirectUri).state(state).build();
}
String errorDescription = request.getFirst(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = request.getFirst(OAuth2ParameterNames.ERROR_URI);
// @formatter:off
return OAuth2AuthorizationResponse.error(errorCode)
.redirectUri(redirectUri)
.errorDescription(errorDescription)
.errorUri(errorUri)
.state(state)
.build();
// @formatter:on
}
}
| 3,046 | 34.847059 | 104 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.util.Assert;
/**
* An implementation of an {@link OAuth2AuthorizedClientRepository} that delegates to the
* provided {@link OAuth2AuthorizedClientService} if the current {@code Principal} is
* authenticated, otherwise, to the default (or provided)
* {@link OAuth2AuthorizedClientRepository} if the current request is unauthenticated (or
* anonymous). The default {@code OAuth2AuthorizedClientRepository} is
* {@link HttpSessionOAuth2AuthorizedClientRepository}.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizedClientRepository
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientService
* @see HttpSessionOAuth2AuthorizedClientRepository
*/
public final class AuthenticatedPrincipalOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private final OAuth2AuthorizedClientService authorizedClientService;
private OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository = new HttpSessionOAuth2AuthorizedClientRepository();
/**
* Constructs a {@code AuthenticatedPrincipalOAuth2AuthorizedClientRepository} using
* the provided parameters.
* @param authorizedClientService the authorized client service
*/
public AuthenticatedPrincipalOAuth2AuthorizedClientRepository(
OAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.authorizedClientService = authorizedClientService;
}
/**
* Sets the {@link OAuth2AuthorizedClientRepository} used for requests that are
* unauthenticated (or anonymous). The default is
* {@link HttpSessionOAuth2AuthorizedClientRepository}.
* @param anonymousAuthorizedClientRepository the repository used for requests that
* are unauthenticated (or anonymous)
*/
public void setAnonymousAuthorizedClientRepository(
OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository) {
Assert.notNull(anonymousAuthorizedClientRepository, "anonymousAuthorizedClientRepository cannot be null");
this.anonymousAuthorizedClientRepository = anonymousAuthorizedClientRepository;
}
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, request);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (this.isPrincipalAuthenticated(principal)) {
this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
}
else {
this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, request,
response);
}
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (this.isPrincipalAuthenticated(principal)) {
this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
}
else {
this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, request,
response);
}
}
private boolean isPrincipalAuthenticated(Authentication authentication) {
return authentication != null && !this.authenticationTrustResolver.isAnonymous(authentication)
&& authentication.isAuthenticated();
}
}
| 4,968 | 42.208696 | 130 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultReactiveOAuth2AuthorizedClientManager.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationSuccessHandler;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
/**
* The default implementation of a {@link ReactiveOAuth2AuthorizedClientManager} for use
* within the context of a {@link ServerWebExchange}.
*
* <p>
* (When operating <em>outside</em> of the context of a {@link ServerWebExchange}, use
* {@link org.springframework.security.oauth2.client.AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager
* AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager} instead.)
* </p>
*
* <p>
* This is a reactive equivalent of {@link DefaultOAuth2AuthorizedClientManager}.
* </p>
*
* <h2>Authorized Client Persistence</h2>
*
* <p>
* This client manager utilizes a {@link ServerOAuth2AuthorizedClientRepository} to
* persist {@link OAuth2AuthorizedClient}s.
* </p>
*
* <p>
* By default, when an authorization attempt succeeds, the {@link OAuth2AuthorizedClient}
* will be saved in the authorized client repository. This functionality can be changed by
* configuring a custom {@link ReactiveOAuth2AuthorizationSuccessHandler} via
* {@link #setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler)}.
* </p>
*
* <p>
* By default, when an authorization attempt fails due to an
* {@value org.springframework.security.oauth2.core.OAuth2ErrorCodes#INVALID_GRANT} error,
* the previously saved {@link OAuth2AuthorizedClient} will be removed from the authorized
* client repository. (The
* {@value org.springframework.security.oauth2.core.OAuth2ErrorCodes#INVALID_GRANT} error
* generally occurs when a refresh token that is no longer valid is used to retrieve a new
* access token.) This functionality can be changed by configuring a custom
* {@link ReactiveOAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)}.
* </p>
*
* @author Joe Grandja
* @author Phil Clay
* @since 5.2
* @see ReactiveOAuth2AuthorizedClientManager
* @see ReactiveOAuth2AuthorizedClientProvider
* @see ReactiveOAuth2AuthorizationSuccessHandler
* @see ReactiveOAuth2AuthorizationFailureHandler
*/
public final class DefaultReactiveOAuth2AuthorizedClientManager implements ReactiveOAuth2AuthorizedClientManager {
// @formatter:off
private static final ReactiveOAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = ReactiveOAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.password()
.build();
// @formatter:on
// @formatter:off
private static final Mono<ServerWebExchange> currentServerWebExchangeMono = Mono.deferContextual(Mono::just)
.filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class));
// @formatter:on
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
private final ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
private Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper = new DefaultContextAttributesMapper();
private ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
/**
* Constructs a {@code DefaultReactiveOAuth2AuthorizedClientManager} using the
* provided parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public DefaultReactiveOAuth2AuthorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientRepository = authorizedClientRepository;
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
.saveAuthorizedClient(authorizedClient, principal,
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName()));
this.authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
clientRegistrationId, principal,
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName())));
}
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
Authentication principal = authorizeRequest.getPrincipal();
// @formatter:off
return Mono.justOrEmpty(authorizeRequest.<ServerWebExchange>getAttribute(ServerWebExchange.class.getName()))
.switchIfEmpty(currentServerWebExchangeMono)
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException("serverWebExchange cannot be null")))
.flatMap((serverWebExchange) -> Mono
.justOrEmpty(authorizeRequest.getAuthorizedClient())
.switchIfEmpty(Mono.defer(() -> loadAuthorizedClient(clientRegistrationId, principal, serverWebExchange)))
.flatMap((authorizedClient) -> // Re-authorize
authorizationContext(authorizeRequest, authorizedClient)
.flatMap((authorizationContext) -> authorize(authorizationContext, principal, serverWebExchange))
// Default to the existing authorizedClient if the
// client was not re-authorized
.defaultIfEmpty((authorizeRequest.getAuthorizedClient() != null)
? authorizeRequest.getAuthorizedClient() : authorizedClient)
)
.switchIfEmpty(Mono.defer(() ->
// Authorize
this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId)
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
"Could not find ClientRegistration with id '" + clientRegistrationId + "'")))
.flatMap((clientRegistration) -> authorizationContext(authorizeRequest,
clientRegistration))
.flatMap((authorizationContext) -> authorize(authorizationContext, principal,
serverWebExchange))))
);
// @formatter:on
}
private Mono<OAuth2AuthorizedClient> loadAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange serverWebExchange) {
return this.authorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, serverWebExchange);
}
/**
* Performs authorization and then delegates to either the
* {@link #authorizationSuccessHandler} or {@link #authorizationFailureHandler},
* depending on the authorization result.
* @param authorizationContext the context to authorize
* @param principal the principle to authorize
* @param serverWebExchange the currently active exchange
* @return a {@link Mono} that emits the authorized client after the authorization
* attempt succeeds and the {@link #authorizationSuccessHandler} has completed, or
* completes with an exception after the authorization attempt fails and the
* {@link #authorizationFailureHandler} has completed
*/
private Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizationContext authorizationContext,
Authentication principal, ServerWebExchange serverWebExchange) {
// @formatter:off
return this.authorizedClientProvider.authorize(authorizationContext)
// Delegate to the authorizationSuccessHandler of the successful
// authorization
.flatMap((authorizedClient) ->
this.authorizationSuccessHandler
.onAuthorizationSuccess(authorizedClient, principal, createAttributes(serverWebExchange))
.thenReturn(authorizedClient)
)
// Delegate to the authorizationFailureHandler of the failed authorization
.onErrorResume(OAuth2AuthorizationException.class, (authorizationException) ->
this.authorizationFailureHandler
.onAuthorizationFailure(authorizationException, principal, createAttributes(serverWebExchange))
.then(Mono.error(authorizationException))
);
// @formatter:on
}
private Map<String, Object> createAttributes(ServerWebExchange serverWebExchange) {
return Collections.singletonMap(ServerWebExchange.class.getName(), serverWebExchange);
}
private Mono<OAuth2AuthorizationContext> authorizationContext(OAuth2AuthorizeRequest authorizeRequest,
OAuth2AuthorizedClient authorizedClient) {
// @formatter:off
return Mono.just(authorizeRequest)
.flatMap(this.contextAttributesMapper)
.map((attrs) -> OAuth2AuthorizationContext
.withAuthorizedClient(authorizedClient)
.principal(authorizeRequest.getPrincipal())
.attributes((attributes) -> {
if (!CollectionUtils.isEmpty(attrs)) {
attributes.putAll(attrs);
}
})
.build());
// @formatter:on
}
private Mono<OAuth2AuthorizationContext> authorizationContext(OAuth2AuthorizeRequest authorizeRequest,
ClientRegistration clientRegistration) {
// @formatter:off
return Mono.just(authorizeRequest)
.flatMap(this.contextAttributesMapper)
.map((attrs) -> OAuth2AuthorizationContext.withClientRegistration(clientRegistration)
.principal(authorizeRequest.getPrincipal())
.attributes((attributes) -> {
if (!CollectionUtils.isEmpty(attrs)) {
attributes.putAll(attrs);
}
})
.build()
);
// @formatter:on
}
/**
* Sets the {@link ReactiveOAuth2AuthorizedClientProvider} used for authorizing (or
* re-authorizing) an OAuth 2.0 Client.
* @param authorizedClientProvider the {@link ReactiveOAuth2AuthorizedClientProvider}
* used for authorizing (or re-authorizing) an OAuth 2.0 Client
*/
public void setAuthorizedClientProvider(ReactiveOAuth2AuthorizedClientProvider authorizedClientProvider) {
Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null");
this.authorizedClientProvider = authorizedClientProvider;
}
/**
* Sets the {@code Function} used for mapping attribute(s) from the
* {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to
* the {@link OAuth2AuthorizationContext#getAttributes() authorization context}.
* @param contextAttributesMapper the {@code Function} used for supplying the
* {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes()
* authorization context}
*/
public void setContextAttributesMapper(
Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper) {
Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null");
this.contextAttributesMapper = contextAttributesMapper;
}
/**
* Sets the handler that handles successful authorizations.
*
* The default saves {@link OAuth2AuthorizedClient}s in the
* {@link ServerOAuth2AuthorizedClientRepository}.
* @param authorizationSuccessHandler the handler that handles successful
* authorizations.
* @since 5.3
*/
public void setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler) {
Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null");
this.authorizationSuccessHandler = authorizationSuccessHandler;
}
/**
* Sets the handler that handles authorization failures.
*
* <p>
* A {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is used
* by default.
* </p>
* @param authorizationFailureHandler the handler that handles authorization failures.
* @since 5.3
* @see RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler
*/
public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
}
/**
* The default implementation of the {@link #setContextAttributesMapper(Function)
* contextAttributesMapper}.
*/
public static class DefaultContextAttributesMapper
implements Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> {
@Override
public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) {
ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
// @formatter:off
return Mono.justOrEmpty(serverWebExchange)
.switchIfEmpty(currentServerWebExchangeMono)
.flatMap((exchange) -> {
Map<String, Object> contextAttributes = Collections.emptyMap();
String scope = exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope)) {
contextAttributes = new HashMap<>();
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
StringUtils.delimitedListToStringArray(scope, " "));
}
return Mono.just(contextAttributes);
})
.defaultIfEmpty(Collections.emptyMap());
// @formatter:on
}
}
}
| 15,624 | 45.227811 | 153 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizationRequestCustomizers.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.web.server.DefaultServerOAuth2AuthorizationRequestResolver;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
/**
* A factory of customizers that customize the {@link OAuth2AuthorizationRequest OAuth 2.0
* Authorization Request} via the {@link OAuth2AuthorizationRequest.Builder}.
*
* @author Joe Grandja
* @since 5.7
* @see OAuth2AuthorizationRequest.Builder
* @see DefaultOAuth2AuthorizationRequestResolver#setAuthorizationRequestCustomizer(Consumer)
* @see DefaultServerOAuth2AuthorizationRequestResolver#setAuthorizationRequestCustomizer(Consumer)
*/
public final class OAuth2AuthorizationRequestCustomizers {
private static final StringKeyGenerator DEFAULT_SECURE_KEY_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private OAuth2AuthorizationRequestCustomizers() {
}
/**
* Returns a {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} that adds the
* {@link PkceParameterNames#CODE_CHALLENGE code_challenge} and, usually,
* {@link PkceParameterNames#CODE_CHALLENGE_METHOD code_challenge_method} parameters
* to the OAuth 2.0 Authorization Request. The {@code code_verifier} is stored in
* {@link OAuth2AuthorizationRequest#getAttribute(String)} under the key
* {@link PkceParameterNames#CODE_VERIFIER code_verifier} for subsequent use in the
* OAuth 2.0 Access Token Request.
* @return a {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} that adds the PKCE parameters
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-1.1">1.1. Protocol Flow</a>
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-4.1">4.1. Client Creates a
* Code Verifier</a>
* @see <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/rfc7636#section-4.2">4.2. Client Creates the
* Code Challenge</a>
*/
public static Consumer<OAuth2AuthorizationRequest.Builder> withPkce() {
return OAuth2AuthorizationRequestCustomizers::applyPkce;
}
private static void applyPkce(OAuth2AuthorizationRequest.Builder builder) {
if (isPkceAlreadyApplied(builder)) {
return;
}
String codeVerifier = DEFAULT_SECURE_KEY_GENERATOR.generateKey();
builder.attributes((attrs) -> attrs.put(PkceParameterNames.CODE_VERIFIER, codeVerifier));
builder.additionalParameters((params) -> {
try {
String codeChallenge = createHash(codeVerifier);
params.put(PkceParameterNames.CODE_CHALLENGE, codeChallenge);
params.put(PkceParameterNames.CODE_CHALLENGE_METHOD, "S256");
}
catch (NoSuchAlgorithmException ex) {
params.put(PkceParameterNames.CODE_CHALLENGE, codeVerifier);
}
});
}
private static boolean isPkceAlreadyApplied(OAuth2AuthorizationRequest.Builder builder) {
AtomicBoolean pkceApplied = new AtomicBoolean(false);
builder.additionalParameters((params) -> {
if (params.containsKey(PkceParameterNames.CODE_CHALLENGE)) {
pkceApplied.set(true);
}
});
return pkceApplied.get();
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
| 4,565 | 39.767857 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/AuthorizationRequestRepository.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
/**
* Implementations of this interface are responsible for the persistence of
* {@link OAuth2AuthorizationRequest} between requests.
*
* <p>
* Used by the {@link OAuth2AuthorizationRequestRedirectFilter} for persisting the
* Authorization Request before it initiates the authorization code grant flow. As well,
* used by the {@link OAuth2LoginAuthenticationFilter} for resolving the associated
* Authorization Request when handling the callback of the Authorization Response.
*
* @param <T> The type of OAuth 2.0 Authorization Request
* @author Joe Grandja
* @since 5.0
* @see OAuth2AuthorizationRequest
* @see HttpSessionOAuth2AuthorizationRequestRepository
*/
public interface AuthorizationRequestRepository<T extends OAuth2AuthorizationRequest> {
/**
* Returns the {@link OAuth2AuthorizationRequest} associated to the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param request the {@code HttpServletRequest}
* @return the {@link OAuth2AuthorizationRequest} or {@code null} if not available
*/
T loadAuthorizationRequest(HttpServletRequest request);
/**
* Persists the {@link OAuth2AuthorizationRequest} associating it to the provided
* {@code HttpServletRequest} and/or {@code HttpServletResponse}.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest}
* @param request the {@code HttpServletRequest}
* @param response the {@code HttpServletResponse}
*/
void saveAuthorizationRequest(T authorizationRequest, HttpServletRequest request, HttpServletResponse response);
/**
* Removes and returns the {@link OAuth2AuthorizationRequest} associated to the
* provided {@code HttpServletRequest} and {@code HttpServletResponse} or if not
* available returns {@code null}.
* @param request the {@code HttpServletRequest}
* @param response the {@code HttpServletResponse}
* @return the {@link OAuth2AuthorizationRequest} or {@code null} if not available
* @since 5.1
*/
T removeAuthorizationRequest(HttpServletRequest request, HttpServletResponse response);
}
| 2,926 | 40.225352 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizationRequestResolver.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* An implementation of an {@link OAuth2AuthorizationRequestResolver} that attempts to
* resolve an {@link OAuth2AuthorizationRequest} from the provided
* {@code HttpServletRequest} using the default request {@code URI} pattern
* {@code /oauth2/authorization/{registrationId}}.
*
* <p>
* <b>NOTE:</b> The default base {@code URI} {@code /oauth2/authorization} may be
* overridden via it's constructor
* {@link #DefaultOAuth2AuthorizationRequestResolver(ClientRegistrationRepository, String)}.
*
* @author Joe Grandja
* @author Rob Winch
* @author Eddú Meléndez
* @author Mark Heckler
* @since 5.1
* @see OAuth2AuthorizationRequestResolver
* @see OAuth2AuthorizationRequestRedirectFilter
*/
public final class DefaultOAuth2AuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
private static final String REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId";
private static final char PATH_DELIMITER = '/';
private static final StringKeyGenerator DEFAULT_STATE_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder());
private static final StringKeyGenerator DEFAULT_SECURE_KEY_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private static final Consumer<OAuth2AuthorizationRequest.Builder> DEFAULT_PKCE_APPLIER = OAuth2AuthorizationRequestCustomizers
.withPkce();
private final ClientRegistrationRepository clientRegistrationRepository;
private final AntPathRequestMatcher authorizationRequestMatcher;
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = (customizer) -> {
};
/**
* Constructs a {@code DefaultOAuth2AuthorizationRequestResolver} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizationRequestBaseUri the base {@code URI} used for resolving
* authorization requests
*/
public DefaultOAuth2AuthorizationRequestResolver(ClientRegistrationRepository clientRegistrationRepository,
String authorizationRequestBaseUri) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizationRequestMatcher = new AntPathRequestMatcher(
authorizationRequestBaseUri + "/{" + REGISTRATION_ID_URI_VARIABLE_NAME + "}");
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
String registrationId = resolveRegistrationId(request);
if (registrationId == null) {
return null;
}
String redirectUriAction = getAction(request, "login");
return resolve(request, registrationId, redirectUriAction);
}
@Override
public OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId) {
if (registrationId == null) {
return null;
}
String redirectUriAction = getAction(request, "authorize");
return resolve(request, registrationId, redirectUriAction);
}
/**
* Sets the {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} allowing for further customizations.
* @param authorizationRequestCustomizer the {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder}
* @since 5.3
* @see OAuth2AuthorizationRequestCustomizers
*/
public void setAuthorizationRequestCustomizer(
Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer) {
Assert.notNull(authorizationRequestCustomizer, "authorizationRequestCustomizer cannot be null");
this.authorizationRequestCustomizer = authorizationRequestCustomizer;
}
private String getAction(HttpServletRequest request, String defaultAction) {
String action = request.getParameter("action");
if (action == null) {
return defaultAction;
}
return action;
}
private OAuth2AuthorizationRequest resolve(HttpServletRequest request, String registrationId,
String redirectUriAction) {
if (registrationId == null) {
return null;
}
ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
if (clientRegistration == null) {
throw new InvalidClientRegistrationIdException("Invalid Client Registration with Id: " + registrationId);
}
OAuth2AuthorizationRequest.Builder builder = getBuilder(clientRegistration);
String redirectUriStr = expandRedirectUri(request, clientRegistration, redirectUriAction);
// @formatter:off
builder.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(redirectUriStr)
.scopes(clientRegistration.getScopes())
.state(DEFAULT_STATE_GENERATOR.generateKey());
// @formatter:on
this.authorizationRequestCustomizer.accept(builder);
return builder.build();
}
private OAuth2AuthorizationRequest.Builder getBuilder(ClientRegistration clientRegistration) {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
// @formatter:off
OAuth2AuthorizationRequest.Builder builder = OAuth2AuthorizationRequest.authorizationCode()
.attributes((attrs) ->
attrs.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
// @formatter:on
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())
&& clientRegistration.getScopes().contains(OidcScopes.OPENID)) {
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope
// value.
applyNonce(builder);
}
if (ClientAuthenticationMethod.NONE.equals(clientRegistration.getClientAuthenticationMethod())) {
DEFAULT_PKCE_APPLIER.accept(builder);
}
return builder;
}
throw new IllegalArgumentException(
"Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue()
+ ") for Client Registration with Id: " + clientRegistration.getRegistrationId());
}
private String resolveRegistrationId(HttpServletRequest request) {
if (this.authorizationRequestMatcher.matches(request)) {
return this.authorizationRequestMatcher.matcher(request).getVariables()
.get(REGISTRATION_ID_URI_VARIABLE_NAME);
}
return null;
}
/**
* Expands the {@link ClientRegistration#getRedirectUri()} with following provided
* variables:<br/>
* - baseUrl (e.g. https://localhost/app) <br/>
* - baseScheme (e.g. https) <br/>
* - baseHost (e.g. localhost) <br/>
* - basePort (e.g. :8080) <br/>
* - basePath (e.g. /app) <br/>
* - registrationId (e.g. google) <br/>
* - action (e.g. login) <br/>
* <p/>
* Null variables are provided as empty strings.
* <p/>
* Default redirectUri is:
* {@code org.springframework.security.config.oauth2.client.CommonOAuth2Provider#DEFAULT_REDIRECT_URL}
* @return expanded URI
*/
private static String expandRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration,
String action) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
// @formatter:off
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(null)
.fragment(null)
.build();
// @formatter:on
String scheme = uriComponents.getScheme();
uriVariables.put("baseScheme", (scheme != null) ? scheme : "");
String host = uriComponents.getHost();
uriVariables.put("baseHost", (host != null) ? host : "");
// following logic is based on HierarchicalUriComponents#toUriString()
int port = uriComponents.getPort();
uriVariables.put("basePort", (port == -1) ? "" : ":" + port);
String path = uriComponents.getPath();
if (StringUtils.hasLength(path)) {
if (path.charAt(0) != PATH_DELIMITER) {
path = PATH_DELIMITER + path;
}
}
uriVariables.put("basePath", (path != null) ? path : "");
uriVariables.put("baseUrl", uriComponents.toUriString());
uriVariables.put("action", (action != null) ? action : "");
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri()).buildAndExpand(uriVariables)
.toUriString();
}
/**
* Creates nonce and its hash for use in OpenID Connect 1.0 Authentication Requests.
* @param builder where the {@link OidcParameterNames#NONCE} and hash is stored for
* the authentication request
*
* @since 5.2
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest">3.1.2.1.
* Authentication Request</a>
*/
private static void applyNonce(OAuth2AuthorizationRequest.Builder builder) {
try {
String nonce = DEFAULT_SECURE_KEY_GENERATOR.generateKey();
String nonceHash = createHash(nonce);
builder.attributes((attrs) -> attrs.put(OidcParameterNames.NONCE, nonce));
builder.additionalParameters((params) -> params.put(OidcParameterNames.NONCE, nonceHash));
}
catch (NoSuchAlgorithmException ex) {
}
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
| 11,628 | 40.532143 | 127 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/OAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* Implementations of this interface are responsible for the persistence of
* {@link OAuth2AuthorizedClient Authorized Client(s)} between requests.
*
* <p>
* The primary purpose of an {@link OAuth2AuthorizedClient Authorized Client} is to
* associate an {@link OAuth2AuthorizedClient#getAccessToken() Access Token} credential to
* a {@link OAuth2AuthorizedClient#getClientRegistration() Client} and Resource Owner, who
* is the {@link OAuth2AuthorizedClient#getPrincipalName() Principal} that originally
* granted the authorization.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizedClient
* @see ClientRegistration
* @see Authentication
* @see OAuth2AccessToken
*/
public interface OAuth2AuthorizedClientRepository {
/**
* Returns the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner) or
* {@code null} if not available.
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param request the {@code HttpServletRequest}
* @param <T> a type of OAuth2AuthorizedClient
* @return the {@link OAuth2AuthorizedClient} or {@code null} if not available
*/
<T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request);
/**
* Saves the {@link OAuth2AuthorizedClient} associating it to the provided End-User
* {@link Authentication} (Resource Owner).
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param request the {@code HttpServletRequest}
* @param response the {@code HttpServletResponse}
*/
void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response);
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner).
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param request the {@code HttpServletRequest}
* @param response the {@code HttpServletResponse}
*/
void removeAuthorizedClient(String clientRegistrationId, Authentication principal, HttpServletRequest request,
HttpServletResponse response);
}
| 3,593 | 42.301205 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/InvalidClientRegistrationIdException.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
/**
* @author Steve Riesenberg
* @since 5.8
*/
class InvalidClientRegistrationIdException extends IllegalArgumentException {
/**
* @param message the exception message
*/
InvalidClientRegistrationIdException(String message) {
super(message);
}
}
| 940 | 27.515152 | 77 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/DefaultOAuth2AuthorizedClientManager.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizationContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* The default implementation of an {@link OAuth2AuthorizedClientManager} for use within
* the context of a {@code HttpServletRequest}.
*
* <p>
* (When operating <em>outside</em> of the context of a {@code HttpServletRequest}, use
* {@link AuthorizedClientServiceOAuth2AuthorizedClientManager} instead.)
*
* <h2>Authorized Client Persistence</h2>
*
* <p>
* This manager utilizes an {@link OAuth2AuthorizedClientRepository} to persist
* {@link OAuth2AuthorizedClient}s.
*
* <p>
* By default, when an authorization attempt succeeds, the {@link OAuth2AuthorizedClient}
* will be saved in the {@link OAuth2AuthorizedClientRepository}. This functionality can
* be changed by configuring a custom {@link OAuth2AuthorizationSuccessHandler} via
* {@link #setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler)}.
*
* <p>
* By default, when an authorization attempt fails due to an
* {@value OAuth2ErrorCodes#INVALID_GRANT} error, the previously saved
* {@link OAuth2AuthorizedClient} will be removed from the
* {@link OAuth2AuthorizedClientRepository}. (The {@value OAuth2ErrorCodes#INVALID_GRANT}
* error can occur when a refresh token that is no longer valid is used to retrieve a new
* access token.) This functionality can be changed by configuring a custom
* {@link OAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)}.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AuthorizedClientManager
* @see OAuth2AuthorizedClientProvider
* @see OAuth2AuthorizationSuccessHandler
* @see OAuth2AuthorizationFailureHandler
*/
public final class DefaultOAuth2AuthorizedClientManager implements OAuth2AuthorizedClientManager {
// @formatter:off
private static final OAuth2AuthorizedClientProvider DEFAULT_AUTHORIZED_CLIENT_PROVIDER = OAuth2AuthorizedClientProviderBuilder.builder()
.authorizationCode()
.refreshToken()
.clientCredentials()
.password()
.build();
// @formatter:on
private final ClientRegistrationRepository clientRegistrationRepository;
private final OAuth2AuthorizedClientRepository authorizedClientRepository;
private OAuth2AuthorizedClientProvider authorizedClientProvider;
private Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper;
private OAuth2AuthorizationSuccessHandler authorizationSuccessHandler;
private OAuth2AuthorizationFailureHandler authorizationFailureHandler;
/**
* Constructs a {@code DefaultOAuth2AuthorizedClientManager} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public DefaultOAuth2AuthorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizedClientRepository = authorizedClientRepository;
this.authorizedClientProvider = DEFAULT_AUTHORIZED_CLIENT_PROVIDER;
this.contextAttributesMapper = new DefaultContextAttributesMapper();
this.authorizationSuccessHandler = (authorizedClient, principal, attributes) -> authorizedClientRepository
.saveAuthorizedClient(authorizedClient, principal,
(HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName()));
this.authorizationFailureHandler = new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
clientRegistrationId, principal,
(HttpServletRequest) attributes.get(HttpServletRequest.class.getName()),
(HttpServletResponse) attributes.get(HttpServletResponse.class.getName())));
}
@Nullable
@Override
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
String clientRegistrationId = authorizeRequest.getClientRegistrationId();
OAuth2AuthorizedClient authorizedClient = authorizeRequest.getAuthorizedClient();
Authentication principal = authorizeRequest.getPrincipal();
HttpServletRequest servletRequest = getHttpServletRequestOrDefault(authorizeRequest.getAttributes());
Assert.notNull(servletRequest, "servletRequest cannot be null");
HttpServletResponse servletResponse = getHttpServletResponseOrDefault(authorizeRequest.getAttributes());
Assert.notNull(servletResponse, "servletResponse cannot be null");
OAuth2AuthorizationContext.Builder contextBuilder;
if (authorizedClient != null) {
contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
}
else {
authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal,
servletRequest);
if (authorizedClient != null) {
contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
}
else {
ClientRegistration clientRegistration = this.clientRegistrationRepository
.findByRegistrationId(clientRegistrationId);
Assert.notNull(clientRegistration,
"Could not find ClientRegistration with id '" + clientRegistrationId + "'");
contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
}
}
// @formatter:off
OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal)
.attributes((attributes) -> {
Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
if (!CollectionUtils.isEmpty(contextAttributes)) {
attributes.putAll(contextAttributes);
}
})
.build();
// @formatter:on
try {
authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
}
catch (OAuth2AuthorizationException ex) {
this.authorizationFailureHandler.onAuthorizationFailure(ex, principal,
createAttributes(servletRequest, servletResponse));
throw ex;
}
if (authorizedClient != null) {
this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal,
createAttributes(servletRequest, servletResponse));
}
else {
// In the case of re-authorization, the returned `authorizedClient` may be
// null if re-authorization is not supported.
// For these cases, return the provided
// `authorizationContext.authorizedClient`.
if (authorizationContext.getAuthorizedClient() != null) {
return authorizationContext.getAuthorizedClient();
}
}
return authorizedClient;
}
private static Map<String, Object> createAttributes(HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(HttpServletRequest.class.getName(), servletRequest);
attributes.put(HttpServletResponse.class.getName(), servletResponse);
return attributes;
}
private static HttpServletRequest getHttpServletRequestOrDefault(Map<String, Object> attributes) {
HttpServletRequest servletRequest = (HttpServletRequest) attributes.get(HttpServletRequest.class.getName());
if (servletRequest == null) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
}
}
return servletRequest;
}
private static HttpServletResponse getHttpServletResponseOrDefault(Map<String, Object> attributes) {
HttpServletResponse servletResponse = (HttpServletResponse) attributes.get(HttpServletResponse.class.getName());
if (servletResponse == null) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
servletResponse = ((ServletRequestAttributes) requestAttributes).getResponse();
}
}
return servletResponse;
}
/**
* Sets the {@link OAuth2AuthorizedClientProvider} used for authorizing (or
* re-authorizing) an OAuth 2.0 Client.
* @param authorizedClientProvider the {@link OAuth2AuthorizedClientProvider} used for
* authorizing (or re-authorizing) an OAuth 2.0 Client
*/
public void setAuthorizedClientProvider(OAuth2AuthorizedClientProvider authorizedClientProvider) {
Assert.notNull(authorizedClientProvider, "authorizedClientProvider cannot be null");
this.authorizedClientProvider = authorizedClientProvider;
}
/**
* Sets the {@code Function} used for mapping attribute(s) from the
* {@link OAuth2AuthorizeRequest} to a {@code Map} of attributes to be associated to
* the {@link OAuth2AuthorizationContext#getAttributes() authorization context}.
* @param contextAttributesMapper the {@code Function} used for supplying the
* {@code Map} of attributes to the {@link OAuth2AuthorizationContext#getAttributes()
* authorization context}
*/
public void setContextAttributesMapper(
Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper) {
Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null");
this.contextAttributesMapper = contextAttributesMapper;
}
/**
* Sets the {@link OAuth2AuthorizationSuccessHandler} that handles successful
* authorizations.
*
* <p>
* The default saves {@link OAuth2AuthorizedClient}s in the
* {@link OAuth2AuthorizedClientRepository}.
* @param authorizationSuccessHandler the {@link OAuth2AuthorizationSuccessHandler}
* that handles successful authorizations
* @since 5.3
*/
public void setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler authorizationSuccessHandler) {
Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null");
this.authorizationSuccessHandler = authorizationSuccessHandler;
}
/**
* Sets the {@link OAuth2AuthorizationFailureHandler} that handles authorization
* failures.
*
* <p>
* A {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} is used by
* default.
* @param authorizationFailureHandler the {@link OAuth2AuthorizationFailureHandler}
* that handles authorization failures
* @since 5.3
* @see RemoveAuthorizedClientOAuth2AuthorizationFailureHandler
*/
public void setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
}
/**
* The default implementation of the {@link #setContextAttributesMapper(Function)
* contextAttributesMapper}.
*/
public static class DefaultContextAttributesMapper
implements Function<OAuth2AuthorizeRequest, Map<String, Object>> {
@Override
public Map<String, Object> apply(OAuth2AuthorizeRequest authorizeRequest) {
Map<String, Object> contextAttributes = Collections.emptyMap();
HttpServletRequest servletRequest = getHttpServletRequestOrDefault(authorizeRequest.getAttributes());
String scope = servletRequest.getParameter(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope)) {
contextAttributes = new HashMap<>();
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
StringUtils.delimitedListToStringArray(scope, " "));
}
return contextAttributes;
}
}
}
| 14,261 | 45.006452 | 137 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.reactive.function.client;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ServerWebExchange;
/**
* Provides an easy mechanism for using an {@link OAuth2AuthorizedClient} to make OAuth2
* requests by including the token as a Bearer Token.
*
* <h3>Authentication and Authorization Failures</h3>
*
* <p>
* Since 5.3, this filter function has the ability to forward authentication (HTTP 401
* Unauthorized) and authorization (HTTP 403 Forbidden) failures from an OAuth 2.0
* Resource Server to a {@link ReactiveOAuth2AuthorizationFailureHandler}. A
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} can be used to
* remove the cached {@link OAuth2AuthorizedClient}, so that future requests will result
* in a new token being retrieved from an Authorization Server, and sent to the Resource
* Server.
* </p>
*
* <p>
* If the
* {@link #ServerOAuth2AuthorizedClientExchangeFilterFunction(ReactiveClientRegistrationRepository, ServerOAuth2AuthorizedClientRepository)}
* constructor is used, a
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} will be
* configured automatically.
* </p>
*
* <p>
* If the
* {@link #ServerOAuth2AuthorizedClientExchangeFilterFunction(ReactiveOAuth2AuthorizedClientManager)}
* constructor is used, a
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} will
* <em>NOT</em> be configured automatically. It is recommended that you configure one via
* {@link #setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)}.
* </p>
*
* @author Rob Winch
* @author Joe Grandja
* @author Phil Clay
* @since 5.1
*/
public final class ServerOAuth2AuthorizedClientExchangeFilterFunction implements ExchangeFilterFunction {
/**
* The request attribute name used to locate the {@link OAuth2AuthorizedClient}.
*/
private static final String OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME = OAuth2AuthorizedClient.class.getName();
/**
* The client request attribute name used to locate the
* {@link ClientRegistration#getRegistrationId()}
*/
private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = OAuth2AuthorizedClient.class.getName()
.concat(".CLIENT_REGISTRATION_ID");
/**
* The request attribute name used to locate the
* {@link org.springframework.web.server.ServerWebExchange}.
*/
private static final String SERVER_WEB_EXCHANGE_ATTR_NAME = ServerWebExchange.class.getName();
private static final AnonymousAuthenticationToken ANONYMOUS_USER_TOKEN = new AnonymousAuthenticationToken(
"anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_USER"));
private final Mono<Authentication> currentAuthenticationMono = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication).defaultIfEmpty(ANONYMOUS_USER_TOKEN);
// @formatter:off
private final Mono<String> clientRegistrationIdMono = this.currentAuthenticationMono
.filter((t) -> this.defaultOAuth2AuthorizedClient && t instanceof OAuth2AuthenticationToken)
.cast(OAuth2AuthenticationToken.class)
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
// @formatter:on
// @formatter:off
private final Mono<ServerWebExchange> currentServerWebExchangeMono = Mono.deferContextual(Mono::just)
.filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class));
// @formatter:on
private final ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
private boolean defaultOAuth2AuthorizedClient;
private String defaultClientRegistrationId;
private ClientResponseHandler clientResponseHandler;
/**
* Constructs a {@code ServerOAuth2AuthorizedClientExchangeFilterFunction} using the
* provided parameters.
*
* <p>
* When this constructor is used, authentication (HTTP 401) and authorization (HTTP
* 403) failures returned from a OAuth 2.0 Resource Server will <em>NOT</em> be
* forwarded to a {@link ReactiveOAuth2AuthorizationFailureHandler}. Therefore, future
* requests to the Resource Server will most likely use the same (most likely invalid)
* token, resulting in the same errors returned from the Resource Server. It is
* recommended to configure a
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler)}
* so that authentication and authorization failures returned from a Resource Server
* will result in removing the authorized client, so that a new token is retrieved for
* future requests.
* </p>
* @param authorizedClientManager the {@link ReactiveOAuth2AuthorizedClientManager}
* which manages the authorized client(s)
* @since 5.2
*/
public ServerOAuth2AuthorizedClientExchangeFilterFunction(
ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
Assert.notNull(authorizedClientManager, "authorizedClientManager cannot be null");
this.authorizedClientManager = authorizedClientManager;
this.clientResponseHandler = (request, responseMono) -> responseMono;
}
/**
* Constructs a {@code ServerOAuth2AuthorizedClientExchangeFilterFunction} using the
* provided parameters.
*
* <p>
* Since 5.3, when this constructor is used, authentication (HTTP 401) and
* authorization (HTTP 403) failures returned from an OAuth 2.0 Resource Server will
* be forwarded to a
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler}, which will
* potentially remove the {@link OAuth2AuthorizedClient} from the given
* {@link ServerOAuth2AuthorizedClientRepository}, depending on the OAuth 2.0 error
* code returned. Authentication failures returned from an OAuth 2.0 Resource Server
* typically indicate that the token is invalid, and should not be used in future
* requests. Removing the authorized client from the repository will ensure that the
* existing token will not be sent for future requests to the Resource Server, and a
* new token is retrieved from Authorization Server and used for future requests to
* the Resource Server.
* </p>
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public ServerOAuth2AuthorizedClientExchangeFilterFunction(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler = new RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> authorizedClientRepository.removeAuthorizedClient(
clientRegistrationId, principal,
(ServerWebExchange) attributes.get(ServerWebExchange.class.getName())));
this.authorizedClientManager = createDefaultAuthorizedClientManager(clientRegistrationRepository,
authorizedClientRepository, authorizationFailureHandler);
this.clientResponseHandler = new AuthorizationFailureForwarder(authorizationFailureHandler);
}
private static ReactiveOAuth2AuthorizedClientManager createDefaultAuthorizedClientManager(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository,
ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
// gh-7544
DefaultReactiveOAuth2AuthorizedClientManager authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
authorizedClientManager.setAuthorizationFailureHandler(authorizationFailureHandler);
return authorizedClientManager;
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link OAuth2AuthorizedClient} to be used for providing the Bearer Token. Example
* usage:
*
* <pre>
* WebClient webClient = WebClient.builder()
* .filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager))
* .build();
* Mono<String> response = webClient
* .get()
* .uri(uri)
* .attributes(oauth2AuthorizedClient(authorizedClient))
* // ...
* .retrieve()
* .bodyToMono(String.class);
* </pre>
*
* An attempt to automatically refresh the token will be made if all of the following
* are true:
*
* <ul>
* <li>A refresh token is present on the OAuth2AuthorizedClient</li>
* <li>The access token will be expired in 1 minute (the default)</li>
* <li>The {@link ReactiveSecurityContextHolder} will be used to attempt to save the
* token. If it is empty, then the principal name on the OAuth2AuthorizedClient will
* be used to create an Authentication for saving.</li>
* </ul>
* @param authorizedClient the {@link OAuth2AuthorizedClient} to use.
* @return the {@link Consumer} to populate the
*/
public static Consumer<Map<String, Object>> oauth2AuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
return (attributes) -> attributes.put(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME, authorizedClient);
}
private static OAuth2AuthorizedClient oauth2AuthorizedClient(ClientRequest request) {
return (OAuth2AuthorizedClient) request.attributes().get(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME);
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link ServerWebExchange} to be used for providing the Bearer Token. Example usage:
*
* <pre>
* WebClient webClient = WebClient.builder()
* .filter(new ServerOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager))
* .build();
* Mono<String> response = webClient
* .get()
* .uri(uri)
* .attributes(serverWebExchange(serverWebExchange))
* // ...
* .retrieve()
* .bodyToMono(String.class);
* </pre>
* @param serverWebExchange the {@link ServerWebExchange} to use
* @return the {@link Consumer} to populate the client request attributes
*/
public static Consumer<Map<String, Object>> serverWebExchange(ServerWebExchange serverWebExchange) {
return (attributes) -> attributes.put(SERVER_WEB_EXCHANGE_ATTR_NAME, serverWebExchange);
}
private static ServerWebExchange serverWebExchange(ClientRequest request) {
return (ServerWebExchange) request.attributes().get(SERVER_WEB_EXCHANGE_ATTR_NAME);
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link ClientRegistration#getRegistrationId()} to be used to look up the
* {@link OAuth2AuthorizedClient}.
* @param clientRegistrationId the {@link ClientRegistration#getRegistrationId()} to
* be used to look up the {@link OAuth2AuthorizedClient}.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) {
return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
}
private static String clientRegistrationId(ClientRequest request) {
OAuth2AuthorizedClient authorizedClient = oauth2AuthorizedClient(request);
if (authorizedClient != null) {
return authorizedClient.getClientRegistration().getRegistrationId();
}
return (String) request.attributes().get(CLIENT_REGISTRATION_ID_ATTR_NAME);
}
/**
* If true, a default {@link OAuth2AuthorizedClient} can be discovered from the
* current Authentication. It is recommended to be cautious with this feature since
* all HTTP requests will receive the access token if it can be resolved from the
* current Authentication.
* @param defaultOAuth2AuthorizedClient true if a default
* {@link OAuth2AuthorizedClient} should be used, else false. Default is false.
*/
public void setDefaultOAuth2AuthorizedClient(boolean defaultOAuth2AuthorizedClient) {
this.defaultOAuth2AuthorizedClient = defaultOAuth2AuthorizedClient;
}
/**
* If set, will be used as the default {@link ClientRegistration#getRegistrationId()}.
* It is recommended to be cautious with this feature since all HTTP requests will
* receive the access token.
* @param clientRegistrationId the id to use
*/
public void setDefaultClientRegistrationId(String clientRegistrationId) {
this.defaultClientRegistrationId = clientRegistrationId;
}
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
// @formatter:off
return authorizedClient(request)
.map((authorizedClient) -> bearer(request, authorizedClient))
.flatMap((requestWithBearer) -> exchangeAndHandleResponse(requestWithBearer, next))
.switchIfEmpty(Mono.defer(() -> exchangeAndHandleResponse(request, next)));
// @formatter:on
}
private Mono<ClientResponse> exchangeAndHandleResponse(ClientRequest request, ExchangeFunction next) {
return next.exchange(request)
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
}
private Mono<OAuth2AuthorizedClient> authorizedClient(ClientRequest request) {
OAuth2AuthorizedClient authorizedClientFromAttrs = oauth2AuthorizedClient(request);
// @formatter:off
return Mono.justOrEmpty(authorizedClientFromAttrs)
.switchIfEmpty(Mono.defer(() -> authorizeRequest(request)
.flatMap(this.authorizedClientManager::authorize))
)
.flatMap((authorizedClient) -> reauthorizeRequest(request, authorizedClient)
.flatMap(this.authorizedClientManager::authorize)
);
// @formatter:on
}
private Mono<OAuth2AuthorizeRequest> authorizeRequest(ClientRequest request) {
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
// @formatter:off
return Mono.zip(clientRegistrationId, this.currentAuthenticationMono, serverWebExchange)
.map((t3) -> {
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest
.withClientRegistrationId(t3.getT1())
.principal(t3.getT2());
t3.getT3().ifPresent((exchange) -> builder.attribute(ServerWebExchange.class.getName(), exchange));
return builder.build();
});
// @formatter:on
}
/**
* Returns a {@link Mono} the emits the {@code clientRegistrationId} that is active
* for the given request.
* @param request the request for which to retrieve the {@code clientRegistrationId}
* @return a mono that emits the {@code clientRegistrationId} that is active for the
* given request.
*/
private Mono<String> effectiveClientRegistrationId(ClientRequest request) {
// @formatter:off
return Mono.justOrEmpty(clientRegistrationId(request))
.switchIfEmpty(Mono.justOrEmpty(this.defaultClientRegistrationId))
.switchIfEmpty(this.clientRegistrationIdMono);
// @formatter:on
}
/**
* Returns a {@link Mono} that emits an {@link Optional} for the
* {@link ServerWebExchange} that is active for the given request.
*
* <p>
* The returned {@link Mono} will never complete empty. Instead, it will emit an empty
* {@link Optional} if no exchange is active.
* </p>
* @param request the request for which to retrieve the exchange
* @return a {@link Mono} that emits an {@link Optional} for the
* {@link ServerWebExchange} that is active for the given request.
*/
private Mono<Optional<ServerWebExchange>> effectiveServerWebExchange(ClientRequest request) {
// @formatter:off
return Mono.justOrEmpty(serverWebExchange(request))
.switchIfEmpty(this.currentServerWebExchangeMono)
.map(Optional::of)
.defaultIfEmpty(Optional.empty());
// @formatter:on
}
private Mono<OAuth2AuthorizeRequest> reauthorizeRequest(ClientRequest request,
OAuth2AuthorizedClient authorizedClient) {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
// @formatter:off
return Mono.zip(this.currentAuthenticationMono, serverWebExchange)
.map((t2) -> {
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient)
.principal(t2.getT1());
t2.getT2().ifPresent((exchange) -> builder.attribute(ServerWebExchange.class.getName(), exchange));
return builder.build();
});
// @formatter:on
}
private ClientRequest bearer(ClientRequest request, OAuth2AuthorizedClient authorizedClient) {
// @formatter:off
return ClientRequest.from(request)
.headers((headers) -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue()))
.build();
// @formatter:on
}
/**
* Sets the handler that handles authentication and authorization failures when
* communicating to the OAuth 2.0 Resource Server.
*
* <p>
* For example, a
* {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is
* typically used to remove the cached {@link OAuth2AuthorizedClient}, so that the
* same token is no longer used in future requests to the Resource Server.
* </p>
*
* <p>
* The failure handler used by default depends on which constructor was used to
* construct this {@link ServerOAuth2AuthorizedClientExchangeFilterFunction}. See the
* constructors for more details.
* </p>
* @param authorizationFailureHandler the handler that handles authentication and
* authorization failures.
* @since 5.3
*/
public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.clientResponseHandler = new AuthorizationFailureForwarder(authorizationFailureHandler);
}
@FunctionalInterface
private interface ClientResponseHandler {
Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> response);
}
/**
* Forwards authentication and authorization failures to a
* {@link ReactiveOAuth2AuthorizationFailureHandler}.
*
* @since 5.3
*/
private final class AuthorizationFailureForwarder implements ClientResponseHandler {
/**
* A map of HTTP Status Code to OAuth 2.0 Error codes for HTTP status codes that
* should be interpreted as authentication or authorization failures.
*/
private final Map<Integer, String> httpStatusToOAuth2ErrorCodeMap;
/**
* The {@link ReactiveOAuth2AuthorizationFailureHandler} to notify when an
* authentication/authorization failure occurs.
*/
private final ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
private AuthorizationFailureForwarder(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
Map<Integer, String> httpStatusToOAuth2Error = new HashMap<>();
httpStatusToOAuth2Error.put(HttpStatus.UNAUTHORIZED.value(), OAuth2ErrorCodes.INVALID_TOKEN);
httpStatusToOAuth2Error.put(HttpStatus.FORBIDDEN.value(), OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
this.httpStatusToOAuth2ErrorCodeMap = Collections.unmodifiableMap(httpStatusToOAuth2Error);
}
@Override
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
// @formatter:off
return responseMono
.flatMap((response) -> handleResponse(request, response).thenReturn(response))
.onErrorResume(WebClientResponseException.class,
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e))
)
.onErrorResume(OAuth2AuthorizationException.class,
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
// @formatter:on
}
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
// @formatter:off
return Mono.justOrEmpty(resolveErrorIfPossible(response))
.flatMap((oauth2Error) -> {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange, clientRegistrationId)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
new ClientAuthorizationException(oauth2Error, zipped.getT3())));
});
// @formatter:on
}
private OAuth2Error resolveErrorIfPossible(ClientResponse response) {
// Try to resolve from 'WWW-Authenticate' header
if (!response.headers().header(HttpHeaders.WWW_AUTHENTICATE).isEmpty()) {
String wwwAuthenticateHeader = response.headers().header(HttpHeaders.WWW_AUTHENTICATE).get(0);
Map<String, String> authParameters = parseAuthParameters(wwwAuthenticateHeader);
if (authParameters.containsKey(OAuth2ParameterNames.ERROR)) {
return new OAuth2Error(authParameters.get(OAuth2ParameterNames.ERROR),
authParameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION),
authParameters.get(OAuth2ParameterNames.ERROR_URI));
}
}
return resolveErrorIfPossible(response.statusCode().value());
}
private OAuth2Error resolveErrorIfPossible(int statusCode) {
if (this.httpStatusToOAuth2ErrorCodeMap.containsKey(statusCode)) {
return new OAuth2Error(this.httpStatusToOAuth2ErrorCodeMap.get(statusCode), null,
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
return null;
}
private Map<String, String> parseAuthParameters(String wwwAuthenticateHeader) {
// @formatter:off
return Stream.of(wwwAuthenticateHeader)
.filter((header) -> StringUtils.hasLength(header))
.filter((header) -> header.toLowerCase().startsWith("bearer"))
.map((header) -> header.substring("bearer".length()))
.map((header) -> header.split(","))
.flatMap(Stream::of)
.map((parameter) -> parameter.split("="))
.filter((parameter) -> parameter.length > 1)
.collect(Collectors.toMap((parameters) -> parameters[0].trim(),
(parameters) -> parameters[1].trim().replace("\"", ""))
);
// @formatter:on
}
/**
* Handles the given http status code returned from a resource server by notifying
* the authorization failure handler if the http status code is in the
* {@link #httpStatusToOAuth2ErrorCodeMap}.
* @param request the request being processed
* @param exception The root cause exception for the failure
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleWebClientResponseException(ClientRequest request,
WebClientResponseException exception) {
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap((oauth2Error) -> {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange, clientRegistrationId)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
new ClientAuthorizationException(oauth2Error, zipped.getT3(), exception)));
});
}
/**
* Handles the given OAuth2AuthorizationException that occurred downstream by
* notifying the authorization failure handler.
* @param request the request being processed
* @param exception the authorization exception to include in the failure event.
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleAuthorizationException(ClientRequest request, OAuth2AuthorizationException exception) {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), exception));
}
/**
* Delegates to the authorization failure handler of the failed authorization.
* @param principal the principal associated with the failed authorization attempt
* @param exchange the currently active exchange
* @param exception the authorization exception to include in the failure event.
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleAuthorizationFailure(Authentication principal, Optional<ServerWebExchange> exchange,
OAuth2AuthorizationException exception) {
return this.authorizationFailureHandler.onAuthorizationFailure(exception, principal,
createAttributes(exchange.orElse(null)));
}
private Map<String, Object> createAttributes(ServerWebExchange exchange) {
if (exchange == null) {
return Collections.emptyMap();
}
return Collections.singletonMap(ServerWebExchange.class.getName(), exchange);
}
}
}
| 28,078 | 44.656911 | 142 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.reactive.function.client;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.util.context.Context;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.client.ClientAuthorizationException;
import org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
/**
* Provides an easy mechanism for using an {@link OAuth2AuthorizedClient} to make OAuth
* 2.0 requests by including the {@link OAuth2AuthorizedClient#getAccessToken() access
* token} as a bearer token.
*
* <p>
* <b>NOTE:</b>This class is intended to be used in a {@code Servlet} environment.
*
* <p>
* Example usage:
*
* <pre>
* ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
* WebClient webClient = WebClient.builder()
* .apply(oauth2.oauth2Configuration())
* .build();
* Mono<String> response = webClient
* .get()
* .uri(uri)
* .attributes(oauth2AuthorizedClient(authorizedClient))
* // ...
* .retrieve()
* .bodyToMono(String.class);
* </pre>
*
* <h3>Authentication and Authorization Failures</h3>
*
* <p>
* Since 5.3, this filter function has the ability to forward authentication (HTTP 401
* Unauthorized) and authorization (HTTP 403 Forbidden) failures from an OAuth 2.0
* Resource Server to a {@link OAuth2AuthorizationFailureHandler}. A
* {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} can be used to remove
* the cached {@link OAuth2AuthorizedClient}, so that future requests will result in a new
* token being retrieved from an Authorization Server, and sent to the Resource Server.
*
* <p>
* If the
* {@link #ServletOAuth2AuthorizedClientExchangeFilterFunction(ClientRegistrationRepository, OAuth2AuthorizedClientRepository)}
* constructor is used, a {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler}
* will be configured automatically.
*
* <p>
* If the
* {@link #ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager)}
* constructor is used, a {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler}
* will <em>NOT</em> be configured automatically. It is recommended that you configure one
* via {@link #setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)}.
*
* @author Rob Winch
* @author Joe Grandja
* @author Roman Matiushchenko
* @since 5.1
* @see OAuth2AuthorizedClientManager
* @see DefaultOAuth2AuthorizedClientManager
* @see OAuth2AuthorizedClientProvider
* @see OAuth2AuthorizedClientProviderBuilder
*/
public final class ServletOAuth2AuthorizedClientExchangeFilterFunction implements ExchangeFilterFunction {
// Same key as in
// SecurityReactorContextConfiguration.SecurityReactorContextSubscriber.SECURITY_CONTEXT_ATTRIBUTES
static final String SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES";
/**
* The request attribute name used to locate the {@link OAuth2AuthorizedClient}.
*/
private static final String OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME = OAuth2AuthorizedClient.class.getName();
private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = OAuth2AuthorizedClient.class.getName()
.concat(".CLIENT_REGISTRATION_ID");
private static final String AUTHENTICATION_ATTR_NAME = Authentication.class.getName();
private static final String HTTP_SERVLET_REQUEST_ATTR_NAME = HttpServletRequest.class.getName();
private static final String HTTP_SERVLET_RESPONSE_ATTR_NAME = HttpServletResponse.class.getName();
private static final Authentication ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken("anonymous",
"anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private OAuth2AuthorizedClientManager authorizedClientManager;
private boolean defaultOAuth2AuthorizedClient;
private String defaultClientRegistrationId;
private ClientResponseHandler clientResponseHandler;
public ServletOAuth2AuthorizedClientExchangeFilterFunction() {
}
/**
* Constructs a {@code ServletOAuth2AuthorizedClientExchangeFilterFunction} using the
* provided parameters.
*
* <p>
* When this constructor is used, authentication (HTTP 401) and authorization (HTTP
* 403) failures returned from an OAuth 2.0 Resource Server will <em>NOT</em> be
* forwarded to an {@link OAuth2AuthorizationFailureHandler}. Therefore, future
* requests to the Resource Server will most likely use the same (likely invalid)
* token, resulting in the same errors returned from the Resource Server. It is
* recommended to configure a
* {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} via
* {@link #setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler)} so that
* authentication and authorization failures returned from a Resource Server will
* result in removing the authorized client, so that a new token is retrieved for
* future requests.
* @param authorizedClientManager the {@link OAuth2AuthorizedClientManager} which
* manages the authorized client(s)
* @since 5.2
*/
public ServletOAuth2AuthorizedClientExchangeFilterFunction(OAuth2AuthorizedClientManager authorizedClientManager) {
Assert.notNull(authorizedClientManager, "authorizedClientManager cannot be null");
this.authorizedClientManager = authorizedClientManager;
this.clientResponseHandler = (request, responseMono) -> responseMono;
}
/**
* Constructs a {@code ServletOAuth2AuthorizedClientExchangeFilterFunction} using the
* provided parameters.
*
* <p>
* Since 5.3, when this constructor is used, authentication (HTTP 401) and
* authorization (HTTP 403) failures returned from an OAuth 2.0 Resource Server will
* be forwarded to a {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler},
* which will potentially remove the {@link OAuth2AuthorizedClient} from the given
* {@link OAuth2AuthorizedClientRepository}, depending on the OAuth 2.0 error code
* returned. Authentication failures returned from an OAuth 2.0 Resource Server
* typically indicate that the token is invalid, and should not be used in future
* requests. Removing the authorized client from the repository will ensure that the
* existing token will not be sent for future requests to the Resource Server, and a
* new token is retrieved from the Authorization Server and used for future requests
* to the Resource Server.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public ServletOAuth2AuthorizedClientExchangeFilterFunction(
ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
OAuth2AuthorizationFailureHandler authorizationFailureHandler = new RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(
(clientRegistrationId, principal, attributes) -> removeAuthorizedClient(authorizedClientRepository,
clientRegistrationId, principal, attributes));
DefaultOAuth2AuthorizedClientManager defaultAuthorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
clientRegistrationRepository, authorizedClientRepository);
defaultAuthorizedClientManager.setAuthorizationFailureHandler(authorizationFailureHandler);
this.authorizedClientManager = defaultAuthorizedClientManager;
this.clientResponseHandler = new AuthorizationFailureForwarder(authorizationFailureHandler);
}
private void removeAuthorizedClient(OAuth2AuthorizedClientRepository authorizedClientRepository,
String clientRegistrationId, Authentication principal, Map<String, Object> attributes) {
HttpServletRequest request = getRequest(attributes);
HttpServletResponse response = getResponse(attributes);
authorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal, request, response);
}
/**
* If true, a default {@link OAuth2AuthorizedClient} can be discovered from the
* current Authentication. It is recommended to be cautious with this feature since
* all HTTP requests will receive the access token if it can be resolved from the
* current Authentication.
* @param defaultOAuth2AuthorizedClient true if a default
* {@link OAuth2AuthorizedClient} should be used, else false. Default is false.
*/
public void setDefaultOAuth2AuthorizedClient(boolean defaultOAuth2AuthorizedClient) {
this.defaultOAuth2AuthorizedClient = defaultOAuth2AuthorizedClient;
}
/**
* If set, will be used as the default {@link ClientRegistration#getRegistrationId()}.
* It is recommended to be cautious with this feature since all HTTP requests will
* receive the access token.
* @param clientRegistrationId the id to use
*/
public void setDefaultClientRegistrationId(String clientRegistrationId) {
this.defaultClientRegistrationId = clientRegistrationId;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
/**
* Configures the builder with {@link #defaultRequest()} and adds this as a
* {@link ExchangeFilterFunction}
* @return the {@link Consumer} to configure the builder
*/
public Consumer<WebClient.Builder> oauth2Configuration() {
return (builder) -> builder.defaultRequest(defaultRequest()).filter(this);
}
/**
* Provides defaults for the {@link HttpServletRequest} and the
* {@link HttpServletResponse} using {@link RequestContextHolder}. It also provides
* defaults for the {@link Authentication} using {@link SecurityContextHolder}. It
* also can default the {@link OAuth2AuthorizedClient} using the
* {@link #clientRegistrationId(String)} or the
* {@link #authentication(Authentication)}.
* @return the {@link Consumer} to populate the attributes
*/
public Consumer<WebClient.RequestHeadersSpec<?>> defaultRequest() {
return (spec) -> spec.attributes((attrs) -> {
populateDefaultRequestResponse(attrs);
populateDefaultAuthentication(attrs);
});
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link OAuth2AuthorizedClient} to be used for providing the Bearer Token.
* @param authorizedClient the {@link OAuth2AuthorizedClient} to use.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> oauth2AuthorizedClient(OAuth2AuthorizedClient authorizedClient) {
return (attributes) -> {
if (authorizedClient == null) {
attributes.remove(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME);
}
else {
attributes.put(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME, authorizedClient);
}
};
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link ClientRegistration#getRegistrationId()} to be used to look up the
* {@link OAuth2AuthorizedClient}.
* @param clientRegistrationId the {@link ClientRegistration#getRegistrationId()} to
* be used to look up the {@link OAuth2AuthorizedClient}.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) {
return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link Authentication} used to look up and save the {@link OAuth2AuthorizedClient}.
* The value is defaulted in
* {@link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest()}
* @param authentication the {@link Authentication} to use.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> authentication(Authentication authentication) {
return (attributes) -> attributes.put(AUTHENTICATION_ATTR_NAME, authentication);
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link HttpServletRequest} used to look up and save the
* {@link OAuth2AuthorizedClient}. The value is defaulted in
* {@link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest()}
* @param request the {@link HttpServletRequest} to use.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> httpServletRequest(HttpServletRequest request) {
return (attributes) -> attributes.put(HTTP_SERVLET_REQUEST_ATTR_NAME, request);
}
/**
* Modifies the {@link ClientRequest#attributes()} to include the
* {@link HttpServletResponse} used to save the {@link OAuth2AuthorizedClient}. The
* value is defaulted in
* {@link ServletOAuth2AuthorizedClientExchangeFilterFunction#defaultRequest()}
* @param response the {@link HttpServletResponse} to use.
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> httpServletResponse(HttpServletResponse response) {
return (attributes) -> attributes.put(HTTP_SERVLET_RESPONSE_ATTR_NAME, response);
}
/**
* Sets the {@link OAuth2AuthorizationFailureHandler} that handles authentication and
* authorization failures when communicating to the OAuth 2.0 Resource Server.
*
* <p>
* For example, a {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} is
* typically used to remove the cached {@link OAuth2AuthorizedClient}, so that the
* same token is no longer used in future requests to the Resource Server.
*
* <p>
* The failure handler used by default depends on which constructor was used to
* construct this {@link ServletOAuth2AuthorizedClientExchangeFilterFunction}. See the
* constructors for more details.
* @param authorizationFailureHandler the {@link OAuth2AuthorizationFailureHandler}
* that handles authentication and authorization failures
* @since 5.3
*/
public void setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.clientResponseHandler = new AuthorizationFailureForwarder(authorizationFailureHandler);
}
@Override
public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) {
// @formatter:off
return mergeRequestAttributesIfNecessary(request)
.filter((req) -> req.attribute(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME).isPresent())
.flatMap((req) -> reauthorizeClient(getOAuth2AuthorizedClient(req.attributes()), req))
.switchIfEmpty(
Mono.defer(() ->
mergeRequestAttributesIfNecessary(request)
.filter((req) -> resolveClientRegistrationId(req) != null)
.flatMap((req) -> authorizeClient(resolveClientRegistrationId(req), req))
)
)
.map((authorizedClient) -> bearer(request, authorizedClient))
.flatMap((requestWithBearer) -> exchangeAndHandleResponse(requestWithBearer, next))
.switchIfEmpty(Mono.defer(() -> exchangeAndHandleResponse(request, next)));
// @formatter:on
}
private Mono<ClientResponse> exchangeAndHandleResponse(ClientRequest request, ExchangeFunction next) {
return next.exchange(request)
.transform((responseMono) -> this.clientResponseHandler.handleResponse(request, responseMono));
}
private Mono<ClientRequest> mergeRequestAttributesIfNecessary(ClientRequest request) {
if (!request.attribute(HTTP_SERVLET_REQUEST_ATTR_NAME).isPresent()
|| !request.attribute(HTTP_SERVLET_RESPONSE_ATTR_NAME).isPresent()
|| !request.attribute(AUTHENTICATION_ATTR_NAME).isPresent()) {
return mergeRequestAttributesFromContext(request);
}
return Mono.just(request);
}
private Mono<ClientRequest> mergeRequestAttributesFromContext(ClientRequest request) {
ClientRequest.Builder builder = ClientRequest.from(request);
return Mono.deferContextual(Mono::just).cast(Context.class)
.map((ctx) -> builder.attributes((attrs) -> populateRequestAttributes(attrs, ctx)))
.map(ClientRequest.Builder::build);
}
private void populateRequestAttributes(Map<String, Object> attrs, Context ctx) {
// NOTE: SecurityReactorContextConfiguration.SecurityReactorContextSubscriber adds
// this key
if (!ctx.hasKey(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY)) {
return;
}
Map<Object, Object> contextAttributes = ctx.get(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY);
HttpServletRequest servletRequest = (HttpServletRequest) contextAttributes.get(HttpServletRequest.class);
if (servletRequest != null) {
attrs.putIfAbsent(HTTP_SERVLET_REQUEST_ATTR_NAME, servletRequest);
}
HttpServletResponse servletResponse = (HttpServletResponse) contextAttributes.get(HttpServletResponse.class);
if (servletResponse != null) {
attrs.putIfAbsent(HTTP_SERVLET_RESPONSE_ATTR_NAME, servletResponse);
}
Authentication authentication = (Authentication) contextAttributes.get(Authentication.class);
if (authentication != null) {
attrs.putIfAbsent(AUTHENTICATION_ATTR_NAME, authentication);
}
}
private void populateDefaultRequestResponse(Map<String, Object> attrs) {
if (attrs.containsKey(HTTP_SERVLET_REQUEST_ATTR_NAME) && attrs.containsKey(HTTP_SERVLET_RESPONSE_ATTR_NAME)) {
return;
}
RequestAttributes context = RequestContextHolder.getRequestAttributes();
if (context instanceof ServletRequestAttributes) {
attrs.putIfAbsent(HTTP_SERVLET_REQUEST_ATTR_NAME, ((ServletRequestAttributes) context).getRequest());
attrs.putIfAbsent(HTTP_SERVLET_RESPONSE_ATTR_NAME, ((ServletRequestAttributes) context).getResponse());
}
}
private void populateDefaultAuthentication(Map<String, Object> attrs) {
if (attrs.containsKey(AUTHENTICATION_ATTR_NAME)) {
return;
}
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
attrs.putIfAbsent(AUTHENTICATION_ATTR_NAME, authentication);
}
private String resolveClientRegistrationId(ClientRequest request) {
Map<String, Object> attrs = request.attributes();
String clientRegistrationId = getClientRegistrationId(attrs);
if (clientRegistrationId == null) {
clientRegistrationId = this.defaultClientRegistrationId;
}
Authentication authentication = getAuthentication(attrs);
if (clientRegistrationId == null && this.defaultOAuth2AuthorizedClient
&& authentication instanceof OAuth2AuthenticationToken) {
clientRegistrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId();
}
return clientRegistrationId;
}
private Mono<OAuth2AuthorizedClient> authorizeClient(String clientRegistrationId, ClientRequest request) {
if (this.authorizedClientManager == null) {
return Mono.empty();
}
Map<String, Object> attrs = request.attributes();
Authentication authentication = getAuthentication(attrs);
if (authentication == null) {
authentication = ANONYMOUS_AUTHENTICATION;
}
HttpServletRequest servletRequest = getRequest(attrs);
HttpServletResponse servletResponse = getResponse(attrs);
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withClientRegistrationId(clientRegistrationId)
.principal(authentication);
builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
OAuth2AuthorizeRequest authorizeRequest = builder.build();
// NOTE: 'authorizedClientManager.authorize()' needs to be executed on a dedicated
// thread via subscribeOn(Schedulers.boundedElastic()) since it performs a
// blocking I/O operation using RestTemplate internally
return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(authorizeRequest))
.subscribeOn(Schedulers.boundedElastic());
}
private Mono<OAuth2AuthorizedClient> reauthorizeClient(OAuth2AuthorizedClient authorizedClient,
ClientRequest request) {
if (this.authorizedClientManager == null) {
return Mono.just(authorizedClient);
}
Map<String, Object> attrs = request.attributes();
Authentication authentication = getAuthentication(attrs);
if (authentication == null) {
authentication = createAuthentication(authorizedClient.getPrincipalName());
}
HttpServletRequest servletRequest = getRequest(attrs);
HttpServletResponse servletResponse = getResponse(attrs);
OAuth2AuthorizeRequest.Builder builder = OAuth2AuthorizeRequest.withAuthorizedClient(authorizedClient)
.principal(authentication);
builder.attributes((attributes) -> addToAttributes(attributes, servletRequest, servletResponse));
OAuth2AuthorizeRequest reauthorizeRequest = builder.build();
// NOTE: 'authorizedClientManager.authorize()' needs to be executed on a dedicated
// thread via subscribeOn(Schedulers.boundedElastic()) since it performs a
// blocking I/O operation using RestTemplate internally
return Mono.fromSupplier(() -> this.authorizedClientManager.authorize(reauthorizeRequest))
.subscribeOn(Schedulers.boundedElastic());
}
private void addToAttributes(Map<String, Object> attributes, HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
if (servletRequest != null) {
attributes.put(HTTP_SERVLET_REQUEST_ATTR_NAME, servletRequest);
}
if (servletResponse != null) {
attributes.put(HTTP_SERVLET_RESPONSE_ATTR_NAME, servletResponse);
}
}
private ClientRequest bearer(ClientRequest request, OAuth2AuthorizedClient authorizedClient) {
// @formatter:off
return ClientRequest.from(request)
.headers((headers) -> headers.setBearerAuth(authorizedClient.getAccessToken().getTokenValue()))
.attributes(oauth2AuthorizedClient(authorizedClient))
.build();
// @formatter:on
}
static OAuth2AuthorizedClient getOAuth2AuthorizedClient(Map<String, Object> attrs) {
return (OAuth2AuthorizedClient) attrs.get(OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME);
}
static String getClientRegistrationId(Map<String, Object> attrs) {
return (String) attrs.get(CLIENT_REGISTRATION_ID_ATTR_NAME);
}
static Authentication getAuthentication(Map<String, Object> attrs) {
return (Authentication) attrs.get(AUTHENTICATION_ATTR_NAME);
}
static HttpServletRequest getRequest(Map<String, Object> attrs) {
return (HttpServletRequest) attrs.get(HTTP_SERVLET_REQUEST_ATTR_NAME);
}
static HttpServletResponse getResponse(Map<String, Object> attrs) {
return (HttpServletResponse) attrs.get(HTTP_SERVLET_RESPONSE_ATTR_NAME);
}
private static Authentication createAuthentication(final String principalName) {
Assert.hasText(principalName, "principalName cannot be empty");
return new AbstractAuthenticationToken(null) {
@Override
public Object getCredentials() {
return "";
}
@Override
public Object getPrincipal() {
return principalName;
}
};
}
@FunctionalInterface
private interface ClientResponseHandler {
Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> response);
}
/**
* Forwards authentication and authorization failures to an
* {@link OAuth2AuthorizationFailureHandler}.
*
* @since 5.3
*/
private static final class AuthorizationFailureForwarder implements ClientResponseHandler {
/**
* A map of HTTP status code to OAuth 2.0 error code for HTTP status codes that
* should be interpreted as authentication or authorization failures.
*/
private final Map<Integer, String> httpStatusToOAuth2ErrorCodeMap;
/**
* The {@link OAuth2AuthorizationFailureHandler} to notify when an
* authentication/authorization failure occurs.
*/
private final OAuth2AuthorizationFailureHandler authorizationFailureHandler;
private AuthorizationFailureForwarder(OAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
Map<Integer, String> httpStatusToOAuth2Error = new HashMap<>();
httpStatusToOAuth2Error.put(HttpStatus.UNAUTHORIZED.value(), OAuth2ErrorCodes.INVALID_TOKEN);
httpStatusToOAuth2Error.put(HttpStatus.FORBIDDEN.value(), OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
this.httpStatusToOAuth2ErrorCodeMap = Collections.unmodifiableMap(httpStatusToOAuth2Error);
}
@Override
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
return responseMono.flatMap((response) -> handleResponse(request, response).thenReturn(response))
.onErrorResume(WebClientResponseException.class,
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e)))
.onErrorResume(OAuth2AuthorizationException.class,
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
}
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
// @formatter:off
return Mono.justOrEmpty(resolveErrorIfPossible(response))
.flatMap((oauth2Error) -> {
Map<String, Object> attrs = request.attributes();
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
if (authorizedClient == null) {
return Mono.empty();
}
ClientAuthorizationException authorizationException = new ClientAuthorizationException(oauth2Error,
authorizedClient.getClientRegistration().getRegistrationId());
Authentication principal = createAuthentication(authorizedClient.getPrincipalName());
HttpServletRequest servletRequest = getRequest(attrs);
HttpServletResponse servletResponse = getResponse(attrs);
return handleAuthorizationFailure(authorizationException, principal, servletRequest, servletResponse);
});
// @formatter:on
}
private OAuth2Error resolveErrorIfPossible(ClientResponse response) {
// Try to resolve from 'WWW-Authenticate' header
if (!response.headers().header(HttpHeaders.WWW_AUTHENTICATE).isEmpty()) {
String wwwAuthenticateHeader = response.headers().header(HttpHeaders.WWW_AUTHENTICATE).get(0);
Map<String, String> authParameters = parseAuthParameters(wwwAuthenticateHeader);
if (authParameters.containsKey(OAuth2ParameterNames.ERROR)) {
return new OAuth2Error(authParameters.get(OAuth2ParameterNames.ERROR),
authParameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION),
authParameters.get(OAuth2ParameterNames.ERROR_URI));
}
}
return resolveErrorIfPossible(response.statusCode().value());
}
private OAuth2Error resolveErrorIfPossible(int statusCode) {
if (this.httpStatusToOAuth2ErrorCodeMap.containsKey(statusCode)) {
return new OAuth2Error(this.httpStatusToOAuth2ErrorCodeMap.get(statusCode), null,
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
return null;
}
private Map<String, String> parseAuthParameters(String wwwAuthenticateHeader) {
// @formatter:off
return Stream.of(wwwAuthenticateHeader).filter((header) -> StringUtils.hasLength(header))
.filter((header) -> header.toLowerCase().startsWith("bearer"))
.map((header) -> header.substring("bearer".length()))
.map((header) -> header.split(","))
.flatMap(Stream::of)
.map((parameter) -> parameter.split("="))
.filter((parameter) -> parameter.length > 1)
.collect(Collectors.toMap((parameters) -> parameters[0].trim(),
(parameters) -> parameters[1].trim().replace("\"", ""))
);
// @formatter:on
}
/**
* Handles the given http status code returned from a resource server by notifying
* the authorization failure handler if the http status code is in the
* {@link #httpStatusToOAuth2ErrorCodeMap}.
* @param request the request being processed
* @param exception The root cause exception for the failure
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes
*/
private Mono<Void> handleWebClientResponseException(ClientRequest request,
WebClientResponseException exception) {
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getRawStatusCode())).flatMap((oauth2Error) -> {
Map<String, Object> attrs = request.attributes();
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
if (authorizedClient == null) {
return Mono.empty();
}
ClientAuthorizationException authorizationException = new ClientAuthorizationException(oauth2Error,
authorizedClient.getClientRegistration().getRegistrationId(), exception);
Authentication principal = createAuthentication(authorizedClient.getPrincipalName());
HttpServletRequest servletRequest = getRequest(attrs);
HttpServletResponse servletResponse = getResponse(attrs);
return handleAuthorizationFailure(authorizationException, principal, servletRequest, servletResponse);
});
}
/**
* Handles the given {@link OAuth2AuthorizationException} that occurred downstream
* by notifying the authorization failure handler.
* @param request the request being processed
* @param authorizationException the authorization exception to include in the
* failure event
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes
*/
private Mono<Void> handleAuthorizationException(ClientRequest request,
OAuth2AuthorizationException authorizationException) {
return Mono.justOrEmpty(request).flatMap((req) -> {
Map<String, Object> attrs = req.attributes();
OAuth2AuthorizedClient authorizedClient = getOAuth2AuthorizedClient(attrs);
if (authorizedClient == null) {
return Mono.empty();
}
Authentication principal = createAuthentication(authorizedClient.getPrincipalName());
HttpServletRequest servletRequest = getRequest(attrs);
HttpServletResponse servletResponse = getResponse(attrs);
return handleAuthorizationFailure(authorizationException, principal, servletRequest, servletResponse);
});
}
/**
* Delegates the failed authorization to the
* {@link OAuth2AuthorizationFailureHandler}.
* @param exception the {@link OAuth2AuthorizationException} to include in the
* failure event
* @param principal the principal associated with the failed authorization attempt
* @param servletRequest the currently active {@code HttpServletRequest}
* @param servletResponse the currently active {@code HttpServletResponse}
* @return a {@link Mono} that completes empty after the
* {@link OAuth2AuthorizationFailureHandler} completes
*/
private Mono<Void> handleAuthorizationFailure(OAuth2AuthorizationException exception, Authentication principal,
HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
Runnable runnable = () -> this.authorizationFailureHandler.onAuthorizationFailure(exception, principal,
createAttributes(servletRequest, servletResponse));
// @formatter:off
return Mono.fromRunnable(runnable)
.subscribeOn(Schedulers.boundedElastic())
.then();
// @formatter:on
}
private static Map<String, Object> createAttributes(HttpServletRequest servletRequest,
HttpServletResponse servletResponse) {
Map<String, Object> attributes = new HashMap<>();
attributes.put(HttpServletRequest.class.getName(), servletRequest);
attributes.put(HttpServletResponse.class.getName(), servletResponse);
return attributes;
}
}
}
| 35,017 | 45.628495 | 145 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/result/method/annotation/OAuth2AuthorizedClientArgumentResolver.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.reactive.result.method.annotation;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.BindingContext;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.server.ServerWebExchange;
/**
* An implementation of a {@link HandlerMethodArgumentResolver} that is capable of
* resolving a method parameter to an argument value of type
* {@link OAuth2AuthorizedClient}.
*
* <p>
* For example: <pre>
* @Controller
* public class MyController {
* @GetMapping("/authorized-client")
* public Mono<String> authorizedClient(@RegisteredOAuth2AuthorizedClient("login-client") OAuth2AuthorizedClient authorizedClient) {
* // do something with authorizedClient
* }
* }
* </pre>
*
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
* @see RegisteredOAuth2AuthorizedClient
*/
public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMethodArgumentResolver {
private static final AnonymousAuthenticationToken ANONYMOUS_USER_TOKEN = new AnonymousAuthenticationToken(
"anonymous", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_USER"));
private ReactiveOAuth2AuthorizedClientManager authorizedClientManager;
/**
* Constructs an {@code OAuth2AuthorizedClientArgumentResolver} using the provided
* parameters.
* @param authorizedClientManager the {@link ReactiveOAuth2AuthorizedClientManager}
* which manages the authorized client(s)
* @since 5.2
*/
public OAuth2AuthorizedClientArgumentResolver(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
Assert.notNull(authorizedClientManager, "authorizedClientManager cannot be null");
this.authorizedClientManager = authorizedClientManager;
}
/**
* Constructs an {@code OAuth2AuthorizedClientArgumentResolver} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public OAuth2AuthorizedClientArgumentResolver(ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authorizedClientManager = new DefaultReactiveOAuth2AuthorizedClientManager(clientRegistrationRepository,
authorizedClientRepository);
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return AnnotatedElementUtils.findMergedAnnotation(parameter.getParameter(),
RegisteredOAuth2AuthorizedClient.class) != null;
}
@Override
public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext bindingContext,
ServerWebExchange exchange) {
return Mono.defer(() -> {
RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
String clientRegistrationId = StringUtils.hasLength(authorizedClientAnnotation.registrationId())
? authorizedClientAnnotation.registrationId() : null;
return authorizeRequest(clientRegistrationId, exchange).flatMap(this.authorizedClientManager::authorize);
});
}
private Mono<OAuth2AuthorizeRequest> authorizeRequest(String registrationId, ServerWebExchange exchange) {
Mono<Authentication> defaultedAuthentication = currentAuthentication();
Mono<String> defaultedRegistrationId = Mono.justOrEmpty(registrationId)
.switchIfEmpty(clientRegistrationId(defaultedAuthentication))
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
"The clientRegistrationId could not be resolved. Please provide one")));
Mono<ServerWebExchange> defaultedExchange = Mono.justOrEmpty(exchange)
.switchIfEmpty(currentServerWebExchange());
return Mono.zip(defaultedRegistrationId, defaultedAuthentication, defaultedExchange)
.map((zipped) -> OAuth2AuthorizeRequest.withClientRegistrationId(zipped.getT1())
.principal(zipped.getT2()).attribute(ServerWebExchange.class.getName(), zipped.getT3())
.build());
}
private Mono<Authentication> currentAuthentication() {
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.defaultIfEmpty(ANONYMOUS_USER_TOKEN);
// @formatter:on
}
private Mono<String> clientRegistrationId(Mono<Authentication> authentication) {
return authentication.filter((t) -> t instanceof OAuth2AuthenticationToken)
.cast(OAuth2AuthenticationToken.class)
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
}
private Mono<ServerWebExchange> currentServerWebExchange() {
// @formatter:off
return Mono.deferContextual(Mono::just)
.filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class));
// @formatter:on
}
}
| 7,003 | 45.384106 | 142 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/method/annotation/OAuth2AuthorizedClientArgumentResolver.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.method.annotation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* An implementation of a {@link HandlerMethodArgumentResolver} that is capable of
* resolving a method parameter 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 RegisteredOAuth2AuthorizedClient
*/
public final class OAuth2AuthorizedClientArgumentResolver implements HandlerMethodArgumentResolver {
private static final Authentication ANONYMOUS_AUTHENTICATION = new AnonymousAuthenticationToken("anonymous",
"anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private OAuth2AuthorizedClientManager authorizedClientManager;
/**
* Constructs an {@code OAuth2AuthorizedClientArgumentResolver} using the provided
* parameters.
* @param authorizedClientManager the {@link OAuth2AuthorizedClientManager} which
* manages the authorized client(s)
* @since 5.2
*/
public OAuth2AuthorizedClientArgumentResolver(OAuth2AuthorizedClientManager authorizedClientManager) {
Assert.notNull(authorizedClientManager, "authorizedClientManager cannot be null");
this.authorizedClientManager = authorizedClientManager;
}
/**
* Constructs an {@code OAuth2AuthorizedClientArgumentResolver} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
* @param authorizedClientRepository the repository of authorized clients
*/
public OAuth2AuthorizedClientArgumentResolver(ClientRegistrationRepository clientRegistrationRepository,
OAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(clientRegistrationRepository,
authorizedClientRepository);
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
Class<?> parameterType = parameter.getParameterType();
return (OAuth2AuthorizedClient.class.isAssignableFrom(parameterType) && (AnnotatedElementUtils
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class) != null));
}
@NonNull
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) {
String clientRegistrationId = this.resolveClientRegistrationId(parameter);
if (!StringUtils.hasLength(clientRegistrationId)) {
throw new IllegalArgumentException("Unable to resolve the Client Registration Identifier. "
+ "It must be provided via @RegisteredOAuth2AuthorizedClient(\"client1\") or "
+ "@RegisteredOAuth2AuthorizedClient(registrationId = \"client1\").");
}
Authentication principal = this.securityContextHolderStrategy.getContext().getAuthentication();
if (principal == null) {
principal = ANONYMOUS_AUTHENTICATION;
}
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
HttpServletResponse servletResponse = webRequest.getNativeResponse(HttpServletResponse.class);
// @formatter:off
OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest
.withClientRegistrationId(clientRegistrationId)
.principal(principal)
.attribute(HttpServletRequest.class.getName(), servletRequest)
.attribute(HttpServletResponse.class.getName(), servletResponse)
.build();
// @formatter:on
return this.authorizedClientManager.authorize(authorizeRequest);
}
private String resolveClientRegistrationId(MethodParameter parameter) {
RegisteredOAuth2AuthorizedClient authorizedClientAnnotation = AnnotatedElementUtils
.findMergedAnnotation(parameter.getParameter(), RegisteredOAuth2AuthorizedClient.class);
Authentication principal = this.securityContextHolderStrategy.getContext().getAuthentication();
if (StringUtils.hasLength(authorizedClientAnnotation.registrationId())) {
return authorizedClientAnnotation.registrationId();
}
if (StringUtils.hasLength(authorizedClientAnnotation.value())) {
return authorizedClientAnnotation.value();
}
if (principal != null && OAuth2AuthenticationToken.class.isAssignableFrom(principal.getClass())) {
return ((OAuth2AuthenticationToken) principal).getAuthorizedClientRegistrationId();
}
return null;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
| 7,734 | 46.164634 | 130 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionOAuth2ServerAuthorizationRequestRepository.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
/**
* An implementation of an {@link ServerAuthorizationRequestRepository} that stores
* {@link OAuth2AuthorizationRequest} in the {@code WebSession}.
*
* @author Rob Winch
* @author Steve Riesenberg
* @since 5.1
* @see AuthorizationRequestRepository
* @see OAuth2AuthorizationRequest
*/
public final class WebSessionOAuth2ServerAuthorizationRequestRepository
implements ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> {
private static final String DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME = WebSessionOAuth2ServerAuthorizationRequestRepository.class
.getName() + ".AUTHORIZATION_REQUEST";
private final String sessionAttributeName = DEFAULT_AUTHORIZATION_REQUEST_ATTR_NAME;
@Override
public Mono<OAuth2AuthorizationRequest> loadAuthorizationRequest(ServerWebExchange exchange) {
String state = getStateParameter(exchange);
if (state == null) {
return Mono.empty();
}
// @formatter:off
return getSessionAttributes(exchange)
.filter((sessionAttrs) -> sessionAttrs.containsKey(this.sessionAttributeName))
.map(this::getAuthorizationRequest)
.filter((authorizationRequest) -> state.equals(authorizationRequest.getState()));
// @formatter:on
}
@Override
public Mono<Void> saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest,
ServerWebExchange exchange) {
Assert.notNull(authorizationRequest, "authorizationRequest cannot be null");
Assert.notNull(exchange, "exchange cannot be null");
// @formatter:off
return getSessionAttributes(exchange)
.doOnNext((sessionAttrs) -> {
Assert.hasText(authorizationRequest.getState(), "authorizationRequest.state cannot be empty");
sessionAttrs.put(this.sessionAttributeName, authorizationRequest);
})
.then();
// @formatter:on
}
@Override
public Mono<OAuth2AuthorizationRequest> removeAuthorizationRequest(ServerWebExchange exchange) {
String state = getStateParameter(exchange);
if (state == null) {
return Mono.empty();
}
// @formatter:off
return getSessionAttributes(exchange)
.filter((sessionAttrs) -> sessionAttrs.containsKey(this.sessionAttributeName))
.flatMap((sessionAttrs) -> {
OAuth2AuthorizationRequest authorizationRequest = (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName);
if (state.equals(authorizationRequest.getState())) {
sessionAttrs.remove(this.sessionAttributeName);
return Mono.just(authorizationRequest);
}
return Mono.empty();
});
// @formatter:on
}
/**
* Gets the state parameter from the {@link ServerHttpRequest}
* @param exchange the exchange to use
* @return the state parameter or null if not found
*/
private String getStateParameter(ServerWebExchange exchange) {
Assert.notNull(exchange, "exchange cannot be null");
return exchange.getRequest().getQueryParams().getFirst(OAuth2ParameterNames.STATE);
}
private Mono<Map<String, Object>> getSessionAttributes(ServerWebExchange exchange) {
return exchange.getSession().map(WebSession::getAttributes);
}
private OAuth2AuthorizationRequest getAuthorizationRequest(Map<String, Object> sessionAttrs) {
return (OAuth2AuthorizationRequest) sessionAttrs.get(this.sessionAttributeName);
}
}
| 4,445 | 37 | 129 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationCodeAuthenticationTokenConverter.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
/**
* Converts from a {@link ServerWebExchange} to an
* {@link OAuth2AuthorizationCodeAuthenticationToken} that can be authenticated. The
* converter does not validate any errors it only performs a conversion.
*
* @author Rob Winch
* @since 5.1
* @see org.springframework.security.web.server.authentication.AuthenticationWebFilter#setServerAuthenticationConverter(ServerAuthenticationConverter)
*/
public class ServerOAuth2AuthorizationCodeAuthenticationTokenConverter implements ServerAuthenticationConverter {
static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found";
static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found";
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
public ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
/**
* Sets the {@link ServerAuthorizationRequestRepository} to be used. The default is
* {@link WebSessionOAuth2ServerAuthorizationRequestRepository}.
* @param authorizationRequestRepository the repository to use.
*/
public void setAuthorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
@Override
public Mono<Authentication> convert(ServerWebExchange serverWebExchange) {
// @formatter:off
return this.authorizationRequestRepository.removeAuthorizationRequest(serverWebExchange)
.switchIfEmpty(oauth2AuthorizationException(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE))
.flatMap((authorizationRequest) -> authenticationRequest(serverWebExchange, authorizationRequest));
// @formatter:on
}
private <T> Mono<T> oauth2AuthorizationException(String errorCode) {
return Mono.defer(() -> {
OAuth2Error oauth2Error = new OAuth2Error(errorCode);
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
});
}
private Mono<OAuth2AuthorizationCodeAuthenticationToken> authenticationRequest(ServerWebExchange exchange,
OAuth2AuthorizationRequest authorizationRequest) {
// @formatter:off
return Mono.just(authorizationRequest)
.map(OAuth2AuthorizationRequest::getAttributes).flatMap((attributes) -> {
String id = (String) attributes.get(OAuth2ParameterNames.REGISTRATION_ID);
if (id == null) {
return oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
}
return this.clientRegistrationRepository.findByRegistrationId(id);
})
.switchIfEmpty(oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE))
.map((clientRegistration) -> {
OAuth2AuthorizationResponse authorizationResponse = convertResponse(exchange);
OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(
clientRegistration,
new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
return authenticationRequest;
});
// @formatter:on
}
private static OAuth2AuthorizationResponse convertResponse(ServerWebExchange exchange) {
String redirectUri = UriComponentsBuilder.fromUri(exchange.getRequest().getURI()).build().toUriString();
return OAuth2AuthorizationResponseUtils.convert(exchange.getRequest().getQueryParams(), redirectUri);
}
}
| 5,587 | 47.591304 | 166 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/ServerAuthorizationRequestRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizationRequestRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* Implementations of this interface are responsible for the persistence of
* {@link OAuth2AuthorizationRequest} between requests.
*
* <p>
* Used by the {@link OAuth2AuthorizationRequestRedirectFilter} for persisting the
* Authorization Request before it initiates the authorization code grant flow. As well,
* used by the {@link OAuth2LoginAuthenticationFilter} for resolving the associated
* Authorization Request when handling the callback of the Authorization Response.
*
* @param <T> The type of OAuth 2.0 Authorization Request
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizationRequest
* @see HttpSessionOAuth2AuthorizationRequestRepository
*/
public interface ServerAuthorizationRequestRepository<T extends OAuth2AuthorizationRequest> {
/**
* Returns the {@link OAuth2AuthorizationRequest} associated to the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param exchange the {@code ServerWebExchange}
* @return the {@link OAuth2AuthorizationRequest} or {@code null} if not available
*/
Mono<T> loadAuthorizationRequest(ServerWebExchange exchange);
/**
* Persists the {@link OAuth2AuthorizationRequest} associating it to the provided
* {@code HttpServletRequest} and/or {@code HttpServletResponse}.
* @param authorizationRequest the {@link OAuth2AuthorizationRequest}
* @param exchange the {@code ServerWebExchange}
*/
Mono<Void> saveAuthorizationRequest(T authorizationRequest, ServerWebExchange exchange);
/**
* Removes and returns the {@link OAuth2AuthorizationRequest} associated to the
* provided {@code HttpServletRequest} or if not available returns {@code null}.
* @param exchange the {@code ServerWebExchange}
* @return the removed {@link OAuth2AuthorizationRequest} or {@code null} if not
* available
*/
Mono<T> removeAuthorizationRequest(ServerWebExchange exchange);
}
| 3,034 | 41.746479 | 102 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.web.server.ServerWebExchange;
/**
* Implementations of this interface are responsible for the persistence of
* {@link OAuth2AuthorizedClient Authorized Client(s)} between requests.
*
* <p>
* The primary purpose of an {@link OAuth2AuthorizedClient Authorized Client} is to
* associate an {@link OAuth2AuthorizedClient#getAccessToken() Access Token} credential to
* a {@link OAuth2AuthorizedClient#getClientRegistration() Client} and Resource Owner, who
* is the {@link OAuth2AuthorizedClient#getPrincipalName() Principal} that originally
* granted the authorization.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizedClient
* @see ClientRegistration
* @see Authentication
* @see OAuth2AccessToken
*/
public interface ServerOAuth2AuthorizedClientRepository {
/**
* Returns the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner) or
* {@code null} if not available.
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param exchange the {@code ServerWebExchange}
* @param <T> a type of OAuth2AuthorizedClient
* @return the {@link OAuth2AuthorizedClient} or {@code null} if not available
*/
<T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange);
/**
* Saves the {@link OAuth2AuthorizedClient} associating it to the provided End-User
* {@link Authentication} (Resource Owner).
* @param authorizedClient the authorized client
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param exchange the {@code ServerWebExchange}
*/
Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange);
/**
* Removes the {@link OAuth2AuthorizedClient} associated to the provided client
* registration identifier and End-User {@link Authentication} (Resource Owner).
* @param clientRegistrationId the identifier for the client's registration
* @param principal the End-User {@link Authentication} (Resource Owner)
* @param exchange the {@code ServerWebExchange}
*/
Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange);
}
| 3,454 | 41.654321 | 99 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
/**
* An implementation of an {@link ServerOAuth2AuthorizedClientRepository} that delegates
* to the provided {@link ServerOAuth2AuthorizedClientRepository} if the current
* {@code Principal} is authenticated, otherwise, to the default (or provided)
* {@link ServerOAuth2AuthorizedClientRepository} if the current request is
* unauthenticated (or anonymous). The default
* {@code ReactiveOAuth2AuthorizedClientRepository} is
* {@link WebSessionServerOAuth2AuthorizedClientRepository}.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizedClientRepository
* @see OAuth2AuthorizedClient
* @see OAuth2AuthorizedClientService
* @see HttpSessionOAuth2AuthorizedClientRepository
*/
public final class AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository
implements ServerOAuth2AuthorizedClientRepository {
private final AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
private final ReactiveOAuth2AuthorizedClientService authorizedClientService;
private ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository = new WebSessionServerOAuth2AuthorizedClientRepository();
/**
* Creates an instance
* @param authorizedClientService the authorized client service
*/
public AuthenticatedPrincipalServerOAuth2AuthorizedClientRepository(
ReactiveOAuth2AuthorizedClientService authorizedClientService) {
Assert.notNull(authorizedClientService, "authorizedClientService cannot be null");
this.authorizedClientService = authorizedClientService;
}
/**
* Sets the {@link ServerOAuth2AuthorizedClientRepository} used for requests that are
* unauthenticated (or anonymous). The default is
* {@link WebSessionServerOAuth2AuthorizedClientRepository}.
* @param anonymousAuthorizedClientRepository the repository used for requests that
* are unauthenticated (or anonymous)
*/
public void setAnonymousAuthorizedClientRepository(
ServerOAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository) {
Assert.notNull(anonymousAuthorizedClientRepository, "anonymousAuthorizedClientRepository cannot be null");
this.anonymousAuthorizedClientRepository = anonymousAuthorizedClientRepository;
}
@Override
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, exchange);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.saveAuthorizedClient(authorizedClient, principal);
}
return this.anonymousAuthorizedClientRepository.saveAuthorizedClient(authorizedClient, principal, exchange);
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
if (this.isPrincipalAuthenticated(principal)) {
return this.authorizedClientService.removeAuthorizedClient(clientRegistrationId, principal.getName());
}
return this.anonymousAuthorizedClientRepository.removeAuthorizedClient(clientRegistrationId, principal,
exchange);
}
private boolean isPrincipalAuthenticated(Authentication authentication) {
return authentication != null && !this.authenticationTrustResolver.isAnonymous(authentication)
&& authentication.isAuthenticated();
}
}
| 5,190 | 44.535088 | 141 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/WebSessionServerOAuth2AuthorizedClientRepository.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.util.HashMap;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
/**
* An implementation of an {@link OAuth2AuthorizedClientRepository} that stores
* {@link OAuth2AuthorizedClient}'s in the {@code HttpSession}.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizedClientRepository
* @see OAuth2AuthorizedClient
*/
public final class WebSessionServerOAuth2AuthorizedClientRepository implements ServerOAuth2AuthorizedClientRepository {
private static final String DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME = WebSessionServerOAuth2AuthorizedClientRepository.class
.getName() + ".AUTHORIZED_CLIENTS";
private final String sessionAttributeName = DEFAULT_AUTHORIZED_CLIENTS_ATTR_NAME;
@Override
@SuppressWarnings("unchecked")
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(exchange, "exchange cannot be null");
// @formatter:off
return exchange.getSession()
.map(this::getAuthorizedClients)
.flatMap((clients) -> Mono.justOrEmpty((T) clients.get(clientRegistrationId)));
// @formatter:on
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(exchange, "exchange cannot be null");
// @formatter:off
return exchange.getSession()
.doOnSuccess((session) -> {
Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session);
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
session.getAttributes().put(this.sessionAttributeName, authorizedClients);
})
.then(Mono.empty());
// @formatter:on
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(exchange, "exchange cannot be null");
// @formatter:off
return exchange.getSession()
.doOnSuccess((session) -> {
Map<String, OAuth2AuthorizedClient> authorizedClients = getAuthorizedClients(session);
authorizedClients.remove(clientRegistrationId);
if (authorizedClients.isEmpty()) {
session.getAttributes().remove(this.sessionAttributeName);
}
else {
session.getAttributes().put(this.sessionAttributeName, authorizedClients);
}
})
.then(Mono.empty());
// @formatter:on
}
@SuppressWarnings("unchecked")
private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(WebSession session) {
Map<String, OAuth2AuthorizedClient> authorizedClients = (session != null)
? (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName) : null;
if (authorizedClients == null) {
authorizedClients = new HashMap<>();
}
return authorizedClients;
}
}
| 4,178 | 37.694444 | 122 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationResponseUtils.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.util.Map;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* Utility methods for an OAuth 2.0 Authorization Response.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizationResponse
*/
final class OAuth2AuthorizationResponseUtils {
private OAuth2AuthorizationResponseUtils() {
}
static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) {
MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size());
map.forEach((key, values) -> {
if (values.length > 0) {
for (String value : values) {
params.add(key, value);
}
}
});
return params;
}
static boolean isAuthorizationResponse(MultiValueMap<String, String> request) {
return isAuthorizationResponseSuccess(request) || isAuthorizationResponseError(request);
}
static boolean isAuthorizationResponseSuccess(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.CODE))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static boolean isAuthorizationResponseError(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.ERROR))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static OAuth2AuthorizationResponse convert(MultiValueMap<String, String> request, String redirectUri) {
String code = request.getFirst(OAuth2ParameterNames.CODE);
String errorCode = request.getFirst(OAuth2ParameterNames.ERROR);
String state = request.getFirst(OAuth2ParameterNames.STATE);
if (StringUtils.hasText(code)) {
return OAuth2AuthorizationResponse.success(code).redirectUri(redirectUri).state(state).build();
}
String errorDescription = request.getFirst(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = request.getFirst(OAuth2ParameterNames.ERROR_URI);
// @formatter:off
return OAuth2AuthorizationResponse.error(errorCode)
.redirectUri(redirectUri)
.errorDescription(errorDescription)
.errorUri(errorUri)
.state(state)
.build();
// @formatter:on
}
}
| 3,053 | 34.929412 | 104 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationRequestRedirectWebFilter.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.net.URI;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.client.ClientAuthorizationRequiredException;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.UriComponentsBuilder;
/**
* This {@code WebFilter} initiates the authorization code grant flow by redirecting the
* End-User's user-agent to the Authorization Server's Authorization Endpoint.
*
* <p>
* It builds the OAuth 2.0 Authorization Request, which is used as the redirect
* {@code URI} to the Authorization Endpoint. The redirect {@code URI} will include the
* client identifier, requested scope(s), state, response type, and a redirection URI
* which the authorization server will send the user-agent back to once access is granted
* (or denied) by the End-User (Resource Owner).
*
* <p>
* By default, this {@code Filter} responds to authorization requests at the {@code URI}
* {@code /oauth2/authorization/{registrationId}}. The {@code URI} template variable
* {@code {registrationId}} represents the {@link ClientRegistration#getRegistrationId()
* registration identifier} of the client that is used for initiating the OAuth 2.0
* Authorization Request.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizationRequest
* @see AuthorizationRequestRepository
* @see ClientRegistration
* @see ClientRegistrationRepository
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.1">Section 4.1.1 Authorization Request
* (Authorization Code)</a>
*/
public class OAuth2AuthorizationRequestRedirectWebFilter implements WebFilter {
private ServerRedirectStrategy authorizationRedirectStrategy = new DefaultServerRedirectStrategy();
private final ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver;
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
/**
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided
* parameters.
* @param clientRegistrationRepository the repository of client registrations
*/
public OAuth2AuthorizationRequestRedirectWebFilter(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
this.authorizationRequestResolver = new DefaultServerOAuth2AuthorizationRequestResolver(
clientRegistrationRepository);
}
/**
* Constructs an {@code OAuth2AuthorizationRequestRedirectFilter} using the provided
* parameters.
* @param authorizationRequestResolver the resolver to use
*/
public OAuth2AuthorizationRequestRedirectWebFilter(
ServerOAuth2AuthorizationRequestResolver authorizationRequestResolver) {
Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null");
this.authorizationRequestResolver = authorizationRequestResolver;
}
/**
* Sets the redirect strategy for Authorization Endpoint redirect URI.
* @param authorizationRedirectStrategy the redirect strategy
*/
public void setAuthorizationRedirectStrategy(ServerRedirectStrategy authorizationRedirectStrategy) {
Assert.notNull(authorizationRedirectStrategy, "authorizationRedirectStrategy cannot be null");
this.authorizationRedirectStrategy = authorizationRedirectStrategy;
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s.
* @param authorizationRequestRepository the repository used for storing
* {@link OAuth2AuthorizationRequest}'s
*/
public final void setAuthorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
}
/**
* The request cache to use to save the request before sending a redirect.
* @param requestCache the cache to redirect to.
*/
public void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.authorizationRequestResolver.resolve(exchange)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.onErrorResume(ClientAuthorizationRequiredException.class,
(ex) -> this.requestCache.saveRequest(exchange).then(
this.authorizationRequestResolver.resolve(exchange, ex.getClientRegistrationId()))
)
.flatMap((clientRegistration) -> sendRedirectForAuthorization(exchange, clientRegistration));
// @formatter:on
}
private Mono<Void> sendRedirectForAuthorization(ServerWebExchange exchange,
OAuth2AuthorizationRequest authorizationRequest) {
return Mono.defer(() -> {
Mono<Void> saveAuthorizationRequest = Mono.empty();
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) {
saveAuthorizationRequest = this.authorizationRequestRepository
.saveAuthorizationRequest(authorizationRequest, exchange);
}
// @formatter:off
URI redirectUri = UriComponentsBuilder.fromUriString(authorizationRequest.getAuthorizationRequestUri())
.build(true)
.toUri();
// @formatter:on
return saveAuthorizationRequest
.then(this.authorizationRedirectStrategy.sendRedirect(exchange, redirectUri));
});
}
}
| 7,368 | 44.208589 | 166 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/OAuth2AuthorizationCodeGrantWebFilter.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.savedrequest.ServerRequestCache;
import org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A {@code Filter} for the OAuth 2.0 Authorization Code Grant, which handles the
* processing of the OAuth 2.0 Authorization Response.
*
* <p>
* The OAuth 2.0 Authorization Response is processed as follows:
*
* <ul>
* <li>Assuming the End-User (Resource Owner) has granted access to the Client, the
* Authorization Server will append the {@link OAuth2ParameterNames#CODE code} and
* {@link OAuth2ParameterNames#STATE state} parameters to the
* {@link OAuth2ParameterNames#REDIRECT_URI redirect_uri} (provided in the Authorization
* Request) and redirect the End-User's user-agent back to this {@code Filter} (the
* Client).</li>
* <li>This {@code Filter} will then create an
* {@link OAuth2AuthorizationCodeAuthenticationToken} with the
* {@link OAuth2ParameterNames#CODE code} received and delegate it to the
* {@link ReactiveAuthenticationManager} to authenticate.</li>
* <li>Upon a successful authentication, an {@link OAuth2AuthorizedClient Authorized
* Client} is created by associating the
* {@link OAuth2AuthorizationCodeAuthenticationToken#getClientRegistration() client} to
* the {@link OAuth2AuthorizationCodeAuthenticationToken#getAccessToken() access token}
* and current {@code Principal} and saving it via the
* {@link ServerOAuth2AuthorizedClientRepository}.</li>
* </ul>
*
* @author Rob Winch
* @author Joe Grandja
* @author Parikshit Dutta
* @since 5.1
* @see OAuth2AuthorizationCodeAuthenticationToken
* @see org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeReactiveAuthenticationManager
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationResponse
* @see AuthorizationRequestRepository
* @see org.springframework.security.oauth2.client.web.server.OAuth2AuthorizationRequestRedirectWebFilter
* @see ReactiveClientRegistrationRepository
* @see OAuth2AuthorizedClient
* @see ServerOAuth2AuthorizedClientRepository
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.2">Section 4.1.2 Authorization
* Response</a>
*/
public class OAuth2AuthorizationCodeGrantWebFilter implements WebFilter {
private final ReactiveAuthenticationManager authenticationManager;
private final ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
private ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = new WebSessionOAuth2ServerAuthorizationRequestRepository();
private ServerAuthenticationSuccessHandler authenticationSuccessHandler;
private ServerAuthenticationConverter authenticationConverter;
private boolean defaultAuthenticationConverter;
private ServerAuthenticationFailureHandler authenticationFailureHandler;
private ServerWebExchangeMatcher requiresAuthenticationMatcher;
private ServerRequestCache requestCache = new WebSessionServerRequestCache();
private AnonymousAuthenticationToken anonymousToken = new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
public OAuth2AuthorizationCodeGrantWebFilter(ReactiveAuthenticationManager authenticationManager,
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authenticationManager = authenticationManager;
this.authorizedClientRepository = authorizedClientRepository;
this.requiresAuthenticationMatcher = this::matchesAuthorizationResponse;
ServerOAuth2AuthorizationCodeAuthenticationTokenConverter authenticationConverter = new ServerOAuth2AuthorizationCodeAuthenticationTokenConverter(
clientRegistrationRepository);
authenticationConverter.setAuthorizationRequestRepository(this.authorizationRequestRepository);
this.authenticationConverter = authenticationConverter;
this.defaultAuthenticationConverter = true;
RedirectServerAuthenticationSuccessHandler authenticationSuccessHandler = new RedirectServerAuthenticationSuccessHandler();
authenticationSuccessHandler.setRequestCache(this.requestCache);
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = (webFilterExchange, exception) -> Mono.error(exception);
}
public OAuth2AuthorizationCodeGrantWebFilter(ReactiveAuthenticationManager authenticationManager,
ServerAuthenticationConverter authenticationConverter,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
Assert.notNull(authenticationManager, "authenticationManager cannot be null");
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null");
this.authenticationManager = authenticationManager;
this.authorizedClientRepository = authorizedClientRepository;
this.requiresAuthenticationMatcher = this::matchesAuthorizationResponse;
this.authenticationConverter = authenticationConverter;
RedirectServerAuthenticationSuccessHandler authenticationSuccessHandler = new RedirectServerAuthenticationSuccessHandler();
authenticationSuccessHandler.setRequestCache(this.requestCache);
this.authenticationSuccessHandler = authenticationSuccessHandler;
this.authenticationFailureHandler = (webFilterExchange, exception) -> Mono.error(exception);
}
/**
* Sets the repository used for storing {@link OAuth2AuthorizationRequest}'s. The
* default is {@link WebSessionOAuth2ServerAuthorizationRequestRepository}.
* @param authorizationRequestRepository the repository used for storing
* {@link OAuth2AuthorizationRequest}'s
* @since 5.2
*/
public final void setAuthorizationRequestRepository(
ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository) {
Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
this.authorizationRequestRepository = authorizationRequestRepository;
updateDefaultAuthenticationConverter();
}
private void updateDefaultAuthenticationConverter() {
if (this.defaultAuthenticationConverter) {
((ServerOAuth2AuthorizationCodeAuthenticationTokenConverter) this.authenticationConverter)
.setAuthorizationRequestRepository(this.authorizationRequestRepository);
}
}
/**
* Sets the {@link ServerRequestCache} used for loading a previously saved request (if
* available) and replaying it after completing the processing of the OAuth 2.0
* Authorization Response.
* @param requestCache the cache used for loading a previously saved request (if
* available)
* @since 5.4
*/
public final void setRequestCache(ServerRequestCache requestCache) {
Assert.notNull(requestCache, "requestCache cannot be null");
this.requestCache = requestCache;
updateDefaultAuthenticationSuccessHandler();
}
private void updateDefaultAuthenticationSuccessHandler() {
((RedirectServerAuthenticationSuccessHandler) this.authenticationSuccessHandler)
.setRequestCache(this.requestCache);
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// @formatter:off
return this.requiresAuthenticationMatcher.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.flatMap((matchResult) -> this.authenticationConverter.convert(exchange)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString())
)
)
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap((token) -> authenticate(exchange, chain, token))
.onErrorResume(AuthenticationException.class, (e) ->
this.authenticationFailureHandler.onAuthenticationFailure(new WebFilterExchange(exchange, chain), e)
);
// @formatter:on
}
private Mono<Void> authenticate(ServerWebExchange exchange, WebFilterChain chain, Authentication token) {
WebFilterExchange webFilterExchange = new WebFilterExchange(exchange, chain);
return this.authenticationManager.authenticate(token)
.onErrorMap(OAuth2AuthorizationException.class,
(ex) -> new OAuth2AuthenticationException(ex.getError(), ex.getError().toString()))
.switchIfEmpty(Mono.defer(
() -> Mono.error(new IllegalStateException("No provider found for " + token.getClass()))))
.flatMap((authentication) -> onAuthenticationSuccess(authentication, webFilterExchange))
.onErrorResume(AuthenticationException.class,
(e) -> this.authenticationFailureHandler.onAuthenticationFailure(webFilterExchange, e));
}
private Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), authenticationResult.getName(),
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
// @formatter:off
return this.authenticationSuccessHandler.onAuthenticationSuccess(webFilterExchange, authentication)
.then(ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication)
.defaultIfEmpty(this.anonymousToken)
.flatMap((principal) -> this.authorizedClientRepository
.saveAuthorizedClient(authorizedClient, principal, webFilterExchange.getExchange())
)
);
// @formatter:on
}
private Mono<ServerWebExchangeMatcher.MatchResult> matchesAuthorizationResponse(ServerWebExchange exchange) {
// @formatter:off
return Mono.just(exchange)
.filter((exch) ->
OAuth2AuthorizationResponseUtils.isAuthorizationResponse(exch.getRequest().getQueryParams())
)
.flatMap((exch) -> this.authorizationRequestRepository.loadAuthorizationRequest(exchange)
.flatMap((authorizationRequest) -> matchesRedirectUri(exch.getRequest().getURI(),
authorizationRequest.getRedirectUri()))
)
.switchIfEmpty(ServerWebExchangeMatcher.MatchResult.notMatch());
// @formatter:on
}
private static Mono<ServerWebExchangeMatcher.MatchResult> matchesRedirectUri(URI authorizationResponseUri,
String authorizationRequestRedirectUri) {
UriComponents requestUri = UriComponentsBuilder.fromUri(authorizationResponseUri).build();
UriComponents redirectUri = UriComponentsBuilder.fromUriString(authorizationRequestRedirectUri).build();
Set<Map.Entry<String, List<String>>> requestUriParameters = new LinkedHashSet<>(
requestUri.getQueryParams().entrySet());
Set<Map.Entry<String, List<String>>> redirectUriParameters = new LinkedHashSet<>(
redirectUri.getQueryParams().entrySet());
// Remove the additional request parameters (if any) from the authorization
// response (request)
// before doing an exact comparison with the authorizationRequest.getRedirectUri()
// parameters (if any)
requestUriParameters.retainAll(redirectUriParameters);
if (Objects.equals(requestUri.getScheme(), redirectUri.getScheme())
&& Objects.equals(requestUri.getUserInfo(), redirectUri.getUserInfo())
&& Objects.equals(requestUri.getHost(), redirectUri.getHost())
&& Objects.equals(requestUri.getPort(), redirectUri.getPort())
&& Objects.equals(requestUri.getPath(), redirectUri.getPath())
&& Objects.equals(requestUriParameters.toString(), redirectUriParameters.toString())) {
return ServerWebExchangeMatcher.MatchResult.match();
}
return ServerWebExchangeMatcher.MatchResult.notMatch();
}
}
| 15,074 | 51.16263 | 166 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/DefaultServerOAuth2AuthorizationRequestResolver.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestCustomizers;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* The default implementation of {@link ServerOAuth2AuthorizationRequestResolver}.
*
* The {@link ClientRegistration#getRegistrationId()} is extracted from the request using
* the {@link #DEFAULT_AUTHORIZATION_REQUEST_PATTERN}. The injected
* {@link ReactiveClientRegistrationRepository} is then used to resolve the
* {@link ClientRegistration} and create the {@link OAuth2AuthorizationRequest}.
*
* @author Rob Winch
* @author Mark Heckler
* @author Joe Grandja
* @since 5.1
*/
public class DefaultServerOAuth2AuthorizationRequestResolver implements ServerOAuth2AuthorizationRequestResolver {
/**
* The name of the path variable that contains the
* {@link ClientRegistration#getRegistrationId()}
*/
public static final String DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId";
/**
* The default pattern used to resolve the
* {@link ClientRegistration#getRegistrationId()}
*/
public static final String DEFAULT_AUTHORIZATION_REQUEST_PATTERN = "/oauth2/authorization/{"
+ DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME + "}";
private static final char PATH_DELIMITER = '/';
private static final StringKeyGenerator DEFAULT_STATE_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder());
private static final StringKeyGenerator DEFAULT_SECURE_KEY_GENERATOR = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
private static final Consumer<OAuth2AuthorizationRequest.Builder> DEFAULT_PKCE_APPLIER = OAuth2AuthorizationRequestCustomizers
.withPkce();
private final ServerWebExchangeMatcher authorizationRequestMatcher;
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
private Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer = (customizer) -> {
};
/**
* Creates a new instance
* @param clientRegistrationRepository the repository to resolve the
* {@link ClientRegistration}
*/
public DefaultServerOAuth2AuthorizationRequestResolver(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
this(clientRegistrationRepository,
new PathPatternParserServerWebExchangeMatcher(DEFAULT_AUTHORIZATION_REQUEST_PATTERN));
}
/**
* Creates a new instance
* @param clientRegistrationRepository the repository to resolve the
* {@link ClientRegistration}
* @param authorizationRequestMatcher the matcher that determines if the request is a
* match and extracts the {@link #DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME} from the
* path variables.
*/
public DefaultServerOAuth2AuthorizationRequestResolver(
ReactiveClientRegistrationRepository clientRegistrationRepository,
ServerWebExchangeMatcher authorizationRequestMatcher) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
Assert.notNull(authorizationRequestMatcher, "authorizationRequestMatcher cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
this.authorizationRequestMatcher = authorizationRequestMatcher;
}
@Override
public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange) {
// @formatter:off
return this.authorizationRequestMatcher
.matches(exchange)
.filter((matchResult) -> matchResult.isMatch())
.map(ServerWebExchangeMatcher.MatchResult::getVariables)
.map((variables) -> variables.get(DEFAULT_REGISTRATION_ID_URI_VARIABLE_NAME))
.cast(String.class)
.flatMap((clientRegistrationId) -> resolve(exchange, clientRegistrationId));
// @formatter:on
}
@Override
public Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, String clientRegistrationId) {
return findByRegistrationId(exchange, clientRegistrationId)
.map((clientRegistration) -> authorizationRequest(exchange, clientRegistration));
}
/**
* Sets the {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder} allowing for further customizations.
* @param authorizationRequestCustomizer the {@code Consumer} to be provided the
* {@link OAuth2AuthorizationRequest.Builder}
* @since 5.3
* @see OAuth2AuthorizationRequestCustomizers
*/
public final void setAuthorizationRequestCustomizer(
Consumer<OAuth2AuthorizationRequest.Builder> authorizationRequestCustomizer) {
Assert.notNull(authorizationRequestCustomizer, "authorizationRequestCustomizer cannot be null");
this.authorizationRequestCustomizer = authorizationRequestCustomizer;
}
private Mono<ClientRegistration> findByRegistrationId(ServerWebExchange exchange, String clientRegistration) {
// @formatter:off
return this.clientRegistrationRepository.findByRegistrationId(clientRegistration)
.switchIfEmpty(Mono.error(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid client registration id")));
// @formatter:on
}
private OAuth2AuthorizationRequest authorizationRequest(ServerWebExchange exchange,
ClientRegistration clientRegistration) {
OAuth2AuthorizationRequest.Builder builder = getBuilder(clientRegistration);
String redirectUriStr = expandRedirectUri(exchange.getRequest(), clientRegistration);
// @formatter:off
builder.clientId(clientRegistration.getClientId())
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(redirectUriStr)
.scopes(clientRegistration.getScopes())
.state(DEFAULT_STATE_GENERATOR.generateKey());
// @formatter:on
this.authorizationRequestCustomizer.accept(builder);
return builder.build();
}
private OAuth2AuthorizationRequest.Builder getBuilder(ClientRegistration clientRegistration) {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
// @formatter:off
OAuth2AuthorizationRequest.Builder builder = OAuth2AuthorizationRequest.authorizationCode()
.attributes((attrs) ->
attrs.put(OAuth2ParameterNames.REGISTRATION_ID, clientRegistration.getRegistrationId()));
// @formatter:on
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())
&& clientRegistration.getScopes().contains(OidcScopes.OPENID)) {
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
// scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope
// value.
applyNonce(builder);
}
if (ClientAuthenticationMethod.NONE.equals(clientRegistration.getClientAuthenticationMethod())) {
DEFAULT_PKCE_APPLIER.accept(builder);
}
return builder;
}
throw new IllegalArgumentException(
"Invalid Authorization Grant Type (" + clientRegistration.getAuthorizationGrantType().getValue()
+ ") for Client Registration with Id: " + clientRegistration.getRegistrationId());
}
/**
* Expands the {@link ClientRegistration#getRedirectUri()} with following provided
* variables:<br/>
* - baseUrl (e.g. https://localhost/app) <br/>
* - baseScheme (e.g. https) <br/>
* - baseHost (e.g. localhost) <br/>
* - basePort (e.g. :8080) <br/>
* - basePath (e.g. /app) <br/>
* - registrationId (e.g. google) <br/>
* - action (e.g. login) <br/>
* <p/>
* Null variables are provided as empty strings.
* <p/>
* Default redirectUri is:
* {@code org.springframework.security.config.oauth2.client.CommonOAuth2Provider#DEFAULT_REDIRECT_URL}
* @return expanded URI
*/
private static String expandRedirectUri(ServerHttpRequest request, ClientRegistration clientRegistration) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
// @formatter:off
UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI())
.replacePath(request.getPath().contextPath().value())
.replaceQuery(null)
.fragment(null)
.build();
// @formatter:on
String scheme = uriComponents.getScheme();
uriVariables.put("baseScheme", (scheme != null) ? scheme : "");
String host = uriComponents.getHost();
uriVariables.put("baseHost", (host != null) ? host : "");
// following logic is based on HierarchicalUriComponents#toUriString()
int port = uriComponents.getPort();
uriVariables.put("basePort", (port == -1) ? "" : ":" + port);
String path = uriComponents.getPath();
if (StringUtils.hasLength(path)) {
if (path.charAt(0) != PATH_DELIMITER) {
path = PATH_DELIMITER + path;
}
}
uriVariables.put("basePath", (path != null) ? path : "");
uriVariables.put("baseUrl", uriComponents.toUriString());
String action = "";
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
action = "login";
}
uriVariables.put("action", action);
// @formatter:off
return UriComponentsBuilder.fromUriString(clientRegistration.getRedirectUri())
.buildAndExpand(uriVariables)
.toUriString();
// @formatter:on
}
/**
* Creates nonce and its hash for use in OpenID Connect 1.0 Authentication Requests.
* @param builder where the {@link OidcParameterNames#NONCE} and hash is stored for
* the authentication request
*
* @since 5.2
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest">3.1.2.1.
* Authentication Request</a>
*/
private static void applyNonce(OAuth2AuthorizationRequest.Builder builder) {
try {
String nonce = DEFAULT_SECURE_KEY_GENERATOR.generateKey();
String nonceHash = createHash(nonce);
builder.attributes((attrs) -> attrs.put(OidcParameterNames.NONCE, nonce));
builder.additionalParameters((params) -> params.put(OidcParameterNames.NONCE, nonceHash));
}
catch (NoSuchAlgorithmException ex) {
}
}
private static String createHash(String value) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(value.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
| 12,468 | 41.848797 | 127 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/ServerOAuth2AuthorizationRequestResolver.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server;
import reactor.core.publisher.Mono;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.web.server.ServerWebExchange;
/**
* Implementations of this interface are capable of resolving an
* {@link OAuth2AuthorizationRequest} from the provided {@code ServerWebExchange}. Used by
* the {@link OAuth2AuthorizationRequestRedirectWebFilter} for resolving Authorization
* Requests.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationRequestRedirectWebFilter
*/
public interface ServerOAuth2AuthorizationRequestResolver {
/**
* Returns the {@link OAuth2AuthorizationRequest} resolved from the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param exchange the {@code ServerWebExchange}
* @return the resolved {@link OAuth2AuthorizationRequest} or {@code null} if not
* available
*/
Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange);
/**
* Returns the {@link OAuth2AuthorizationRequest} resolved from the provided
* {@code HttpServletRequest} or {@code null} if not available.
* @param exchange the {@code ServerWebExchange}
* @param clientRegistrationId the client registration id
* @return the resolved {@link OAuth2AuthorizationRequest} or {@code null} if not
* available
*/
Mono<OAuth2AuthorizationRequest> resolve(ServerWebExchange exchange, String clientRegistrationId);
}
| 2,151 | 36.754386 | 99 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilter.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.web.server.authentication;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.AuthenticationWebFilter;
import org.springframework.util.Assert;
/**
* A specialized {@link AuthenticationWebFilter} that converts from an
* {@link OAuth2LoginAuthenticationToken} to an {@link OAuth2AuthenticationToken} and
* saves the {@link OAuth2AuthorizedClient}
*
* @author Rob Winch
* @since 5.1
*/
public class OAuth2LoginAuthenticationWebFilter extends AuthenticationWebFilter {
private final ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
/**
* Creates an instance
* @param authenticationManager the authentication manager to use
* @param authorizedClientRepository
*/
public OAuth2LoginAuthenticationWebFilter(ReactiveAuthenticationManager authenticationManager,
ServerOAuth2AuthorizedClientRepository authorizedClientRepository) {
super(authenticationManager);
Assert.notNull(authorizedClientRepository, "authorizedClientService cannot be null");
this.authorizedClientRepository = authorizedClientRepository;
}
@Override
protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) {
OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) authentication;
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(
authenticationResult.getClientRegistration(), authenticationResult.getName(),
authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
OAuth2AuthenticationToken result = new OAuth2AuthenticationToken(authenticationResult.getPrincipal(),
authenticationResult.getAuthorities(),
authenticationResult.getClientRegistration().getRegistrationId());
// @formatter:off
return this.authorizedClientRepository
.saveAuthorizedClient(authorizedClient, authenticationResult, webFilterExchange.getExchange())
.then(super.onAuthenticationSuccess(result, webFilterExchange));
// @formatter:on
}
}
| 3,286 | 44.652778 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/aot/hint/OAuth2ClientRuntimeHints.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.aot.hint;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
/**
* {@link RuntimeHintsRegistrar} for OAuth2 Client
*
* @author Marcus Da Coregio
* @since 6.0
*/
class OAuth2ClientRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
registerOAuth2ClientSchemaFilesHints(hints);
}
private void registerOAuth2ClientSchemaFilesHints(RuntimeHints hints) {
hints.resources().registerPattern("org/springframework/security/oauth2/client/oauth2-client-schema.sql")
.registerPattern("org/springframework/security/oauth2/client/oauth2-client-schema-postgres.sql");
}
}
| 1,391 | 32.95122 | 106 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2ErrorMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2Error} as part of
* {@link org.springframework.security.oauth2.core.OAuth2AuthenticationException}.
*
* @author Dennis Neufeld
* @since 5.3.4
* @see OAuth2Error
* @see OAuth2AuthenticationExceptionMixin
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2ErrorMixin {
@JsonCreator
OAuth2ErrorMixin(@JsonProperty("errorCode") String errorCode, @JsonProperty("description") String description,
@JsonProperty("uri") String uri) {
}
}
| 1,808 | 35.918367 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2ClientJackson2Module.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.jackson2;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
/**
* Jackson {@code Module} for {@code spring-security-oauth2-client}, that registers the
* following mix-in annotations:
*
* <ul>
* <li>{@link OAuth2AuthorizationRequestMixin}</li>
* <li>{@link ClientRegistrationMixin}</li>
* <li>{@link OAuth2AccessTokenMixin}</li>
* <li>{@link OAuth2RefreshTokenMixin}</li>
* <li>{@link OAuth2AuthorizedClientMixin}</li>
* <li>{@link OAuth2UserAuthorityMixin}</li>
* <li>{@link DefaultOAuth2UserMixin}</li>
* <li>{@link OidcIdTokenMixin}</li>
* <li>{@link OidcUserInfoMixin}</li>
* <li>{@link OidcUserAuthorityMixin}</li>
* <li>{@link DefaultOidcUserMixin}</li>
* <li>{@link OAuth2AuthenticationTokenMixin}</li>
* <li>{@link OAuth2AuthenticationExceptionMixin}</li>
* <li>{@link OAuth2ErrorMixin}</li>
* </ul>
*
* If not already enabled, default typing will be automatically enabled as type info is
* required to properly serialize/deserialize objects. In order to use this module just
* add it to your {@code ObjectMapper} configuration.
*
* <pre>
* ObjectMapper mapper = new ObjectMapper();
* mapper.registerModule(new OAuth2ClientJackson2Module());
* </pre>
*
* <b>NOTE:</b> Use {@link SecurityJackson2Modules#getModules(ClassLoader)} to get a list
* of all security modules.
*
* @author Joe Grandja
* @since 5.3
* @see SecurityJackson2Modules
* @see OAuth2AuthorizationRequestMixin
* @see ClientRegistrationMixin
* @see OAuth2AccessTokenMixin
* @see OAuth2RefreshTokenMixin
* @see OAuth2AuthorizedClientMixin
* @see OAuth2UserAuthorityMixin
* @see DefaultOAuth2UserMixin
* @see OidcIdTokenMixin
* @see OidcUserInfoMixin
* @see OidcUserAuthorityMixin
* @see DefaultOidcUserMixin
* @see OAuth2AuthenticationTokenMixin
* @see OAuth2AuthenticationExceptionMixin
* @see OAuth2ErrorMixin
*/
public class OAuth2ClientJackson2Module extends SimpleModule {
public OAuth2ClientJackson2Module() {
super(OAuth2ClientJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void setupModule(SetupContext context) {
SecurityJackson2Modules.enableDefaultTyping(context.getOwner());
context.setMixInAnnotations(OAuth2AuthorizationRequest.class, OAuth2AuthorizationRequestMixin.class);
context.setMixInAnnotations(ClientRegistration.class, ClientRegistrationMixin.class);
context.setMixInAnnotations(OAuth2AccessToken.class, OAuth2AccessTokenMixin.class);
context.setMixInAnnotations(OAuth2RefreshToken.class, OAuth2RefreshTokenMixin.class);
context.setMixInAnnotations(OAuth2AuthorizedClient.class, OAuth2AuthorizedClientMixin.class);
context.setMixInAnnotations(OAuth2UserAuthority.class, OAuth2UserAuthorityMixin.class);
context.setMixInAnnotations(DefaultOAuth2User.class, DefaultOAuth2UserMixin.class);
context.setMixInAnnotations(OidcIdToken.class, OidcIdTokenMixin.class);
context.setMixInAnnotations(OidcUserInfo.class, OidcUserInfoMixin.class);
context.setMixInAnnotations(OidcUserAuthority.class, OidcUserAuthorityMixin.class);
context.setMixInAnnotations(DefaultOidcUser.class, DefaultOidcUserMixin.class);
context.setMixInAnnotations(OAuth2AuthenticationToken.class, OAuth2AuthenticationTokenMixin.class);
context.setMixInAnnotations(OAuth2AuthenticationException.class, OAuth2AuthenticationExceptionMixin.class);
context.setMixInAnnotations(OAuth2Error.class, OAuth2ErrorMixin.class);
}
}
| 5,258 | 44.730435 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OidcUserAuthorityMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
/**
* This mixin class is used to serialize/deserialize {@link OidcUserAuthority}.
*
* @author Joe Grandja
* @since 5.3
* @see OidcUserAuthority
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(value = { "attributes" }, ignoreUnknown = true)
abstract class OidcUserAuthorityMixin {
@JsonCreator
OidcUserAuthorityMixin(@JsonProperty("authority") String authority, @JsonProperty("idToken") OidcIdToken idToken,
@JsonProperty("userInfo") OidcUserInfo userInfo) {
}
}
| 1,879 | 37.367347 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestDeserializer.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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest.Builder;
/**
* A {@code JsonDeserializer} for {@link OAuth2AuthorizationRequest}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationRequestMixin
*/
final class OAuth2AuthorizationRequestDeserializer extends JsonDeserializer<OAuth2AuthorizationRequest> {
private static final StdConverter<JsonNode, AuthorizationGrantType> AUTHORIZATION_GRANT_TYPE_CONVERTER = new StdConverters.AuthorizationGrantTypeConverter();
@Override
public OAuth2AuthorizationRequest deserialize(JsonParser parser, DeserializationContext context)
throws IOException {
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
JsonNode root = mapper.readTree(parser);
return deserialize(parser, mapper, root);
}
private OAuth2AuthorizationRequest deserialize(JsonParser parser, ObjectMapper mapper, JsonNode root)
throws JsonParseException {
AuthorizationGrantType authorizationGrantType = AUTHORIZATION_GRANT_TYPE_CONVERTER
.convert(JsonNodeUtils.findObjectNode(root, "authorizationGrantType"));
Builder builder = getBuilder(parser, authorizationGrantType);
builder.authorizationUri(JsonNodeUtils.findStringValue(root, "authorizationUri"));
builder.clientId(JsonNodeUtils.findStringValue(root, "clientId"));
builder.redirectUri(JsonNodeUtils.findStringValue(root, "redirectUri"));
builder.scopes(JsonNodeUtils.findValue(root, "scopes", JsonNodeUtils.STRING_SET, mapper));
builder.state(JsonNodeUtils.findStringValue(root, "state"));
builder.additionalParameters(
JsonNodeUtils.findValue(root, "additionalParameters", JsonNodeUtils.STRING_OBJECT_MAP, mapper));
builder.authorizationRequestUri(JsonNodeUtils.findStringValue(root, "authorizationRequestUri"));
builder.attributes(JsonNodeUtils.findValue(root, "attributes", JsonNodeUtils.STRING_OBJECT_MAP, mapper));
return builder.build();
}
private OAuth2AuthorizationRequest.Builder getBuilder(JsonParser parser,
AuthorizationGrantType authorizationGrantType) throws JsonParseException {
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationGrantType)) {
return OAuth2AuthorizationRequest.authorizationCode();
}
throw new JsonParseException(parser, "Invalid authorizationGrantType");
}
}
| 3,573 | 44.240506 | 158 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizedClientMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2AuthorizedClient}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizedClient
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2AuthorizedClientMixin {
@JsonCreator
OAuth2AuthorizedClientMixin(@JsonProperty("clientRegistration") ClientRegistration clientRegistration,
@JsonProperty("principalName") String principalName,
@JsonProperty("accessToken") OAuth2AccessToken accessToken,
@JsonProperty("refreshToken") OAuth2RefreshToken refreshToken) {
}
}
| 2,072 | 38.865385 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/DefaultOidcUserMixin.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.jackson2;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
/**
* This mixin class is used to serialize/deserialize {@link DefaultOidcUser}.
*
* @author Joe Grandja
* @since 5.3
* @see DefaultOidcUser
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(value = { "attributes" }, ignoreUnknown = true)
abstract class DefaultOidcUserMixin {
@JsonCreator
DefaultOidcUserMixin(@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities,
@JsonProperty("idToken") OidcIdToken idToken, @JsonProperty("userInfo") OidcUserInfo userInfo,
@JsonProperty("nameAttributeKey") String nameAttributeKey) {
}
}
| 2,056 | 37.811321 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/StdConverters.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.jackson2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* {@code StdConverter} implementations.
*
* @author Joe Grandja
* @since 5.3
*/
abstract class StdConverters {
static final class AccessTokenTypeConverter extends StdConverter<JsonNode, OAuth2AccessToken.TokenType> {
@Override
public OAuth2AccessToken.TokenType convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(value)) {
return OAuth2AccessToken.TokenType.BEARER;
}
return null;
}
}
static final class ClientAuthenticationMethodConverter extends StdConverter<JsonNode, ClientAuthenticationMethod> {
@Override
public ClientAuthenticationMethod convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue().equalsIgnoreCase(value)) {
return ClientAuthenticationMethod.CLIENT_SECRET_BASIC;
}
if (ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue().equalsIgnoreCase(value)) {
return ClientAuthenticationMethod.CLIENT_SECRET_POST;
}
if (ClientAuthenticationMethod.NONE.getValue().equalsIgnoreCase(value)) {
return ClientAuthenticationMethod.NONE;
}
return null;
}
}
static final class AuthorizationGrantTypeConverter extends StdConverter<JsonNode, AuthorizationGrantType> {
@Override
public AuthorizationGrantType convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.AUTHORIZATION_CODE;
}
if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.CLIENT_CREDENTIALS;
}
if (AuthorizationGrantType.PASSWORD.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.PASSWORD;
}
return new AuthorizationGrantType(value);
}
}
static final class AuthenticationMethodConverter extends StdConverter<JsonNode, AuthenticationMethod> {
@Override
public AuthenticationMethod convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthenticationMethod.HEADER.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.HEADER;
}
if (AuthenticationMethod.FORM.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.FORM;
}
if (AuthenticationMethod.QUERY.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.QUERY;
}
return null;
}
}
}
| 3,676 | 33.688679 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OidcIdTokenMixin.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.jackson2;
import java.time.Instant;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
/**
* This mixin class is used to serialize/deserialize {@link OidcIdToken}.
*
* @author Joe Grandja
* @since 5.3
* @see OidcIdToken
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OidcIdTokenMixin {
@JsonCreator
OidcIdTokenMixin(@JsonProperty("tokenValue") String tokenValue, @JsonProperty("issuedAt") Instant issuedAt,
@JsonProperty("expiresAt") Instant expiresAt, @JsonProperty("claims") Map<String, Object> claims) {
}
}
| 1,783 | 34.68 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationExceptionMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
/**
* This mixin class is used to serialize/deserialize
* {@link OAuth2AuthenticationException}.
*
* @author Dennis Neufeld
* @since 5.3.4
* @see OAuth2AuthenticationException
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true, value = { "cause", "stackTrace", "suppressedExceptions" })
abstract class OAuth2AuthenticationExceptionMixin {
@JsonCreator
OAuth2AuthenticationExceptionMixin(@JsonProperty("error") OAuth2Error error,
@JsonProperty("detailMessage") String message) {
}
}
| 1,847 | 36.714286 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/JsonNodeUtils.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.jackson2;
import java.util.Map;
import java.util.Set;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility class for {@code JsonNode}.
*
* @author Joe Grandja
* @since 5.3
*/
abstract class JsonNodeUtils {
static final TypeReference<Set<String>> STRING_SET = new TypeReference<Set<String>>() {
};
static final TypeReference<Map<String, Object>> STRING_OBJECT_MAP = new TypeReference<Map<String, Object>>() {
};
static String findStringValue(JsonNode jsonNode, String fieldName) {
if (jsonNode == null) {
return null;
}
JsonNode value = jsonNode.findValue(fieldName);
return (value != null && value.isTextual()) ? value.asText() : null;
}
static <T> T findValue(JsonNode jsonNode, String fieldName, TypeReference<T> valueTypeReference,
ObjectMapper mapper) {
if (jsonNode == null) {
return null;
}
JsonNode value = jsonNode.findValue(fieldName);
return (value != null && value.isContainerNode()) ? mapper.convertValue(value, valueTypeReference) : null;
}
static JsonNode findObjectNode(JsonNode jsonNode, String fieldName) {
if (jsonNode == null) {
return null;
}
JsonNode value = jsonNode.findValue(fieldName);
return (value != null && value.isObject()) ? value : null;
}
}
| 2,023 | 29.666667 | 111 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OidcUserInfoMixin.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.jackson2;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
/**
* This mixin class is used to serialize/deserialize {@link OidcUserInfo}.
*
* @author Joe Grandja
* @since 5.3
* @see OidcUserInfo
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OidcUserInfoMixin {
@JsonCreator
OidcUserInfoMixin(@JsonProperty("claims") Map<String, Object> claims) {
}
}
| 1,622 | 32.8125 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2UserAuthorityMixin.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.jackson2;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2UserAuthority}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2UserAuthority
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2UserAuthorityMixin {
@JsonCreator
OAuth2UserAuthorityMixin(@JsonProperty("authority") String authority,
@JsonProperty("attributes") Map<String, Object> attributes) {
}
}
| 1,713 | 33.979592 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/DefaultOAuth2UserMixin.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.jackson2;
import java.util.Collection;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
/**
* This mixin class is used to serialize/deserialize {@link DefaultOAuth2User}.
*
* @author Joe Grandja
* @since 5.3
* @see DefaultOAuth2User
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class DefaultOAuth2UserMixin {
@JsonCreator
DefaultOAuth2UserMixin(@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities,
@JsonProperty("attributes") Map<String, Object> attributes,
@JsonProperty("nameAttributeKey") String nameAttributeKey) {
}
}
| 1,889 | 35.346154 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AccessTokenMixin.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.jackson2;
import java.time.Instant;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2AccessToken}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AccessToken
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2AccessTokenMixin {
@JsonCreator
OAuth2AccessTokenMixin(
@JsonProperty("tokenType") @JsonDeserialize(
converter = StdConverters.AccessTokenTypeConverter.class) OAuth2AccessToken.TokenType tokenType,
@JsonProperty("tokenValue") String tokenValue, @JsonProperty("issuedAt") Instant issuedAt,
@JsonProperty("expiresAt") Instant expiresAt, @JsonProperty("scopes") Set<String> scopes) {
}
}
| 2,020 | 36.425926 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationDeserializer.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.jackson2;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthenticationMethod;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
/**
* A {@code JsonDeserializer} for {@link ClientRegistration}.
*
* @author Joe Grandja
* @since 5.3
* @see ClientRegistration
* @see ClientRegistrationMixin
*/
final class ClientRegistrationDeserializer extends JsonDeserializer<ClientRegistration> {
private static final StdConverter<JsonNode, ClientAuthenticationMethod> CLIENT_AUTHENTICATION_METHOD_CONVERTER = new StdConverters.ClientAuthenticationMethodConverter();
private static final StdConverter<JsonNode, AuthorizationGrantType> AUTHORIZATION_GRANT_TYPE_CONVERTER = new StdConverters.AuthorizationGrantTypeConverter();
private static final StdConverter<JsonNode, AuthenticationMethod> AUTHENTICATION_METHOD_CONVERTER = new StdConverters.AuthenticationMethodConverter();
@Override
public ClientRegistration deserialize(JsonParser parser, DeserializationContext context) throws IOException {
ObjectMapper mapper = (ObjectMapper) parser.getCodec();
JsonNode clientRegistrationNode = mapper.readTree(parser);
JsonNode providerDetailsNode = JsonNodeUtils.findObjectNode(clientRegistrationNode, "providerDetails");
JsonNode userInfoEndpointNode = JsonNodeUtils.findObjectNode(providerDetailsNode, "userInfoEndpoint");
return ClientRegistration
.withRegistrationId(JsonNodeUtils.findStringValue(clientRegistrationNode, "registrationId"))
.clientId(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientId"))
.clientSecret(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientSecret"))
.clientAuthenticationMethod(CLIENT_AUTHENTICATION_METHOD_CONVERTER
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "clientAuthenticationMethod")))
.authorizationGrantType(AUTHORIZATION_GRANT_TYPE_CONVERTER
.convert(JsonNodeUtils.findObjectNode(clientRegistrationNode, "authorizationGrantType")))
.redirectUri(JsonNodeUtils.findStringValue(clientRegistrationNode, "redirectUri"))
.scope(JsonNodeUtils.findValue(clientRegistrationNode, "scopes", JsonNodeUtils.STRING_SET, mapper))
.clientName(JsonNodeUtils.findStringValue(clientRegistrationNode, "clientName"))
.authorizationUri(JsonNodeUtils.findStringValue(providerDetailsNode, "authorizationUri"))
.tokenUri(JsonNodeUtils.findStringValue(providerDetailsNode, "tokenUri"))
.userInfoUri(JsonNodeUtils.findStringValue(userInfoEndpointNode, "uri"))
.userInfoAuthenticationMethod(AUTHENTICATION_METHOD_CONVERTER
.convert(JsonNodeUtils.findObjectNode(userInfoEndpointNode, "authenticationMethod")))
.userNameAttributeName(JsonNodeUtils.findStringValue(userInfoEndpointNode, "userNameAttributeName"))
.jwkSetUri(JsonNodeUtils.findStringValue(providerDetailsNode, "jwkSetUri"))
.issuerUri(JsonNodeUtils.findStringValue(providerDetailsNode, "issuerUri"))
.providerConfigurationMetadata(JsonNodeUtils.findValue(providerDetailsNode, "configurationMetadata",
JsonNodeUtils.STRING_OBJECT_MAP, mapper))
.build();
}
}
| 4,281 | 52.525 | 170 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthorizationRequestMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2AuthorizationRequest}.
* It also registers a custom deserializer {@link OAuth2AuthorizationRequestDeserializer}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthorizationRequest
* @see OAuth2AuthorizationRequestDeserializer
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonDeserialize(using = OAuth2AuthorizationRequestDeserializer.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2AuthorizationRequestMixin {
}
| 1,736 | 38.477273 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/ClientRegistrationMixin.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.jackson2;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
/**
* This mixin class is used to serialize/deserialize {@link ClientRegistration}. It also
* registers a custom deserializer {@link ClientRegistrationDeserializer}.
*
* @author Joe Grandja
* @since 5.3
* @see ClientRegistration
* @see ClientRegistrationDeserializer
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonDeserialize(using = ClientRegistrationDeserializer.class)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class ClientRegistrationMixin {
}
| 1,686 | 37.340909 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2AuthenticationTokenMixin.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.jackson2;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.user.OAuth2User;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2AuthenticationToken}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2AuthenticationToken
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(value = { "authenticated" }, ignoreUnknown = true)
abstract class OAuth2AuthenticationTokenMixin {
@JsonCreator
OAuth2AuthenticationTokenMixin(@JsonProperty("principal") OAuth2User principal,
@JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities,
@JsonProperty("authorizedClientRegistrationId") String authorizedClientRegistrationId) {
}
}
| 2,030 | 38.057692 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/jackson2/OAuth2RefreshTokenMixin.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.jackson2;
import java.time.Instant;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
/**
* This mixin class is used to serialize/deserialize {@link OAuth2RefreshToken}.
*
* @author Joe Grandja
* @since 5.3
* @see OAuth2RefreshToken
* @see OAuth2ClientJackson2Module
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
abstract class OAuth2RefreshTokenMixin {
@JsonCreator
OAuth2RefreshTokenMixin(@JsonProperty("tokenValue") String tokenValue, @JsonProperty("issuedAt") Instant issuedAt) {
}
}
| 1,690 | 34.229167 | 117 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/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.
*/
/**
* Classes and interfaces providing support to the client for initiating requests to the
* OpenID Connect 1.0 Provider's UserInfo Endpoint.
*/
package org.springframework.security.oauth2.client.oidc.userinfo;
| 838 | 37.136364 | 88 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequest.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.oidc.userinfo;
import java.util.Collections;
import java.util.Map;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.util.Assert;
/**
* Represents a request the {@link OidcUserService} uses when initiating a request to the
* UserInfo Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see ClientRegistration
* @see OAuth2AccessToken
* @see OidcIdToken
* @see OidcUserService
*/
public class OidcUserRequest extends OAuth2UserRequest {
private final OidcIdToken idToken;
/**
* Constructs an {@code OidcUserRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param accessToken the access token credential
* @param idToken the ID Token
*/
public OidcUserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken, OidcIdToken idToken) {
this(clientRegistration, accessToken, idToken, Collections.emptyMap());
}
/**
* Constructs an {@code OidcUserRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param accessToken the access token credential
* @param idToken the ID Token
* @param additionalParameters the additional parameters, may be empty
* @since 5.1
*/
public OidcUserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken, OidcIdToken idToken,
Map<String, Object> additionalParameters) {
super(clientRegistration, accessToken, additionalParameters);
Assert.notNull(idToken, "idToken cannot be null");
this.idToken = idToken;
}
/**
* Returns the {@link OidcIdToken ID Token} containing claims about the user.
* @return the {@link OidcIdToken} containing claims about the user.
*/
public OidcIdToken getIdToken() {
return this.idToken;
}
}
| 2,684 | 33.87013 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcReactiveOAuth2UserService.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.userinfo;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.userinfo.DefaultReactiveOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link ReactiveOAuth2UserService} that supports OpenID Connect
* 1.0 Provider's.
*
* @author Rob Winch
* @since 5.1
* @see ReactiveOAuth2UserService
* @see OidcUserRequest
* @see OidcUser
* @see DefaultOidcUser
* @see OidcUserInfo
*/
public class OidcReactiveOAuth2UserService implements ReactiveOAuth2UserService<OidcUserRequest, OidcUser> {
private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
private static final Converter<Map<String, Object>, Map<String, Object>> DEFAULT_CLAIM_TYPE_CONVERTER = new ClaimTypeConverter(
createDefaultClaimTypeConverters());
private ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = new DefaultReactiveOAuth2UserService();
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
/**
* Returns the default {@link Converter}'s used for type conversion of claim values
* for an {@link OidcUserInfo}.
* @return a {@link Map} of {@link Converter}'s keyed by {@link StandardClaimNames
* claim name}
* @since 5.2
*/
public static Map<String, Converter<Object, ?>> createDefaultClaimTypeConverters() {
Converter<Object, ?> booleanConverter = getConverter(TypeDescriptor.valueOf(Boolean.class));
Converter<Object, ?> instantConverter = getConverter(TypeDescriptor.valueOf(Instant.class));
Map<String, Converter<Object, ?>> claimTypeConverters = new HashMap<>();
claimTypeConverters.put(StandardClaimNames.EMAIL_VERIFIED, booleanConverter);
claimTypeConverters.put(StandardClaimNames.PHONE_NUMBER_VERIFIED, booleanConverter);
claimTypeConverters.put(StandardClaimNames.UPDATED_AT, instantConverter);
return claimTypeConverters;
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
targetDescriptor);
}
@Override
public Mono<OidcUser> loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
Assert.notNull(userRequest, "userRequest cannot be null");
// @formatter:off
return getUserInfo(userRequest)
.map((userInfo) ->
new OidcUserAuthority(userRequest.getIdToken(), userInfo)
)
.defaultIfEmpty(new OidcUserAuthority(userRequest.getIdToken(), null))
.map((authority) -> {
OidcUserInfo userInfo = authority.getUserInfo();
Set<GrantedAuthority> authorities = new HashSet<>();
authorities.add(authority);
OAuth2AccessToken token = userRequest.getAccessToken();
for (String scope : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
}
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails()
.getUserInfoEndpoint().getUserNameAttributeName();
if (StringUtils.hasText(userNameAttributeName)) {
return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo,
userNameAttributeName);
}
return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
});
// @formatter:on
}
private Mono<OidcUserInfo> getUserInfo(OidcUserRequest userRequest) {
if (!OidcUserRequestUtils.shouldRetrieveUserInfo(userRequest)) {
return Mono.empty();
}
// @formatter:off
return this.oauth2UserService
.loadUser(userRequest)
.map(OAuth2User::getAttributes)
.map((claims) -> convertClaims(claims, userRequest.getClientRegistration()))
.map(OidcUserInfo::new)
.doOnNext((userInfo) -> {
String subject = userInfo.getSubject();
if (subject == null || !subject.equals(userRequest.getIdToken().getSubject())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
});
// @formatter:on
}
private Map<String, Object> convertClaims(Map<String, Object> claims, ClientRegistration clientRegistration) {
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
.apply(clientRegistration);
return (claimTypeConverter != null) ? claimTypeConverter.convert(claims)
: DEFAULT_CLAIM_TYPE_CONVERTER.convert(claims);
}
public void setOauth2UserService(ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService) {
Assert.notNull(oauth2UserService, "oauth2UserService cannot be null");
this.oauth2UserService = oauth2UserService;
}
/**
* Sets the factory that provides a {@link Converter} used for type conversion of
* claim values for an {@link OidcUserInfo}. The default is {@link ClaimTypeConverter}
* for all {@link ClientRegistration clients}.
* @param claimTypeConverterFactory the factory that provides a {@link Converter} used
* for type conversion of claim values for a specific {@link ClientRegistration
* client}
* @since 5.2
*/
public final void setClaimTypeConverterFactory(
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) {
Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null");
this.claimTypeConverterFactory = claimTypeConverterFactory;
}
}
| 7,786 | 44.011561 | 128 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserRequestUtils.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.oidc.userinfo;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* Utilities for working with the {@link OidcUserRequest}
*
* @author Rob Winch
* @since 5.1
*/
final class OidcUserRequestUtils {
/**
* Determines if an {@link OidcUserRequest} should attempt to retrieve the user info
* endpoint. Will return true if all of the following are true:
*
* <ul>
* <li>The user info endpoint is defined on the ClientRegistration</li>
* <li>The Client Registration uses the
* {@link AuthorizationGrantType#AUTHORIZATION_CODE} and scopes in the access token
* are defined in the {@link ClientRegistration}</li>
* </ul>
* @param userRequest
* @return
*/
static boolean shouldRetrieveUserInfo(OidcUserRequest userRequest) {
// Auto-disabled if UserInfo Endpoint URI is not provided
ClientRegistration clientRegistration = userRequest.getClientRegistration();
if (!StringUtils.hasLength(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri())) {
return false;
}
// The Claims requested by the profile, email, address, and phone scope values
// are returned from the UserInfo Endpoint (as described in Section 5.3.2),
// when a response_type value is used that results in an Access Token being
// issued.
// However, when no Access Token is issued, which is the case for the
// response_type=id_token,
// the resulting Claims are returned in the ID Token.
// The Authorization Code Grant Flow, which is response_type=code, results in an
// Access Token being issued.
if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(clientRegistration.getAuthorizationGrantType())) {
// Return true if there is at least one match between the authorized scope(s)
// and UserInfo scope(s)
return CollectionUtils.containsAny(userRequest.getAccessToken().getScopes(),
userRequest.getClientRegistration().getScopes());
}
return false;
}
private OidcUserRequestUtils() {
}
}
| 2,823 | 37.684932 | 105 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/userinfo/OidcUserService.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.userinfo;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* An implementation of an {@link OAuth2UserService} that supports OpenID Connect 1.0
* Provider's.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2UserService
* @see OidcUserRequest
* @see OidcUser
* @see DefaultOidcUser
* @see OidcUserInfo
*/
public class OidcUserService implements OAuth2UserService<OidcUserRequest, OidcUser> {
private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
private static final Converter<Map<String, Object>, Map<String, Object>> DEFAULT_CLAIM_TYPE_CONVERTER = new ClaimTypeConverter(
createDefaultClaimTypeConverters());
private Set<String> accessibleScopes = new HashSet<>(
Arrays.asList(OidcScopes.PROFILE, OidcScopes.EMAIL, OidcScopes.ADDRESS, OidcScopes.PHONE));
private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService = new DefaultOAuth2UserService();
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
/**
* Returns the default {@link Converter}'s used for type conversion of claim values
* for an {@link OidcUserInfo}.
* @return a {@link Map} of {@link Converter}'s keyed by {@link StandardClaimNames
* claim name}
* @since 5.2
*/
public static Map<String, Converter<Object, ?>> createDefaultClaimTypeConverters() {
Converter<Object, ?> booleanConverter = getConverter(TypeDescriptor.valueOf(Boolean.class));
Converter<Object, ?> instantConverter = getConverter(TypeDescriptor.valueOf(Instant.class));
Map<String, Converter<Object, ?>> claimTypeConverters = new HashMap<>();
claimTypeConverters.put(StandardClaimNames.EMAIL_VERIFIED, booleanConverter);
claimTypeConverters.put(StandardClaimNames.PHONE_NUMBER_VERIFIED, booleanConverter);
claimTypeConverters.put(StandardClaimNames.UPDATED_AT, instantConverter);
return claimTypeConverters;
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
targetDescriptor);
}
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
Assert.notNull(userRequest, "userRequest cannot be null");
OidcUserInfo userInfo = null;
if (this.shouldRetrieveUserInfo(userRequest)) {
OAuth2User oauth2User = this.oauth2UserService.loadUser(userRequest);
Map<String, Object> claims = getClaims(userRequest, oauth2User);
userInfo = new OidcUserInfo(claims);
// https://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
// 1) The sub (subject) Claim MUST always be returned in the UserInfo Response
if (userInfo.getSubject() == null) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
// 2) Due to the possibility of token substitution attacks (see Section
// 16.11),
// the UserInfo Response is not guaranteed to be about the End-User
// identified by the sub (subject) element of the ID Token.
// The sub Claim in the UserInfo Response MUST be verified to exactly match
// the sub Claim in the ID Token; if they do not match,
// the UserInfo Response values MUST NOT be used.
if (!userInfo.getSubject().equals(userRequest.getIdToken().getSubject())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OidcUserAuthority(userRequest.getIdToken(), userInfo));
OAuth2AccessToken token = userRequest.getAccessToken();
for (String authority : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return getUser(userRequest, userInfo, authorities);
}
private Map<String, Object> getClaims(OidcUserRequest userRequest, OAuth2User oauth2User) {
Converter<Map<String, Object>, Map<String, Object>> converter = this.claimTypeConverterFactory
.apply(userRequest.getClientRegistration());
if (converter != null) {
return converter.convert(oauth2User.getAttributes());
}
return DEFAULT_CLAIM_TYPE_CONVERTER.convert(oauth2User.getAttributes());
}
private OidcUser getUser(OidcUserRequest userRequest, OidcUserInfo userInfo, Set<GrantedAuthority> authorities) {
ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails();
String userNameAttributeName = providerDetails.getUserInfoEndpoint().getUserNameAttributeName();
if (StringUtils.hasText(userNameAttributeName)) {
return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo, userNameAttributeName);
}
return new DefaultOidcUser(authorities, userRequest.getIdToken(), userInfo);
}
private boolean shouldRetrieveUserInfo(OidcUserRequest userRequest) {
// Auto-disabled if UserInfo Endpoint URI is not provided
ProviderDetails providerDetails = userRequest.getClientRegistration().getProviderDetails();
if (!StringUtils.hasLength(providerDetails.getUserInfoEndpoint().getUri())) {
return false;
}
// The Claims requested by the profile, email, address, and phone scope values
// are returned from the UserInfo Endpoint (as described in Section 5.3.2),
// when a response_type value is used that results in an Access Token being
// issued.
// However, when no Access Token is issued, which is the case for the
// response_type=id_token,
// the resulting Claims are returned in the ID Token.
// The Authorization Code Grant Flow, which is response_type=code, results in an
// Access Token being issued.
if (AuthorizationGrantType.AUTHORIZATION_CODE
.equals(userRequest.getClientRegistration().getAuthorizationGrantType())) {
// Return true if there is at least one match between the authorized scope(s)
// and accessible scope(s)
//
// Also return true if authorized scope(s) is empty, because the provider has
// not indicated which scopes are accessible via the access token
// @formatter:off
return this.accessibleScopes.isEmpty()
|| CollectionUtils.isEmpty(userRequest.getAccessToken().getScopes())
|| CollectionUtils.containsAny(userRequest.getAccessToken().getScopes(), this.accessibleScopes);
// @formatter:on
}
return false;
}
/**
* Sets the {@link OAuth2UserService} used when requesting the user info resource.
* @param oauth2UserService the {@link OAuth2UserService} used when requesting the
* user info resource.
* @since 5.1
*/
public final void setOauth2UserService(OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService) {
Assert.notNull(oauth2UserService, "oauth2UserService cannot be null");
this.oauth2UserService = oauth2UserService;
}
/**
* Sets the factory that provides a {@link Converter} used for type conversion of
* claim values for an {@link OidcUserInfo}. The default is {@link ClaimTypeConverter}
* for all {@link ClientRegistration clients}.
* @param claimTypeConverterFactory the factory that provides a {@link Converter} used
* for type conversion of claim values for a specific {@link ClientRegistration
* client}
* @since 5.2
*/
public final void setClaimTypeConverterFactory(
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) {
Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null");
this.claimTypeConverterFactory = claimTypeConverterFactory;
}
/**
* Sets the scope(s) that allow access to the user info resource. The default is
* {@link OidcScopes#PROFILE profile}, {@link OidcScopes#EMAIL email},
* {@link OidcScopes#ADDRESS address} and {@link OidcScopes#PHONE phone}. The scope(s)
* are checked against the "granted" scope(s) associated to the
* {@link OidcUserRequest#getAccessToken() access token} to determine if the user info
* resource is accessible or not. If there is at least one match, the user info
* resource will be requested, otherwise it will not.
* @param accessibleScopes the scope(s) that allow access to the user info resource
* @since 5.2
*/
public final void setAccessibleScopes(Set<String> accessibleScopes) {
Assert.notNull(accessibleScopes, "accessibleScopes cannot be null");
this.accessibleScopes = accessibleScopes;
}
}
| 11,213 | 47.545455 | 128 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/logout/OidcClientInitiatedLogoutSuccessHandler.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.oidc.web.logout;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A logout success handler for initiating OIDC logout through the user agent.
*
* @author Josh Cummings
* @since 5.2
* @see <a href=
* "https://openid.net/specs/openid-connect-rpinitiated-1_0.html">RP-Initiated Logout</a>
* @see org.springframework.security.web.authentication.logout.LogoutSuccessHandler
*/
public class OidcClientInitiatedLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
private final ClientRegistrationRepository clientRegistrationRepository;
private String postLogoutRedirectUri;
public OidcClientInitiatedLogoutSuccessHandler(ClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) {
String targetUrl = null;
if (authentication instanceof OAuth2AuthenticationToken && authentication.getPrincipal() instanceof OidcUser) {
String registrationId = ((OAuth2AuthenticationToken) authentication).getAuthorizedClientRegistrationId();
ClientRegistration clientRegistration = this.clientRegistrationRepository
.findByRegistrationId(registrationId);
URI endSessionEndpoint = this.endSessionEndpoint(clientRegistration);
if (endSessionEndpoint != null) {
String idToken = idToken(authentication);
String postLogoutRedirectUri = postLogoutRedirectUri(request, clientRegistration);
targetUrl = endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri);
}
}
return (targetUrl != null) ? targetUrl : super.determineTargetUrl(request, response);
}
private URI endSessionEndpoint(ClientRegistration clientRegistration) {
if (clientRegistration != null) {
ProviderDetails providerDetails = clientRegistration.getProviderDetails();
Object endSessionEndpoint = providerDetails.getConfigurationMetadata().get("end_session_endpoint");
if (endSessionEndpoint != null) {
return URI.create(endSessionEndpoint.toString());
}
}
return null;
}
private String idToken(Authentication authentication) {
return ((OidcUser) authentication.getPrincipal()).getIdToken().getTokenValue();
}
private String postLogoutRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
if (this.postLogoutRedirectUri == null) {
return null;
}
// @formatter:off
UriComponents uriComponents = UriComponentsBuilder
.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(null)
.fragment(null)
.build();
Map<String, String> uriVariables = new HashMap<>();
String scheme = uriComponents.getScheme();
uriVariables.put("baseScheme", (scheme != null) ? scheme : "");
uriVariables.put("baseUrl", uriComponents.toUriString());
String host = uriComponents.getHost();
uriVariables.put("baseHost", (host != null) ? host : "");
String path = uriComponents.getPath();
uriVariables.put("basePath", (path != null) ? path : "");
int port = uriComponents.getPort();
uriVariables.put("basePort", (port == -1) ? "" : ":" + port);
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
return UriComponentsBuilder.fromUriString(this.postLogoutRedirectUri)
.buildAndExpand(uriVariables)
.toUriString();
// @formatter:on
}
private String endpointUri(URI endSessionEndpoint, String idToken, String postLogoutRedirectUri) {
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint);
builder.queryParam("id_token_hint", idToken);
if (postLogoutRedirectUri != null) {
builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri);
}
// @formatter:off
return builder.encode(StandardCharsets.UTF_8)
.build()
.toUriString();
// @formatter:on
}
/**
* Set the post logout redirect uri template.
*
* <br />
* The supported uri template variables are: {@code {baseScheme}}, {@code {baseHost}},
* {@code {basePort}} and {@code {basePath}}.
*
* <br />
* <b>NOTE:</b> {@code "{baseUrl}"} is also supported, which is the same as
* {@code "{baseScheme}://{baseHost}{basePort}{basePath}"}
*
* <pre>
* handler.setPostLogoutRedirectUri("{baseUrl}");
* </pre>
*
* will make so that {@code post_logout_redirect_uri} will be set to the base url for
* the client application.
* @param postLogoutRedirectUri - A template for creating the
* {@code post_logout_redirect_uri} query parameter
* @since 5.3
*/
public void setPostLogoutRedirectUri(String postLogoutRedirectUri) {
Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be null");
this.postLogoutRedirectUri = postLogoutRedirectUri;
}
}
| 6,519 | 38.277108 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/web/server/logout/OidcClientInitiatedServerLogoutSuccessHandler.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.oidc.web.server.logout;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.server.DefaultServerRedirectStrategy;
import org.springframework.security.web.server.ServerRedirectStrategy;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.RedirectServerLogoutSuccessHandler;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.util.Assert;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A reactive logout success handler for initiating OIDC logout through the user agent.
*
* @author Josh Cummings
* @since 5.2
* @see <a href=
* "https://openid.net/specs/openid-connect-rpinitiated-1_0.html">RP-Initiated Logout</a>
* @see org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler
*/
public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogoutSuccessHandler {
private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
private final RedirectServerLogoutSuccessHandler serverLogoutSuccessHandler = new RedirectServerLogoutSuccessHandler();
private final ReactiveClientRegistrationRepository clientRegistrationRepository;
private String postLogoutRedirectUri;
/**
* Constructs an {@link OidcClientInitiatedServerLogoutSuccessHandler} with the
* provided parameters
* @param clientRegistrationRepository The
* {@link ReactiveClientRegistrationRepository} to use to derive the
* end_session_endpoint value
*/
public OidcClientInitiatedServerLogoutSuccessHandler(
ReactiveClientRegistrationRepository clientRegistrationRepository) {
Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
this.clientRegistrationRepository = clientRegistrationRepository;
}
@Override
public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) {
// @formatter:off
return Mono.just(authentication)
.filter(OAuth2AuthenticationToken.class::isInstance)
.filter((token) -> authentication.getPrincipal() instanceof OidcUser)
.map(OAuth2AuthenticationToken.class::cast)
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId)
.flatMap(this.clientRegistrationRepository::findByRegistrationId)
.flatMap((clientRegistration) -> {
URI endSessionEndpoint = endSessionEndpoint(clientRegistration);
if (endSessionEndpoint == null) {
return Mono.empty();
}
String idToken = idToken(authentication);
String postLogoutRedirectUri = postLogoutRedirectUri(exchange.getExchange().getRequest(), clientRegistration);
return Mono.just(endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri));
})
.switchIfEmpty(
this.serverLogoutSuccessHandler.onLogoutSuccess(exchange, authentication).then(Mono.empty())
)
.flatMap((endpointUri) -> this.redirectStrategy.sendRedirect(exchange.getExchange(), URI.create(endpointUri)));
// @formatter:on
}
private URI endSessionEndpoint(ClientRegistration clientRegistration) {
if (clientRegistration != null) {
Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata()
.get("end_session_endpoint");
if (endSessionEndpoint != null) {
return URI.create(endSessionEndpoint.toString());
}
}
return null;
}
private String endpointUri(URI endSessionEndpoint, String idToken, String postLogoutRedirectUri) {
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint);
builder.queryParam("id_token_hint", idToken);
if (postLogoutRedirectUri != null) {
builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri);
}
return builder.encode(StandardCharsets.UTF_8).build().toUriString();
}
private String idToken(Authentication authentication) {
return ((OidcUser) authentication.getPrincipal()).getIdToken().getTokenValue();
}
private String postLogoutRedirectUri(ServerHttpRequest request, ClientRegistration clientRegistration) {
if (this.postLogoutRedirectUri == null) {
return null;
}
// @formatter:off
UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI())
.replacePath(request.getPath().contextPath().value())
.replaceQuery(null)
.fragment(null)
.build();
Map<String, String> uriVariables = new HashMap<>();
String scheme = uriComponents.getScheme();
uriVariables.put("baseScheme", (scheme != null) ? scheme : "");
uriVariables.put("baseUrl", uriComponents.toUriString());
String host = uriComponents.getHost();
uriVariables.put("baseHost", (host != null) ? host : "");
String path = uriComponents.getPath();
uriVariables.put("basePath", (path != null) ? path : "");
int port = uriComponents.getPort();
uriVariables.put("basePort", (port == -1) ? "" : ":" + port);
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
return UriComponentsBuilder.fromUriString(this.postLogoutRedirectUri)
.buildAndExpand(uriVariables)
.toUriString();
// @formatter:on
}
/**
* Set the post logout redirect uri template.
*
* <br />
* The supported uri template variables are: {@code {baseScheme}}, {@code {baseHost}},
* {@code {basePort}} and {@code {basePath}}.
*
* <br />
* <b>NOTE:</b> {@code {baseUrl}} is also supported, which is the same as
* {@code "{baseScheme}://{baseHost}{basePort}{basePath}"}
*
* <pre>
* handler.setPostLogoutRedirectUri("{baseUrl}");
* </pre>
*
* will make so that {@code post_logout_redirect_uri} will be set to the base url for
* the client application.
* @param postLogoutRedirectUri - A template for creating the
* {@code post_logout_redirect_uri} query parameter
* @since 5.3
*/
public void setPostLogoutRedirectUri(String postLogoutRedirectUri) {
Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be null");
this.postLogoutRedirectUri = postLogoutRedirectUri;
}
/**
* The URL to redirect to after successfully logging out when not originally an OIDC
* login
* @param logoutSuccessUrl the url to redirect to. Default is "/login?logout".
*/
public void setLogoutSuccessUrl(URI logoutSuccessUrl) {
Assert.notNull(logoutSuccessUrl, "logoutSuccessUrl cannot be null");
this.serverLogoutSuccessHandler.setLogoutSuccessUrl(logoutSuccessUrl);
}
}
| 7,765 | 39.447917 | 120 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeReactiveAuthenticationManager.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.oidc.authentication;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collection;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory;
import org.springframework.util.Assert;
/**
* An implementation of an
* {@link org.springframework.security.authentication.AuthenticationProvider} for OAuth
* 2.0 Login, which leverages the OAuth 2.0 Authorization Code Grant Flow.
* <p>
* This {@link org.springframework.security.authentication.AuthenticationProvider} is
* responsible for authenticating an Authorization Code credential with the Authorization
* Server's Token Endpoint and if valid, exchanging it for an Access Token credential.
* <p>
* It will also obtain the user attributes of the End-User (Resource Owner) from the
* UserInfo Endpoint using an
* {@link org.springframework.security.oauth2.client.userinfo.OAuth2UserService}, which
* will create a {@code Principal} in the form of an {@link OAuth2User}. The
* {@code OAuth2User} is then associated to the {@link OAuth2LoginAuthenticationToken} to
* complete the authentication.
*
* @author Rob Winch
* @author Mark Heckler
* @since 5.1
* @see OAuth2LoginAuthenticationToken
* @see ReactiveOAuth2AccessTokenResponseClient
* @see ReactiveOAuth2UserService
* @see OAuth2User
* @see ReactiveOidcIdTokenDecoderFactory
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token
* Request</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token
* Response</a>
*/
public class OidcAuthorizationCodeReactiveAuthenticationManager implements ReactiveAuthenticationManager {
private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter";
private static final String INVALID_ID_TOKEN_ERROR_CODE = "invalid_id_token";
private static final String INVALID_NONCE_ERROR_CODE = "invalid_nonce";
private final ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private final ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService;
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
private ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new ReactiveOidcIdTokenDecoderFactory();
public OidcAuthorizationCodeReactiveAuthenticationManager(
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient,
ReactiveOAuth2UserService<OidcUserRequest, OidcUser> userService) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
Assert.notNull(userService, "userService cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
this.userService = userService;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.defer(() -> {
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
// scope REQUIRED. OpenID Connect requests MUST contain the "openid" scope
// value.
if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes()
.contains("openid")) {
// This is an OpenID Connect Authentication Request so return empty
// and let OAuth2LoginReactiveAuthenticationManager handle it instead
return Mono.empty();
}
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication
.getAuthorizationExchange().getAuthorizationResponse();
if (authorizationResponse.statusError()) {
return Mono.error(new OAuth2AuthenticationException(authorizationResponse.getError(),
authorizationResponse.getError().toString()));
}
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
return Mono.error(new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()));
}
OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(
authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange());
return this.accessTokenResponseClient.getTokenResponse(authzRequest).flatMap(
(accessTokenResponse) -> authenticationResult(authorizationCodeAuthentication, accessTokenResponse))
.onErrorMap(OAuth2AuthorizationException.class,
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
.onErrorMap(JwtException.class, (e) -> {
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, e.getMessage(),
null);
return new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(),
e);
});
});
}
/**
* Sets the {@link ReactiveJwtDecoderFactory} used for {@link OidcIdToken} signature
* verification. The factory returns a {@link ReactiveJwtDecoder} associated to the
* provided {@link ClientRegistration}.
* @param jwtDecoderFactory the {@link ReactiveJwtDecoderFactory} used for
* {@link OidcIdToken} signature verification
* @since 5.2
*/
public final void setJwtDecoderFactory(ReactiveJwtDecoderFactory<ClientRegistration> jwtDecoderFactory) {
Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null");
this.jwtDecoderFactory = jwtDecoderFactory;
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OidcUser#getAuthorities()} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
* @since 5.4
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
private Mono<OAuth2LoginAuthenticationToken> authenticationResult(
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication,
OAuth2AccessTokenResponse accessTokenResponse) {
OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE,
"Missing (required) ID Token in Token Response for Client Registration: "
+ clientRegistration.getRegistrationId(),
null);
return Mono.error(new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString()));
}
// @formatter:off
return createOidcToken(clientRegistration, accessTokenResponse)
.doOnNext((idToken) -> validateNonce(authorizationCodeAuthentication, idToken))
.map((idToken) -> new OidcUserRequest(clientRegistration, accessToken, idToken, additionalParameters))
.flatMap(this.userService::loadUser)
.map((oauth2User) -> {
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
.mapAuthorities(oauth2User.getAuthorities());
return new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange(), oauth2User, mappedAuthorities,
accessToken, accessTokenResponse.getRefreshToken());
});
// @formatter:on
}
private Mono<OidcIdToken> createOidcToken(ClientRegistration clientRegistration,
OAuth2AccessTokenResponse accessTokenResponse) {
ReactiveJwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
String rawIdToken = (String) accessTokenResponse.getAdditionalParameters().get(OidcParameterNames.ID_TOKEN);
// @formatter:off
return jwtDecoder.decode(rawIdToken)
.map((jwt) ->
new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims())
);
// @formatter:on
}
private static Mono<OidcIdToken> validateNonce(
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest()
.getAttribute(OidcParameterNames.NONCE);
if (requestNonce != null) {
String nonceHash = getNonceHash(requestNonce);
String nonceHashClaim = idToken.getNonce();
if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
return Mono.just(idToken);
}
private static String getNonceHash(String requestNonce) {
try {
return createHash(requestNonce);
}
catch (NoSuchAlgorithmException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
static String createHash(String nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
| 12,694 | 48.980315 | 140 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/package-info.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Support classes and interfaces for authenticating and authorizing a client with an
* OpenID Connect 1.0 Provider using a specific authorization grant flow.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
| 863 | 38.272727 | 85 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenValidator.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.oidc.authentication;
import java.net.URL;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
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.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* An {@link OAuth2TokenValidator} responsible for validating the claims in an
* {@link OidcIdToken ID Token}.
*
* @author Rob Winch
* @author Joe Grandja
* @since 5.1
* @see OAuth2TokenValidator
* @see Jwt
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation">ID Token
* Validation</a>
*/
public final class OidcIdTokenValidator implements OAuth2TokenValidator<Jwt> {
private static final Duration DEFAULT_CLOCK_SKEW = Duration.ofSeconds(60);
private final ClientRegistration clientRegistration;
private Duration clockSkew = DEFAULT_CLOCK_SKEW;
private Clock clock = Clock.systemUTC();
public OidcIdTokenValidator(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
this.clientRegistration = clientRegistration;
}
@Override
public OAuth2TokenValidatorResult validate(Jwt idToken) {
// 3.1.3.7 ID Token Validation
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
Map<String, Object> invalidClaims = validateRequiredClaims(idToken);
if (!invalidClaims.isEmpty()) {
return OAuth2TokenValidatorResult.failure(invalidIdToken(invalidClaims));
}
// 2. The Issuer Identifier for the OpenID Provider (which is typically obtained
// during Discovery)
// MUST exactly match the value of the iss (issuer) Claim.
String metadataIssuer = this.clientRegistration.getProviderDetails().getIssuerUri();
if (metadataIssuer != null && !Objects.equals(metadataIssuer, idToken.getIssuer().toExternalForm())) {
invalidClaims.put(IdTokenClaimNames.ISS, idToken.getIssuer());
}
// 3. The Client MUST validate that the aud (audience) Claim contains its
// client_id value
// registered at the Issuer identified by the iss (issuer) Claim as an audience.
// The aud (audience) Claim MAY contain an array with more than one element.
// The ID Token MUST be rejected if the ID Token does not list the Client as a
// valid audience,
// or if it contains additional audiences not trusted by the Client.
if (!idToken.getAudience().contains(this.clientRegistration.getClientId())) {
invalidClaims.put(IdTokenClaimNames.AUD, idToken.getAudience());
}
// 4. If the ID Token contains multiple audiences,
// the Client SHOULD verify that an azp Claim is present.
String authorizedParty = idToken.getClaimAsString(IdTokenClaimNames.AZP);
if (idToken.getAudience().size() > 1 && authorizedParty == null) {
invalidClaims.put(IdTokenClaimNames.AZP, authorizedParty);
}
// 5. If an azp (authorized party) Claim is present,
// the Client SHOULD verify that its client_id is the Claim Value.
if (authorizedParty != null && !authorizedParty.equals(this.clientRegistration.getClientId())) {
invalidClaims.put(IdTokenClaimNames.AZP, authorizedParty);
}
// 7. The alg value SHOULD be the default of RS256 or the algorithm sent by the
// Client
// in the id_token_signed_response_alg parameter during Registration.
// TODO Depends on gh-4413
// 9. The current time MUST be before the time represented by the exp Claim.
Instant now = Instant.now(this.clock);
if (now.minus(this.clockSkew).isAfter(idToken.getExpiresAt())) {
invalidClaims.put(IdTokenClaimNames.EXP, idToken.getExpiresAt());
}
// 10. The iat Claim can be used to reject tokens that were issued too far away
// from the current time,
// limiting the amount of time that nonces need to be stored to prevent attacks.
// The acceptable range is Client specific.
if (now.plus(this.clockSkew).isBefore(idToken.getIssuedAt())) {
invalidClaims.put(IdTokenClaimNames.IAT, idToken.getIssuedAt());
}
if (!invalidClaims.isEmpty()) {
return OAuth2TokenValidatorResult.failure(invalidIdToken(invalidClaims));
}
return OAuth2TokenValidatorResult.success();
}
/**
* Sets the maximum acceptable clock skew. The default is 60 seconds. The clock skew
* is used when validating the {@link JwtClaimNames#EXP exp} and
* {@link JwtClaimNames#IAT iat} claims.
* @param clockSkew the maximum acceptable clock skew
* @since 5.2
*/
public void setClockSkew(Duration clockSkew) {
Assert.notNull(clockSkew, "clockSkew cannot be null");
Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0");
this.clockSkew = clockSkew;
}
/**
* Sets the {@link Clock} used in {@link Instant#now(Clock)} when validating the
* {@link JwtClaimNames#EXP exp} and {@link JwtClaimNames#IAT iat} claims.
* @param clock the clock
* @since 5.3
*/
public void setClock(Clock clock) {
Assert.notNull(clock, "clock cannot be null");
this.clock = clock;
}
private static OAuth2Error invalidIdToken(Map<String, Object> invalidClaims) {
return new OAuth2Error("invalid_id_token", "The ID Token contains invalid claims: " + invalidClaims,
"https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation");
}
private static Map<String, Object> validateRequiredClaims(Jwt idToken) {
Map<String, Object> requiredClaims = new HashMap<>();
URL issuer = idToken.getIssuer();
if (issuer == null) {
requiredClaims.put(IdTokenClaimNames.ISS, issuer);
}
String subject = idToken.getSubject();
if (subject == null) {
requiredClaims.put(IdTokenClaimNames.SUB, subject);
}
List<String> audience = idToken.getAudience();
if (CollectionUtils.isEmpty(audience)) {
requiredClaims.put(IdTokenClaimNames.AUD, audience);
}
Instant expiresAt = idToken.getExpiresAt();
if (expiresAt == null) {
requiredClaims.put(IdTokenClaimNames.EXP, expiresAt);
}
Instant issuedAt = idToken.getIssuedAt();
if (issuedAt == null) {
requiredClaims.put(IdTokenClaimNames.IAT, issuedAt);
}
return requiredClaims;
}
}
| 7,270 | 39.394444 | 104 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/OidcAuthorizationCodeAuthenticationProvider.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collection;
import java.util.Map;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtDecoderFactory;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AuthenticationProvider} for the OpenID Connect Core 1.0
* Authorization Code Grant Flow.
* <p>
* This {@link AuthenticationProvider} is responsible for authenticating an Authorization
* Code credential with the Authorization Server's Token Endpoint and if valid, exchanging
* it for an Access Token credential.
* <p>
* It will also obtain the user attributes of the End-User (Resource Owner) from the
* UserInfo Endpoint using an {@link OAuth2UserService}, which will create a
* {@code Principal} in the form of an {@link OidcUser}. The {@code OidcUser} is then
* associated to the {@link OAuth2LoginAuthenticationToken} to complete the
* authentication.
*
* @author Joe Grandja
* @author Mark Heckler
* @since 5.0
* @see OAuth2LoginAuthenticationToken
* @see OAuth2AccessTokenResponseClient
* @see OidcUserService
* @see OidcUser
* @see OidcIdTokenDecoderFactory
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth">Section 3.1
* Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#TokenRequest">Section 3.1.3.1
* Token Request</a>
* @see <a target="_blank" href=
* "https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse">Section 3.1.3.3
* Token Response</a>
*/
public class OidcAuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter";
private static final String INVALID_ID_TOKEN_ERROR_CODE = "invalid_id_token";
private static final String INVALID_NONCE_ERROR_CODE = "invalid_nonce";
private final OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
private final OAuth2UserService<OidcUserRequest, OidcUser> userService;
private JwtDecoderFactory<ClientRegistration> jwtDecoderFactory = new OidcIdTokenDecoderFactory();
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
/**
* Constructs an {@code OidcAuthorizationCodeAuthenticationProvider} using the
* provided parameters.
* @param accessTokenResponseClient the client used for requesting the access token
* credential from the Token Endpoint
* @param userService the service used for obtaining the user attributes of the
* End-User from the UserInfo Endpoint
*/
public OidcAuthorizationCodeAuthenticationProvider(
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient,
OAuth2UserService<OidcUserRequest, OidcUser> userService) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
Assert.notNull(userService, "userService cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
this.userService = userService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication;
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
// scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
if (!authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getScopes()
.contains(OidcScopes.OPENID)) {
// This is NOT an OpenID Connect Authentication Request so return null
// and let OAuth2LoginAuthenticationProvider handle it instead
return null;
}
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest();
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationResponse();
if (authorizationResponse.statusError()) {
throw new OAuth2AuthenticationException(authorizationResponse.getError(),
authorizationResponse.getError().toString());
}
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
OAuth2AccessTokenResponse accessTokenResponse = getResponse(authorizationCodeAuthentication);
ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE,
"Missing (required) ID Token in Token Response for Client Registration: "
+ clientRegistration.getRegistrationId(),
null);
throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString());
}
OidcIdToken idToken = createOidcToken(clientRegistration, accessTokenResponse);
validateNonce(authorizationRequest, idToken);
OidcUser oidcUser = this.userService.loadUser(new OidcUserRequest(clientRegistration,
accessTokenResponse.getAccessToken(), idToken, additionalParameters));
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
.mapAuthorities(oidcUser.getAuthorities());
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities,
accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken());
authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
return authenticationResult;
}
private OAuth2AccessTokenResponse getResponse(OAuth2LoginAuthenticationToken authorizationCodeAuthentication) {
try {
return this.accessTokenResponseClient.getTokenResponse(
new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange()));
}
catch (OAuth2AuthorizationException ex) {
OAuth2Error oauth2Error = ex.getError();
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}
}
private void validateNonce(OAuth2AuthorizationRequest authorizationRequest, OidcIdToken idToken) {
String requestNonce = authorizationRequest.getAttribute(OidcParameterNames.NONCE);
if (requestNonce == null) {
return;
}
String nonceHash = getNonceHash(requestNonce);
String nonceHashClaim = idToken.getNonce();
if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
private String getNonceHash(String requestNonce) {
try {
return createHash(requestNonce);
}
catch (NoSuchAlgorithmException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
}
/**
* Sets the {@link JwtDecoderFactory} used for {@link OidcIdToken} signature
* verification. The factory returns a {@link JwtDecoder} associated to the provided
* {@link ClientRegistration}.
* @param jwtDecoderFactory the {@link JwtDecoderFactory} used for {@link OidcIdToken}
* signature verification
* @since 5.2
*/
public final void setJwtDecoderFactory(JwtDecoderFactory<ClientRegistration> jwtDecoderFactory) {
Assert.notNull(jwtDecoderFactory, "jwtDecoderFactory cannot be null");
this.jwtDecoderFactory = jwtDecoderFactory;
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OidcUser#getAuthorities()}} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication);
}
private OidcIdToken createOidcToken(ClientRegistration clientRegistration,
OAuth2AccessTokenResponse accessTokenResponse) {
JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration);
Jwt jwt = getJwt(accessTokenResponse, jwtDecoder);
OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(),
jwt.getClaims());
return idToken;
}
private Jwt getJwt(OAuth2AccessTokenResponse accessTokenResponse, JwtDecoder jwtDecoder) {
try {
Map<String, Object> parameters = accessTokenResponse.getAdditionalParameters();
return jwtDecoder.decode((String) parameters.get(OidcParameterNames.ID_TOKEN));
}
catch (JwtException ex) {
OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(), null);
throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex);
}
}
static String createHash(String nonce) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}
| 12,626 | 47.565385 | 115 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/DefaultOidcIdTokenValidatorFactory.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
import java.util.function.Function;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
/**
* @author Joe Grandja
* @since 5.2
*/
class DefaultOidcIdTokenValidatorFactory implements Function<ClientRegistration, OAuth2TokenValidator<Jwt>> {
@Override
public OAuth2TokenValidator<Jwt> apply(ClientRegistration clientRegistration) {
return new DelegatingOAuth2TokenValidator<>(new JwtTimestampValidator(),
new OidcIdTokenValidator(clientRegistration));
}
}
| 1,469 | 35.75 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/OidcIdTokenDecoderFactory.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
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.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtDecoderFactory;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A {@link JwtDecoderFactory factory} that provides a {@link JwtDecoder} used for
* {@link OidcIdToken} signature verification. The provided {@link JwtDecoder} is
* associated to a specific {@link ClientRegistration}.
*
* @author Joe Grandja
* @author Rafael Dominguez
* @author Mark Heckler
* @since 5.2
* @see JwtDecoderFactory
* @see ClientRegistration
* @see OidcIdToken
*/
public final class OidcIdTokenDecoderFactory implements JwtDecoderFactory<ClientRegistration> {
private static final String MISSING_SIGNATURE_VERIFIER_ERROR_CODE = "missing_signature_verifier";
private static final Map<JwsAlgorithm, String> JCA_ALGORITHM_MAPPINGS;
static {
Map<JwsAlgorithm, String> mappings = new HashMap<>();
mappings.put(MacAlgorithm.HS256, "HmacSHA256");
mappings.put(MacAlgorithm.HS384, "HmacSHA384");
mappings.put(MacAlgorithm.HS512, "HmacSHA512");
JCA_ALGORITHM_MAPPINGS = Collections.unmodifiableMap(mappings);
};
private static final ClaimTypeConverter DEFAULT_CLAIM_TYPE_CONVERTER = new ClaimTypeConverter(
createDefaultClaimTypeConverters());
private final Map<String, JwtDecoder> jwtDecoders = new ConcurrentHashMap<>();
private Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = new DefaultOidcIdTokenValidatorFactory();
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = (
clientRegistration) -> SignatureAlgorithm.RS256;
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
/**
* Returns the default {@link Converter}'s used for type conversion of claim values
* for an {@link OidcIdToken}.
* @return a {@link Map} of {@link Converter}'s keyed by {@link IdTokenClaimNames
* claim name}
*/
public static Map<String, Converter<Object, ?>> createDefaultClaimTypeConverters() {
Converter<Object, ?> booleanConverter = getConverter(TypeDescriptor.valueOf(Boolean.class));
Converter<Object, ?> instantConverter = getConverter(TypeDescriptor.valueOf(Instant.class));
Converter<Object, ?> urlConverter = getConverter(TypeDescriptor.valueOf(URL.class));
Converter<Object, ?> stringConverter = getConverter(TypeDescriptor.valueOf(String.class));
Converter<Object, ?> collectionStringConverter = getConverter(
TypeDescriptor.collection(Collection.class, TypeDescriptor.valueOf(String.class)));
Map<String, Converter<Object, ?>> converters = new HashMap<>();
converters.put(IdTokenClaimNames.ISS, urlConverter);
converters.put(IdTokenClaimNames.AUD, collectionStringConverter);
converters.put(IdTokenClaimNames.NONCE, stringConverter);
converters.put(IdTokenClaimNames.EXP, instantConverter);
converters.put(IdTokenClaimNames.IAT, instantConverter);
converters.put(IdTokenClaimNames.AUTH_TIME, instantConverter);
converters.put(IdTokenClaimNames.AMR, collectionStringConverter);
converters.put(StandardClaimNames.EMAIL_VERIFIED, booleanConverter);
converters.put(StandardClaimNames.PHONE_NUMBER_VERIFIED, booleanConverter);
converters.put(StandardClaimNames.UPDATED_AT, instantConverter);
return converters;
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
targetDescriptor);
}
@Override
public JwtDecoder createDecoder(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), (key) -> {
NimbusJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
.apply(clientRegistration);
if (claimTypeConverter != null) {
jwtDecoder.setClaimSetConverter(claimTypeConverter);
}
return jwtDecoder;
});
}
private NimbusJwtDecoder buildDecoder(ClientRegistration clientRegistration) {
JwsAlgorithm jwsAlgorithm = this.jwsAlgorithmResolver.apply(clientRegistration);
if (jwsAlgorithm != null && SignatureAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
//
// 6. If the ID Token is received via direct communication between the Client
// and the Token Endpoint (which it is in this flow),
// the TLS server validation MAY be used to validate the issuer in place of
// checking the token signature.
// The Client MUST validate the signature of all other ID Tokens according to
// JWS [JWS]
// using the algorithm specified in the JWT alg Header Parameter.
// The Client MUST use the keys provided by the Issuer.
//
// 7. The alg value SHOULD be the default of RS256 or the algorithm sent by
// the Client
// in the id_token_signed_response_alg parameter during Registration.
String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
if (!StringUtils.hasText(jwkSetUri)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured the JwkSet URI.",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm).build();
}
if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
//
// 8. If the JWT alg Header Parameter uses a MAC based algorithm such as
// HS256, HS384, or HS512,
// the octets of the UTF-8 representation of the client_secret
// corresponding to the client_id contained in the aud (audience) Claim
// are used as the key to validate the signature.
// For MAC based algorithms, the behavior is unspecified if the aud is
// multi-valued or
// if an azp value is present that is different than the aud value.
String clientSecret = clientRegistration.getClientSecret();
if (!StringUtils.hasText(clientSecret)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured the client secret.",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8),
JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
return NimbusJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm).build();
}
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
/**
* Sets the factory that provides an {@link OAuth2TokenValidator}, which is used by
* the {@link JwtDecoder}. The default composes {@link JwtTimestampValidator} and
* {@link OidcIdTokenValidator}.
* @param jwtValidatorFactory the factory that provides an
* {@link OAuth2TokenValidator}
*/
public void setJwtValidatorFactory(Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory) {
Assert.notNull(jwtValidatorFactory, "jwtValidatorFactory cannot be null");
this.jwtValidatorFactory = jwtValidatorFactory;
}
/**
* Sets the resolver that provides the expected {@link JwsAlgorithm JWS algorithm}
* used for the signature or MAC on the {@link OidcIdToken ID Token}. The default
* resolves to {@link SignatureAlgorithm#RS256 RS256} for all
* {@link ClientRegistration clients}.
* @param jwsAlgorithmResolver the resolver that provides the expected
* {@link JwsAlgorithm JWS algorithm} for a specific {@link ClientRegistration client}
*/
public void setJwsAlgorithmResolver(Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver) {
Assert.notNull(jwsAlgorithmResolver, "jwsAlgorithmResolver cannot be null");
this.jwsAlgorithmResolver = jwsAlgorithmResolver;
}
/**
* Sets the factory that provides a {@link Converter} used for type conversion of
* claim values for an {@link OidcIdToken}. The default is {@link ClaimTypeConverter}
* for all {@link ClientRegistration clients}.
* @param claimTypeConverterFactory the factory that provides a {@link Converter} used
* for type conversion of claim values for a specific {@link ClientRegistration
* client}
*/
public void setClaimTypeConverterFactory(
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) {
Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null");
this.claimTypeConverterFactory = claimTypeConverterFactory;
}
}
| 11,876 | 48.282158 | 128 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/oidc/authentication/ReactiveOidcIdTokenDecoderFactory.java | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.oidc.authentication;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2TokenValidator;
import org.springframework.security.oauth2.core.converter.ClaimConversionService;
import org.springframework.security.oauth2.core.converter.ClaimTypeConverter;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.StandardClaimNames;
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.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder;
import org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A {@link ReactiveJwtDecoderFactory factory} that provides a {@link ReactiveJwtDecoder}
* used for {@link OidcIdToken} signature verification. The provided
* {@link ReactiveJwtDecoder} is associated to a specific {@link ClientRegistration}.
*
* @author Joe Grandja
* @author Rafael Dominguez
* @author Mark Heckler
* @since 5.2
* @see ReactiveJwtDecoderFactory
* @see ClientRegistration
* @see OidcIdToken
*/
public final class ReactiveOidcIdTokenDecoderFactory implements ReactiveJwtDecoderFactory<ClientRegistration> {
private static final String MISSING_SIGNATURE_VERIFIER_ERROR_CODE = "missing_signature_verifier";
private static final Map<JwsAlgorithm, String> JCA_ALGORITHM_MAPPINGS;
static {
Map<JwsAlgorithm, String> mappings = new HashMap<JwsAlgorithm, String>();
mappings.put(MacAlgorithm.HS256, "HmacSHA256");
mappings.put(MacAlgorithm.HS384, "HmacSHA384");
mappings.put(MacAlgorithm.HS512, "HmacSHA512");
JCA_ALGORITHM_MAPPINGS = Collections.unmodifiableMap(mappings);
}
private static final ClaimTypeConverter DEFAULT_CLAIM_TYPE_CONVERTER = new ClaimTypeConverter(
createDefaultClaimTypeConverters());
private final Map<String, ReactiveJwtDecoder> jwtDecoders = new ConcurrentHashMap<>();
private Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory = new DefaultOidcIdTokenValidatorFactory();
private Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver = (
clientRegistration) -> SignatureAlgorithm.RS256;
private Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory = (
clientRegistration) -> DEFAULT_CLAIM_TYPE_CONVERTER;
/**
* Returns the default {@link Converter}'s used for type conversion of claim values
* for an {@link OidcIdToken}.
* @return a {@link Map} of {@link Converter}'s keyed by {@link IdTokenClaimNames
* claim name}
*/
public static Map<String, Converter<Object, ?>> createDefaultClaimTypeConverters() {
Converter<Object, ?> booleanConverter = getConverter(TypeDescriptor.valueOf(Boolean.class));
Converter<Object, ?> instantConverter = getConverter(TypeDescriptor.valueOf(Instant.class));
Converter<Object, ?> urlConverter = getConverter(TypeDescriptor.valueOf(URL.class));
Converter<Object, ?> stringConverter = getConverter(TypeDescriptor.valueOf(String.class));
Converter<Object, ?> collectionStringConverter = getConverter(
TypeDescriptor.collection(Collection.class, TypeDescriptor.valueOf(String.class)));
Map<String, Converter<Object, ?>> converters = new HashMap<>();
converters.put(IdTokenClaimNames.ISS, urlConverter);
converters.put(IdTokenClaimNames.AUD, collectionStringConverter);
converters.put(IdTokenClaimNames.NONCE, stringConverter);
converters.put(IdTokenClaimNames.EXP, instantConverter);
converters.put(IdTokenClaimNames.IAT, instantConverter);
converters.put(IdTokenClaimNames.AUTH_TIME, instantConverter);
converters.put(IdTokenClaimNames.AMR, collectionStringConverter);
converters.put(StandardClaimNames.EMAIL_VERIFIED, booleanConverter);
converters.put(StandardClaimNames.PHONE_NUMBER_VERIFIED, booleanConverter);
converters.put(StandardClaimNames.UPDATED_AT, instantConverter);
return converters;
}
private static Converter<Object, ?> getConverter(TypeDescriptor targetDescriptor) {
final TypeDescriptor sourceDescriptor = TypeDescriptor.valueOf(Object.class);
return (source) -> ClaimConversionService.getSharedInstance().convert(source, sourceDescriptor,
targetDescriptor);
}
@Override
public ReactiveJwtDecoder createDecoder(ClientRegistration clientRegistration) {
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
return this.jwtDecoders.computeIfAbsent(clientRegistration.getRegistrationId(), (key) -> {
NimbusReactiveJwtDecoder jwtDecoder = buildDecoder(clientRegistration);
jwtDecoder.setJwtValidator(this.jwtValidatorFactory.apply(clientRegistration));
Converter<Map<String, Object>, Map<String, Object>> claimTypeConverter = this.claimTypeConverterFactory
.apply(clientRegistration);
if (claimTypeConverter != null) {
jwtDecoder.setClaimSetConverter(claimTypeConverter);
}
return jwtDecoder;
});
}
private NimbusReactiveJwtDecoder buildDecoder(ClientRegistration clientRegistration) {
JwsAlgorithm jwsAlgorithm = this.jwsAlgorithmResolver.apply(clientRegistration);
if (jwsAlgorithm != null && SignatureAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
//
// 6. If the ID Token is received via direct communication between the Client
// and the Token Endpoint (which it is in this flow),
// the TLS server validation MAY be used to validate the issuer in place of
// checking the token signature.
// The Client MUST validate the signature of all other ID Tokens according to
// JWS [JWS]
// using the algorithm specified in the JWT alg Header Parameter.
// The Client MUST use the keys provided by the Issuer.
//
// 7. The alg value SHOULD be the default of RS256 or the algorithm sent by
// the Client
// in the id_token_signed_response_alg parameter during Registration.
String jwkSetUri = clientRegistration.getProviderDetails().getJwkSetUri();
if (!StringUtils.hasText(jwkSetUri)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured the JwkSet URI.",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).jwsAlgorithm((SignatureAlgorithm) jwsAlgorithm)
.build();
}
if (jwsAlgorithm != null && MacAlgorithm.class.isAssignableFrom(jwsAlgorithm.getClass())) {
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
//
// 8. If the JWT alg Header Parameter uses a MAC based algorithm such as
// HS256, HS384, or HS512,
// the octets of the UTF-8 representation of the client_secret
// corresponding to the client_id contained in the aud (audience) Claim
// are used as the key to validate the signature.
// For MAC based algorithms, the behavior is unspecified if the aud is
// multi-valued or
// if an azp value is present that is different than the aud value.
String clientSecret = clientRegistration.getClientSecret();
if (!StringUtils.hasText(clientSecret)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured the client secret.",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
SecretKeySpec secretKeySpec = new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8),
JCA_ALGORITHM_MAPPINGS.get(jwsAlgorithm));
return NimbusReactiveJwtDecoder.withSecretKey(secretKeySpec).macAlgorithm((MacAlgorithm) jwsAlgorithm)
.build();
}
OAuth2Error oauth2Error = new OAuth2Error(MISSING_SIGNATURE_VERIFIER_ERROR_CODE,
"Failed to find a Signature Verifier for Client Registration: '"
+ clientRegistration.getRegistrationId()
+ "'. Check to ensure you have configured a valid JWS Algorithm: '" + jwsAlgorithm + "'",
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
/**
* Sets the factory that provides an {@link OAuth2TokenValidator}, which is used by
* the {@link ReactiveJwtDecoder}. The default composes {@link JwtTimestampValidator}
* and {@link OidcIdTokenValidator}.
* @param jwtValidatorFactory the factory that provides an
* {@link OAuth2TokenValidator}
*/
public void setJwtValidatorFactory(Function<ClientRegistration, OAuth2TokenValidator<Jwt>> jwtValidatorFactory) {
Assert.notNull(jwtValidatorFactory, "jwtValidatorFactory cannot be null");
this.jwtValidatorFactory = jwtValidatorFactory;
}
/**
* Sets the resolver that provides the expected {@link JwsAlgorithm JWS algorithm}
* used for the signature or MAC on the {@link OidcIdToken ID Token}. The default
* resolves to {@link SignatureAlgorithm#RS256 RS256} for all
* {@link ClientRegistration clients}.
* @param jwsAlgorithmResolver the resolver that provides the expected
* {@link JwsAlgorithm JWS algorithm} for a specific {@link ClientRegistration client}
*/
public void setJwsAlgorithmResolver(Function<ClientRegistration, JwsAlgorithm> jwsAlgorithmResolver) {
Assert.notNull(jwsAlgorithmResolver, "jwsAlgorithmResolver cannot be null");
this.jwsAlgorithmResolver = jwsAlgorithmResolver;
}
/**
* Sets the factory that provides a {@link Converter} used for type conversion of
* claim values for an {@link OidcIdToken}. The default is {@link ClaimTypeConverter}
* for all {@link ClientRegistration clients}.
* @param claimTypeConverterFactory the factory that provides a {@link Converter} used
* for type conversion of claim values for a specific {@link ClientRegistration
* client}
*/
public void setClaimTypeConverterFactory(
Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> claimTypeConverterFactory) {
Assert.notNull(claimTypeConverterFactory, "claimTypeConverterFactory cannot be null");
this.claimTypeConverterFactory = claimTypeConverterFactory;
}
}
| 12,041 | 48.555556 | 128 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthenticationToken.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.client.authentication;
import java.util.Collection;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AbstractAuthenticationToken} that represents an OAuth
* 2.0 {@link Authentication}.
* <p>
* The {@link Authentication} associates an {@link OAuth2User} {@code Principal} to the
* identifier of the {@link #getAuthorizedClientRegistrationId() Authorized Client}, which
* the End-User ({@code Principal}) granted authorization to so that it can access it's
* protected resources at the UserInfo Endpoint.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractAuthenticationToken
* @see OAuth2User
* @see OAuth2AuthorizedClient
*/
public class OAuth2AuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final OAuth2User principal;
private final String authorizedClientRegistrationId;
/**
* Constructs an {@code OAuth2AuthenticationToken} using the provided parameters.
* @param principal the user {@code Principal} registered with the OAuth 2.0 Provider
* @param authorities the authorities granted to the user
* @param authorizedClientRegistrationId the registration identifier of the
* {@link OAuth2AuthorizedClient Authorized Client}
*/
public OAuth2AuthenticationToken(OAuth2User principal, Collection<? extends GrantedAuthority> authorities,
String authorizedClientRegistrationId) {
super(authorities);
Assert.notNull(principal, "principal cannot be null");
Assert.hasText(authorizedClientRegistrationId, "authorizedClientRegistrationId cannot be empty");
this.principal = principal;
this.authorizedClientRegistrationId = authorizedClientRegistrationId;
this.setAuthenticated(true);
}
@Override
public OAuth2User getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
// Credentials are never exposed (by the Provider) for an OAuth2 User
return "";
}
/**
* Returns the registration identifier of the {@link OAuth2AuthorizedClient Authorized
* Client}.
* @return the registration identifier of the Authorized Client.
*/
public String getAuthorizedClientRegistrationId() {
return this.authorizedClientRegistrationId;
}
}
| 3,334 | 36.055556 | 107 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationProvider.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.authentication;
import java.util.Collection;
import java.util.Map;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AuthenticationProvider} for OAuth 2.0 Login, which
* leverages the OAuth 2.0 Authorization Code Grant Flow.
*
* This {@link AuthenticationProvider} is responsible for authenticating an Authorization
* Code credential with the Authorization Server's Token Endpoint and if valid, exchanging
* it for an Access Token credential.
* <p>
* It will also obtain the user attributes of the End-User (Resource Owner) from the
* UserInfo Endpoint using an {@link OAuth2UserService}, which will create a
* {@code Principal} in the form of an {@link OAuth2User}. The {@code OAuth2User} is then
* associated to the {@link OAuth2LoginAuthenticationToken} to complete the
* authentication.
*
* @author Joe Grandja
* @since 5.0
* @see OAuth2LoginAuthenticationToken
* @see OAuth2AccessTokenResponseClient
* @see OAuth2UserService
* @see OAuth2User
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token
* Request</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token
* Response</a>
*/
public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider {
private final OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider;
private final OAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
/**
* Constructs an {@code OAuth2LoginAuthenticationProvider} using the provided
* parameters.
* @param accessTokenResponseClient the client used for requesting the access token
* credential from the Token Endpoint
* @param userService the service used for obtaining the user attributes of the
* End-User from the UserInfo Endpoint
*/
public OAuth2LoginAuthenticationProvider(
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient,
OAuth2UserService<OAuth2UserRequest, OAuth2User> userService) {
Assert.notNull(userService, "userService cannot be null");
this.authorizationCodeAuthenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider(
accessTokenResponseClient);
this.userService = userService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication;
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
if (loginAuthenticationToken.getAuthorizationExchange().getAuthorizationRequest().getScopes()
.contains("openid")) {
// This is an OpenID Connect Authentication Request so return null
// and let OidcAuthorizationCodeAuthenticationProvider handle it instead
return null;
}
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken;
try {
authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider
.authenticate(new OAuth2AuthorizationCodeAuthenticationToken(
loginAuthenticationToken.getClientRegistration(),
loginAuthenticationToken.getAuthorizationExchange()));
}
catch (OAuth2AuthorizationException ex) {
OAuth2Error oauth2Error = ex.getError();
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
}
OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken();
Map<String, Object> additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters();
OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest(
loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters));
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
.mapAuthorities(oauth2User.getAuthorities());
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(),
oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken());
authenticationResult.setDetails(loginAuthenticationToken.getDetails());
return authenticationResult;
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OAuth2User#getAuthorities()} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication);
}
}
| 7,141 | 47.917808 | 131 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/package-info.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Support classes and interfaces for authenticating and authorizing a client with an
* OAuth 2.0 Authorization Server using a specific authorization grant flow.
*/
package org.springframework.security.oauth2.client.authentication;
| 861 | 38.181818 | 85 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginAuthenticationToken.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.authentication;
import java.util.Collection;
import java.util.Collections;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An {@link AbstractAuthenticationToken} for OAuth 2.0 Login, which leverages the OAuth
* 2.0 Authorization Code Grant Flow.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractAuthenticationToken
* @see OAuth2User
* @see ClientRegistration
* @see OAuth2AuthorizationExchange
* @see OAuth2AccessToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
*/
public class OAuth2LoginAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private OAuth2User principal;
private ClientRegistration clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
/**
* This constructor should be used when the Authorization Request/Response is
* complete.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
*/
public OAuth2LoginAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange) {
super(Collections.emptyList());
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
Assert.notNull(authorizationExchange, "authorizationExchange cannot be null");
this.clientRegistration = clientRegistration;
this.authorizationExchange = authorizationExchange;
this.setAuthenticated(false);
}
/**
* This constructor should be used when the Access Token Request/Response is complete,
* which indicates that the Authorization Code Grant flow has fully completed and
* OAuth 2.0 Login has been achieved.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
* @param principal the user {@code Principal} registered with the OAuth 2.0 Provider
* @param authorities the authorities granted to the user
* @param accessToken the access token credential
*/
public OAuth2LoginAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange, OAuth2User principal,
Collection<? extends GrantedAuthority> authorities, OAuth2AccessToken accessToken) {
this(clientRegistration, authorizationExchange, principal, authorities, accessToken, null);
}
/**
* This constructor should be used when the Access Token Request/Response is complete,
* which indicates that the Authorization Code Grant flow has fully completed and
* OAuth 2.0 Login has been achieved.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
* @param principal the user {@code Principal} registered with the OAuth 2.0 Provider
* @param authorities the authorities granted to the user
* @param accessToken the access token credential
* @param refreshToken the refresh token credential
*/
public OAuth2LoginAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange, OAuth2User principal,
Collection<? extends GrantedAuthority> authorities, OAuth2AccessToken accessToken,
@Nullable OAuth2RefreshToken refreshToken) {
super(authorities);
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
Assert.notNull(authorizationExchange, "authorizationExchange cannot be null");
Assert.notNull(principal, "principal cannot be null");
Assert.notNull(accessToken, "accessToken cannot be null");
this.clientRegistration = clientRegistration;
this.authorizationExchange = authorizationExchange;
this.principal = principal;
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.setAuthenticated(true);
}
@Override
public OAuth2User getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return "";
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the {@link OAuth2AuthorizationExchange authorization exchange}.
* @return the {@link OAuth2AuthorizationExchange}
*/
public OAuth2AuthorizationExchange getAuthorizationExchange() {
return this.authorizationExchange;
}
/**
* Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token}.
* @return the {@link OAuth2RefreshToken}
* @since 5.1
*/
public @Nullable OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
}
| 6,208 | 36.630303 | 93 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationProvider.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.authentication;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.util.Assert;
/**
* An implementation of an {@link AuthenticationProvider} for the OAuth 2.0 Authorization
* Code Grant.
*
* <p>
* This {@link AuthenticationProvider} is responsible for authenticating an Authorization
* Code credential with the Authorization Server's Token Endpoint and if valid, exchanging
* it for an Access Token credential.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AuthorizationCodeAuthenticationToken
* @see OAuth2AccessTokenResponseClient
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token
* Request</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token
* Response</a>
*/
public class OAuth2AuthorizationCodeAuthenticationProvider implements AuthenticationProvider {
private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter";
private final OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
/**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationProvider} using the
* provided parameters.
* @param accessTokenResponseClient the client used for requesting the access token
* credential from the Token Endpoint
*/
public OAuth2AuthorizationCodeAuthenticationProvider(
OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationResponse();
if (authorizationResponse.statusError()) {
throw new OAuth2AuthorizationException(authorizationResponse.getError());
}
OAuth2AuthorizationRequest authorizationRequest = authorizationCodeAuthentication.getAuthorizationExchange()
.getAuthorizationRequest();
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
throw new OAuth2AuthorizationException(oauth2Error);
}
OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenResponseClient.getTokenResponse(
new OAuth2AuthorizationCodeGrantRequest(authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange()));
OAuth2AuthorizationCodeAuthenticationToken authenticationResult = new OAuth2AuthorizationCodeAuthenticationToken(
authorizationCodeAuthentication.getClientRegistration(),
authorizationCodeAuthentication.getAuthorizationExchange(), accessTokenResponse.getAccessToken(),
accessTokenResponse.getRefreshToken(), accessTokenResponse.getAdditionalParameters());
authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
return authenticationResult;
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2AuthorizationCodeAuthenticationToken.class.isAssignableFrom(authentication);
}
}
| 5,037 | 48.392157 | 139 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeAuthenticationToken.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.authentication;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.util.Assert;
/**
* An {@link AbstractAuthenticationToken} for the OAuth 2.0 Authorization Code Grant.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractAuthenticationToken
* @see ClientRegistration
* @see OAuth2AuthorizationExchange
* @see OAuth2AccessToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
*/
public class OAuth2AuthorizationCodeAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private Map<String, Object> additionalParameters = new HashMap<>();
private ClientRegistration clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
private OAuth2AccessToken accessToken;
private OAuth2RefreshToken refreshToken;
/**
* This constructor should be used when the Authorization Request/Response is
* complete.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
*/
public OAuth2AuthorizationCodeAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange) {
super(Collections.emptyList());
Assert.notNull(clientRegistration, "clientRegistration cannot be null");
Assert.notNull(authorizationExchange, "authorizationExchange cannot be null");
this.clientRegistration = clientRegistration;
this.authorizationExchange = authorizationExchange;
}
/**
* This constructor should be used when the Access Token Request/Response is complete,
* which indicates that the Authorization Code Grant flow has fully completed.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
* @param accessToken the access token credential
*/
public OAuth2AuthorizationCodeAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange, OAuth2AccessToken accessToken) {
this(clientRegistration, authorizationExchange, accessToken, null);
}
/**
* This constructor should be used when the Access Token Request/Response is complete,
* which indicates that the Authorization Code Grant flow has fully completed.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
* @param accessToken the access token credential
* @param refreshToken the refresh token credential
*/
public OAuth2AuthorizationCodeAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange, OAuth2AccessToken accessToken,
@Nullable OAuth2RefreshToken refreshToken) {
this(clientRegistration, authorizationExchange, accessToken, refreshToken, Collections.emptyMap());
}
public OAuth2AuthorizationCodeAuthenticationToken(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange, OAuth2AccessToken accessToken,
OAuth2RefreshToken refreshToken, Map<String, Object> additionalParameters) {
this(clientRegistration, authorizationExchange);
Assert.notNull(accessToken, "accessToken cannot be null");
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.setAuthenticated(true);
this.additionalParameters.putAll(additionalParameters);
}
@Override
public Object getPrincipal() {
return this.clientRegistration.getClientId();
}
@Override
public Object getCredentials() {
return (this.accessToken != null) ? this.accessToken.getTokenValue()
: this.authorizationExchange.getAuthorizationResponse().getCode();
}
/**
* Returns the {@link ClientRegistration client registration}.
* @return the {@link ClientRegistration}
*/
public ClientRegistration getClientRegistration() {
return this.clientRegistration;
}
/**
* Returns the {@link OAuth2AuthorizationExchange authorization exchange}.
* @return the {@link OAuth2AuthorizationExchange}
*/
public OAuth2AuthorizationExchange getAuthorizationExchange() {
return this.authorizationExchange;
}
/**
* Returns the {@link OAuth2AccessToken access token}.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token}.
* @return the {@link OAuth2RefreshToken}
*/
public @Nullable OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the additional parameters
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
}
| 5,961 | 35.802469 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2AuthorizationCodeReactiveAuthenticationManager.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.authentication;
import java.util.function.Function;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An implementation of an
* {@link org.springframework.security.authentication.AuthenticationProvider} for OAuth
* 2.0 Login, which leverages the OAuth 2.0 Authorization Code Grant Flow.
*
* This {@link org.springframework.security.authentication.AuthenticationProvider} is
* responsible for authenticating an Authorization Code credential with the Authorization
* Server's Token Endpoint and if valid, exchanging it for an Access Token credential.
* <p>
* It will also obtain the user attributes of the End-User (Resource Owner) from the
* UserInfo Endpoint using an
* {@link org.springframework.security.oauth2.client.userinfo.OAuth2UserService}, which
* will create a {@code Principal} in the form of an {@link OAuth2User}. The
* {@code OAuth2User} is then associated to the {@link OAuth2LoginAuthenticationToken} to
* complete the authentication.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2LoginAuthenticationToken
* @see ReactiveOAuth2AccessTokenResponseClient
* @see ReactiveOAuth2UserService
* @see OAuth2User
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token
* Request</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token
* Response</a>
*/
public class OAuth2AuthorizationCodeReactiveAuthenticationManager implements ReactiveAuthenticationManager {
private static final String INVALID_STATE_PARAMETER_ERROR_CODE = "invalid_state_parameter";
private final ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;
public OAuth2AuthorizationCodeReactiveAuthenticationManager(
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
this.accessTokenResponseClient = accessTokenResponseClient;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.defer(() -> {
OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
OAuth2AuthorizationResponse authorizationResponse = token.getAuthorizationExchange()
.getAuthorizationResponse();
if (authorizationResponse.statusError()) {
return Mono.error(new OAuth2AuthorizationException(authorizationResponse.getError()));
}
OAuth2AuthorizationRequest authorizationRequest = token.getAuthorizationExchange()
.getAuthorizationRequest();
if (!authorizationResponse.getState().equals(authorizationRequest.getState())) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_STATE_PARAMETER_ERROR_CODE);
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
OAuth2AuthorizationCodeGrantRequest authzRequest = new OAuth2AuthorizationCodeGrantRequest(
token.getClientRegistration(), token.getAuthorizationExchange());
return this.accessTokenResponseClient.getTokenResponse(authzRequest).map(onSuccess(token));
});
}
private Function<OAuth2AccessTokenResponse, OAuth2AuthorizationCodeAuthenticationToken> onSuccess(
OAuth2AuthorizationCodeAuthenticationToken token) {
return (accessTokenResponse) -> {
ClientRegistration registration = token.getClientRegistration();
OAuth2AuthorizationExchange exchange = token.getAuthorizationExchange();
OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
OAuth2RefreshToken refreshToken = accessTokenResponse.getRefreshToken();
return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange, accessToken, refreshToken,
accessTokenResponse.getAdditionalParameters());
};
}
}
| 5,864 | 49.128205 | 118 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/authentication/OAuth2LoginReactiveAuthenticationManager.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.authentication;
import java.util.Collection;
import java.util.Map;
import reactor.core.publisher.Mono;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.util.Assert;
/**
* An implementation of an
* {@link org.springframework.security.authentication.AuthenticationProvider} for OAuth
* 2.0 Login, which leverages the OAuth 2.0 Authorization Code Grant Flow.
*
* This {@link org.springframework.security.authentication.AuthenticationProvider} is
* responsible for authenticating an Authorization Code credential with the Authorization
* Server's Token Endpoint and if valid, exchanging it for an Access Token credential.
* <p>
* It will also obtain the user attributes of the End-User (Resource Owner) from the
* UserInfo Endpoint using an
* {@link org.springframework.security.oauth2.client.userinfo.OAuth2UserService}, which
* will create a {@code Principal} in the form of an {@link OAuth2User}. The
* {@code OAuth2User} is then associated to the {@link OAuth2LoginAuthenticationToken} to
* complete the authentication.
*
* @author Rob Winch
* @since 5.1
* @see OAuth2LoginAuthenticationToken
* @see org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient
* @see org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService
* @see OAuth2User
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.1">Section
* 4.1 Authorization Code Grant Flow</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.3">Section 4.1.3 Access Token
* Request</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.1.4">Section 4.1.4 Access Token
* Response</a>
*/
public class OAuth2LoginReactiveAuthenticationManager implements ReactiveAuthenticationManager {
private final ReactiveAuthenticationManager authorizationCodeManager;
private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> userService;
private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities);
public OAuth2LoginReactiveAuthenticationManager(
ReactiveOAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient,
ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> userService) {
Assert.notNull(accessTokenResponseClient, "accessTokenResponseClient cannot be null");
Assert.notNull(userService, "userService cannot be null");
this.authorizationCodeManager = new OAuth2AuthorizationCodeReactiveAuthenticationManager(
accessTokenResponseClient);
this.userService = userService;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.defer(() -> {
OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
if (token.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
// This is an OpenID Connect Authentication Request so return null
// and let OidcAuthorizationCodeReactiveAuthenticationManager handle it
// instead once one is created
return Mono.empty();
}
return this.authorizationCodeManager.authenticate(token)
.onErrorMap(OAuth2AuthorizationException.class,
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
.cast(OAuth2AuthorizationCodeAuthenticationToken.class).flatMap(this::onSuccess);
});
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OAuth2User#getAuthorities()} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
* @since 5.4
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
private Mono<OAuth2LoginAuthenticationToken> onSuccess(OAuth2AuthorizationCodeAuthenticationToken authentication) {
OAuth2AccessToken accessToken = authentication.getAccessToken();
Map<String, Object> additionalParameters = authentication.getAdditionalParameters();
OAuth2UserRequest userRequest = new OAuth2UserRequest(authentication.getClientRegistration(), accessToken,
additionalParameters);
return this.userService.loadUser(userRequest).map((oauth2User) -> {
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
.mapAuthorities(oauth2User.getAuthorities());
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
authentication.getClientRegistration(), authentication.getAuthorizationExchange(), oauth2User,
mappedAuthorities, accessToken, authentication.getRefreshToken());
return authenticationResult;
});
}
}
| 6,706 | 48.316176 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/JwtBearerGrantRequestEntityConverter.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 JwtBearerGrantRequest} to a {@link RequestEntity}
* representation of an OAuth 2.0 Access Token Request for the JWT Bearer Grant.
*
* @author Joe Grandja
* @since 5.5
* @see AbstractOAuth2AuthorizationGrantRequestEntityConverter
* @see JwtBearerGrantRequest
* @see RequestEntity
* @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 JwtBearerGrantRequestEntityConverter
extends AbstractOAuth2AuthorizationGrantRequestEntityConverter<JwtBearerGrantRequest> {
@Override
protected MultiValueMap<String, String> createParameters(JwtBearerGrantRequest jwtBearerGrantRequest) {
ClientRegistration clientRegistration = jwtBearerGrantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, jwtBearerGrantRequest.getGrantType().getValue());
parameters.add(OAuth2ParameterNames.ASSERTION, jwtBearerGrantRequest.getJwt().getTokenValue());
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,863 | 45.193548 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/DefaultRefreshTokenTokenResponseClient.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.util.Arrays;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#REFRESH_TOKEN refresh_token} grant. This implementation
* uses a {@link RestOperations} when requesting an access token credential at the
* Authorization Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AccessTokenResponseClient
* @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 DefaultRefreshTokenTokenResponseClient
implements OAuth2AccessTokenResponseClient<OAuth2RefreshTokenGrantRequest> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2RefreshTokenGrantRequestEntityConverter());
private RestOperations restOperations;
public DefaultRefreshTokenTokenResponseClient() {
RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest) {
Assert.notNull(refreshTokenGrantRequest, "refreshTokenGrantRequest cannot be null");
RequestEntity<?> request = this.requestEntityConverter.convert(refreshTokenGrantRequest);
ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
OAuth2AccessTokenResponse tokenResponse = response.getBody();
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())
|| tokenResponse.getRefreshToken() == null) {
OAuth2AccessTokenResponse.Builder tokenResponseBuilder = OAuth2AccessTokenResponse
.withResponse(tokenResponse);
if (CollectionUtils.isEmpty(tokenResponse.getAccessToken().getScopes())) {
// As per spec, in Section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then default to the scope
// originally requested by the client in the Token Request
tokenResponseBuilder.scopes(refreshTokenGrantRequest.getAccessToken().getScopes());
}
if (tokenResponse.getRefreshToken() == null) {
// Reuse existing refresh token
tokenResponseBuilder.refreshToken(refreshTokenGrantRequest.getRefreshToken().getTokenValue());
}
tokenResponse = tokenResponseBuilder.build();
}
return tokenResponse;
}
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
+ ex.getMessage(),
null);
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2RefreshTokenGrantRequest} to a {@link RequestEntity} representation of
* the OAuth 2.0 Access Token Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the Access Token Request
*/
public void setRequestEntityConverter(
Converter<OAuth2RefreshTokenGrantRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
* Response.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the Access
* Token Response
*/
public void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 6,450 | 44.111888 | 159 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/WebClientReactiveClientCredentialsTokenResponseClient.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.Set;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
/**
* An implementation of a {@link ReactiveOAuth2AccessTokenResponseClient} that
* "exchanges" a client credential for an access token credential at the
* Authorization Server's Token Endpoint.
*
* @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>
*/
public class WebClientReactiveClientCredentialsTokenResponseClient
extends AbstractWebClientReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> {
@Override
ClientRegistration clientRegistration(OAuth2ClientCredentialsGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
@Override
Set<String> scopes(OAuth2ClientCredentialsGrantRequest grantRequest) {
return grantRequest.getClientRegistration().getScopes();
}
}
| 2,172 | 36.465517 | 105 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/package-info.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Classes and interfaces providing support to the client for initiating requests to the
* Authorization Server's Protocol Endpoints.
*/
package org.springframework.security.oauth2.client.endpoint;
| 827 | 36.636364 | 88 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/NimbusJwtClientAuthenticationParametersConverter.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.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyType;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
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.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* A {@link Converter} that customizes the OAuth 2.0 Access Token Request parameters by
* adding a signed JSON Web Token (JWS) to be used for client authentication at the
* Authorization Server's Token Endpoint. The private/secret key used for signing the JWS
* is supplied by the {@code com.nimbusds.jose.jwk.JWK} resolver provided via the
* constructor.
*
* <p>
* <b>NOTE:</b> This implementation uses the Nimbus JOSE + JWT SDK.
*
* @param <T> the type of {@link AbstractOAuth2AuthorizationGrantRequest}
* @author Joe Grandja
* @author Steve Riesenberg
* @since 5.5
* @see Converter
* @see com.nimbusds.jose.jwk.JWK
* @see OAuth2AuthorizationCodeGrantRequestEntityConverter#addParametersConverter(Converter)
* @see OAuth2ClientCredentialsGrantRequestEntityConverter#addParametersConverter(Converter)
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7523#section-2.2">2.2
* Using JWTs for Client Authentication</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc7521#section-4.2">4.2
* Using Assertions for Client Authentication</a>
* @see <a target="_blank" href="https://connect2id.com/products/nimbus-jose-jwt">Nimbus
* JOSE + JWT SDK</a>
*/
public final class NimbusJwtClientAuthenticationParametersConverter<T extends AbstractOAuth2AuthorizationGrantRequest>
implements Converter<T, MultiValueMap<String, String>> {
private static final String INVALID_KEY_ERROR_CODE = "invalid_key";
private static final String INVALID_ALGORITHM_ERROR_CODE = "invalid_algorithm";
private static final String CLIENT_ASSERTION_TYPE_VALUE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
private final Function<ClientRegistration, JWK> jwkResolver;
private final Map<String, JwsEncoderHolder> jwsEncoders = new ConcurrentHashMap<>();
private Consumer<JwtClientAuthenticationContext<T>> jwtClientAssertionCustomizer = (context) -> {
};
/**
* Constructs a {@code NimbusJwtClientAuthenticationParametersConverter} using the
* provided parameters.
* @param jwkResolver the resolver that provides the {@code com.nimbusds.jose.jwk.JWK}
* associated to the {@link ClientRegistration client}
*/
public NimbusJwtClientAuthenticationParametersConverter(Function<ClientRegistration, JWK> jwkResolver) {
Assert.notNull(jwkResolver, "jwkResolver cannot be null");
this.jwkResolver = jwkResolver;
}
@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod())
&& !ClientAuthenticationMethod.CLIENT_SECRET_JWT
.equals(clientRegistration.getClientAuthenticationMethod())) {
return null;
}
JWK jwk = this.jwkResolver.apply(clientRegistration);
if (jwk == null) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE,
"Failed to resolve JWK signing key for client registration '"
+ clientRegistration.getRegistrationId() + "'.",
null);
throw new OAuth2AuthorizationException(oauth2Error);
}
JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
if (jwsAlgorithm == null) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE,
"Unable to resolve JWS (signing) algorithm from JWK associated to client registration '"
+ clientRegistration.getRegistrationId() + "'.",
null);
throw new OAuth2AuthorizationException(oauth2Error);
}
JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
// @formatter:off
JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder()
.issuer(clientRegistration.getClientId())
.subject(clientRegistration.getClientId())
.audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri()))
.id(UUID.randomUUID().toString())
.issuedAt(issuedAt)
.expiresAt(expiresAt);
// @formatter:on
JwtClientAuthenticationContext<T> jwtClientAssertionContext = new JwtClientAuthenticationContext<>(
authorizationGrantRequest, headersBuilder, claimsBuilder);
this.jwtClientAssertionCustomizer.accept(jwtClientAssertionContext);
JwsHeader jwsHeader = headersBuilder.build();
JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(),
(clientRegistrationId, currentJwsEncoderHolder) -> {
if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
return currentJwsEncoderHolder;
}
JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
});
JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
return parameters;
}
private static JwsAlgorithm resolveAlgorithm(JWK jwk) {
JwsAlgorithm jwsAlgorithm = null;
if (jwk.getAlgorithm() != null) {
jwsAlgorithm = SignatureAlgorithm.from(jwk.getAlgorithm().getName());
if (jwsAlgorithm == null) {
jwsAlgorithm = MacAlgorithm.from(jwk.getAlgorithm().getName());
}
}
if (jwsAlgorithm == null) {
if (KeyType.RSA.equals(jwk.getKeyType())) {
jwsAlgorithm = SignatureAlgorithm.RS256;
}
else if (KeyType.EC.equals(jwk.getKeyType())) {
jwsAlgorithm = SignatureAlgorithm.ES256;
}
else if (KeyType.OCT.equals(jwk.getKeyType())) {
jwsAlgorithm = MacAlgorithm.HS256;
}
}
return jwsAlgorithm;
}
/**
* Sets the {@link Consumer} to be provided the
* {@link JwtClientAuthenticationContext}, which contains the
* {@link JwsHeader.Builder} and {@link JwtClaimsSet.Builder} for further
* customization.
* @param jwtClientAssertionCustomizer the {@link Consumer} to be provided the
* {@link JwtClientAuthenticationContext}
* @since 5.7
*/
public void setJwtClientAssertionCustomizer(
Consumer<JwtClientAuthenticationContext<T>> jwtClientAssertionCustomizer) {
Assert.notNull(jwtClientAssertionCustomizer, "jwtClientAssertionCustomizer cannot be null");
this.jwtClientAssertionCustomizer = jwtClientAssertionCustomizer;
}
private static final class JwsEncoderHolder {
private final JwtEncoder jwsEncoder;
private final JWK jwk;
private JwsEncoderHolder(JwtEncoder jwsEncoder, JWK jwk) {
this.jwsEncoder = jwsEncoder;
this.jwk = jwk;
}
private JwtEncoder getJwsEncoder() {
return this.jwsEncoder;
}
private JWK getJwk() {
return this.jwk;
}
}
/**
* A context that holds client authentication-specific state and is used by
* {@link NimbusJwtClientAuthenticationParametersConverter} when attempting to
* customize the JSON Web Token (JWS) client assertion.
*
* @param <T> the type of {@link AbstractOAuth2AuthorizationGrantRequest}
* @since 5.7
*/
public static final class JwtClientAuthenticationContext<T extends AbstractOAuth2AuthorizationGrantRequest> {
private final T authorizationGrantRequest;
private final JwsHeader.Builder headers;
private final JwtClaimsSet.Builder claims;
private JwtClientAuthenticationContext(T authorizationGrantRequest, JwsHeader.Builder headers,
JwtClaimsSet.Builder claims) {
this.authorizationGrantRequest = authorizationGrantRequest;
this.headers = headers;
this.claims = claims;
}
/**
* Returns the {@link AbstractOAuth2AuthorizationGrantRequest authorization grant
* request}.
* @return the {@link AbstractOAuth2AuthorizationGrantRequest authorization grant
* request}
*/
public T getAuthorizationGrantRequest() {
return this.authorizationGrantRequest;
}
/**
* Returns the {@link JwsHeader.Builder} to be used to customize headers of the
* JSON Web Token (JWS).
* @return the {@link JwsHeader.Builder} to be used to customize headers of the
* JSON Web Token (JWS)
*/
public JwsHeader.Builder getHeaders() {
return this.headers;
}
/**
* Returns the {@link JwtClaimsSet.Builder} to be used to customize claims of the
* JSON Web Token (JWS).
* @return the {@link JwtClaimsSet.Builder} to be used to customize claims of the
* JSON Web Token (JWS)
*/
public JwtClaimsSet.Builder getClaims() {
return this.claims;
}
}
}
| 11,117 | 36.945392 | 118 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequest.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.Collections;
import java.util.LinkedHashSet;
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.OAuth2RefreshToken;
import org.springframework.util.Assert;
/**
* An OAuth 2.0 Refresh Token Grant request that holds the {@link OAuth2RefreshToken
* refresh token} credential granted to the {@link #getClientRegistration() client}.
*
* @author Joe Grandja
* @since 5.2
* @see AbstractOAuth2AuthorizationGrantRequest
* @see OAuth2RefreshToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-6">Section 6
* Refreshing an Access Token</a>
*/
public class OAuth2RefreshTokenGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final OAuth2AccessToken accessToken;
private final OAuth2RefreshToken refreshToken;
private final Set<String> scopes;
/**
* Constructs an {@code OAuth2RefreshTokenGrantRequest} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param accessToken the access token credential granted
* @param refreshToken the refresh token credential granted
*/
public OAuth2RefreshTokenGrantRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken,
OAuth2RefreshToken refreshToken) {
this(clientRegistration, accessToken, refreshToken, Collections.emptySet());
}
/**
* Constructs an {@code OAuth2RefreshTokenGrantRequest} using the provided parameters.
* @param clientRegistration the authorized client's registration
* @param accessToken the access token credential granted
* @param refreshToken the refresh token credential granted
* @param scopes the scopes to request
*/
public OAuth2RefreshTokenGrantRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken,
OAuth2RefreshToken refreshToken, Set<String> scopes) {
super(AuthorizationGrantType.REFRESH_TOKEN, clientRegistration);
Assert.notNull(accessToken, "accessToken cannot be null");
Assert.notNull(refreshToken, "refreshToken cannot be null");
this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.scopes = Collections
.unmodifiableSet((scopes != null) ? new LinkedHashSet<>(scopes) : Collections.emptySet());
}
/**
* Returns the {@link OAuth2AccessToken access token} credential granted.
* @return the {@link OAuth2AccessToken}
*/
public OAuth2AccessToken getAccessToken() {
return this.accessToken;
}
/**
* Returns the {@link OAuth2RefreshToken refresh token} credential granted.
* @return the {@link OAuth2RefreshToken}
*/
public OAuth2RefreshToken getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the scope(s) to request.
* @return the scope(s) to request
*/
public Set<String> getScopes() {
return this.scopes;
}
}
| 3,697 | 35.254902 | 108 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2PasswordGrantRequest.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;
/**
* An OAuth 2.0 Resource Owner Password Credentials Grant request that holds the resource
* owner's credentials.
*
* @author Joe Grandja
* @since 5.2
* @see AbstractOAuth2AuthorizationGrantRequest
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-1.3.3">Section 1.3.3 Resource Owner
* Password Credentials</a>
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use of
* the Resource Owner Password Credentials grant. See reference <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public class OAuth2PasswordGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final String username;
private final String password;
/**
* Constructs an {@code OAuth2PasswordGrantRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param username the resource owner's username
* @param password the resource owner's password
*/
public OAuth2PasswordGrantRequest(ClientRegistration clientRegistration, String username, String password) {
super(AuthorizationGrantType.PASSWORD, clientRegistration);
Assert.isTrue(AuthorizationGrantType.PASSWORD.equals(clientRegistration.getAuthorizationGrantType()),
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.PASSWORD");
Assert.hasText(username, "username cannot be empty");
Assert.hasText(password, "password cannot be empty");
this.username = username;
this.password = password;
}
/**
* Returns the resource owner's username.
* @return the resource owner's username
*/
public String getUsername() {
return this.username;
}
/**
* Returns the resource owner's password.
* @return the resource owner's password
*/
public String getPassword() {
return this.password;
}
}
| 2,818 | 35.141026 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/DefaultClientCredentialsTokenResponseClient.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.util.Arrays;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#CLIENT_CREDENTIALS client_credentials} grant. This
* implementation uses a {@link RestOperations} when requesting an access token credential
* at the Authorization Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AccessTokenResponseClient
* @see OAuth2ClientCredentialsGrantRequest
* @see OAuth2AccessTokenResponse
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.4.2">Section 4.4.2 Access Token Request
* (Client Credentials Grant)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.4.3">Section 4.4.3 Access Token Response
* (Client Credentials Grant)</a>
*/
public final class DefaultClientCredentialsTokenResponseClient
implements OAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2ClientCredentialsGrantRequestEntityConverter());
private RestOperations restOperations;
public DefaultClientCredentialsTokenResponseClient() {
RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2AccessTokenResponse getTokenResponse(
OAuth2ClientCredentialsGrantRequest clientCredentialsGrantRequest) {
Assert.notNull(clientCredentialsGrantRequest, "clientCredentialsGrantRequest cannot be null");
RequestEntity<?> request = this.requestEntityConverter.convert(clientCredentialsGrantRequest);
ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
// As per spec, in Section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then we assume all requested scopes were
// granted.
// However, we use the explicit scopes returned in the response (if any).
return response.getBody();
}
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
+ ex.getMessage(),
null);
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2ClientCredentialsGrantRequest} to a {@link RequestEntity}
* representation of the OAuth 2.0 Access Token Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the Access Token Request
*/
public void setRequestEntityConverter(
Converter<OAuth2ClientCredentialsGrantRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
* Response.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the Access
* Token Response
*/
public void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 5,989 | 43.701493 | 164 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/DefaultAuthorizationCodeTokenResponseClient.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.util.Arrays;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#AUTHORIZATION_CODE authorization_code} grant. This
* implementation uses a {@link RestOperations} when requesting an access token credential
* at the Authorization Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.1
* @see OAuth2AccessTokenResponseClient
* @see OAuth2AuthorizationCodeGrantRequest
* @see OAuth2AccessTokenResponse
* @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>
*/
public final class DefaultAuthorizationCodeTokenResponseClient
implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new OAuth2AuthorizationCodeGrantRequestEntityConverter());
private RestOperations restOperations;
public DefaultAuthorizationCodeTokenResponseClient() {
RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2AccessTokenResponse getTokenResponse(
OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest) {
Assert.notNull(authorizationCodeGrantRequest, "authorizationCodeGrantRequest cannot be null");
RequestEntity<?> request = this.requestEntityConverter.convert(authorizationCodeGrantRequest);
ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
// As per spec, in Section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then we assume all requested scopes were
// granted.
// However, we use the explicit scopes returned in the response (if any).
OAuth2AccessTokenResponse tokenResponse = response.getBody();
Assert.notNull(tokenResponse,
"The authorization server responded to this Authorization Code grant request with an empty body; as such, it cannot be materialized into an OAuth2AccessTokenResponse instance. Please check the HTTP response code in your server logs for more details.");
return tokenResponse;
}
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
+ ex.getMessage(),
null);
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2AuthorizationCodeGrantRequest} to a {@link RequestEntity}
* representation of the OAuth 2.0 Access Token Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the Access Token Request
*/
public void setRequestEntityConverter(
Converter<OAuth2AuthorizationCodeGrantRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
* Response.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the Access
* Token Response
*/
public void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 6,337 | 45.262774 | 256 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2ClientCredentialsGrantRequest.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.util.Assert;
/**
* An OAuth 2.0 Client Credentials Grant request that holds the client's credentials in
* {@link #getClientRegistration()}.
*
* @author Joe Grandja
* @since 5.1
* @see AbstractOAuth2AuthorizationGrantRequest
* @see ClientRegistration
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-1.3.4">Section 1.3.4 Client Credentials
* Grant</a>
*/
public class OAuth2ClientCredentialsGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
/**
* Constructs an {@code OAuth2ClientCredentialsGrantRequest} using the provided
* parameters.
* @param clientRegistration the client registration
*/
public OAuth2ClientCredentialsGrantRequest(ClientRegistration clientRegistration) {
super(AuthorizationGrantType.CLIENT_CREDENTIALS, clientRegistration);
Assert.isTrue(AuthorizationGrantType.CLIENT_CREDENTIALS.equals(clientRegistration.getAuthorizationGrantType()),
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.CLIENT_CREDENTIALS");
}
}
| 1,901 | 37.816327 | 113 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/DefaultPasswordTokenResponseClient.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.Arrays;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#PASSWORD password} grant. This implementation uses a
* {@link RestOperations} when requesting an access token credential at the Authorization
* Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.2
* @see OAuth2AccessTokenResponseClient
* @see OAuth2PasswordGrantRequest
* @see OAuth2AccessTokenResponse
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.3.2">Section 4.3.2 Access Token Request
* (Resource Owner Password Credentials Grant)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.3.3">Section 4.3.3 Access Token Response
* (Resource Owner Password Credentials Grant)</a>
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use of
* the Resource Owner Password Credentials grant. See reference <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public final class DefaultPasswordTokenResponseClient
implements OAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private Converter<OAuth2PasswordGrantRequest, RequestEntity<?>> requestEntityConverter = new OAuth2PasswordGrantRequestEntityConverter();
private RestOperations restOperations;
public DefaultPasswordTokenResponseClient() {
RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2AccessTokenResponse getTokenResponse(OAuth2PasswordGrantRequest passwordGrantRequest) {
Assert.notNull(passwordGrantRequest, "passwordGrantRequest cannot be null");
RequestEntity<?> request = this.requestEntityConverter.convert(passwordGrantRequest);
ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
// As per spec, in Section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then we assume all requested scopes were
// granted.
// However, we use the explicit scopes returned in the response (if any).
return response.getBody();
}
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
+ ex.getMessage(),
null);
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
/**
* Sets the {@link Converter} used for converting the
* {@link OAuth2PasswordGrantRequest} to a {@link RequestEntity} representation of the
* OAuth 2.0 Access Token Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the Access Token Request
*/
public void setRequestEntityConverter(
Converter<OAuth2PasswordGrantRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
* Response.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the Access
* Token Response
*/
public void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 6,141 | 43.832117 | 138 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2AuthorizationCodeGrantRequest.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.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.util.Assert;
/**
* An OAuth 2.0 Authorization Code Grant request that holds an Authorization Code
* credential, which was granted by the Resource Owner to the
* {@link #getClientRegistration() Client}.
*
* @author Joe Grandja
* @since 5.0
* @see AbstractOAuth2AuthorizationGrantRequest
* @see ClientRegistration
* @see OAuth2AuthorizationExchange
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-1.3.1">Section 1.3.1 Authorization Code
* Grant</a>
*/
public class OAuth2AuthorizationCodeGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final OAuth2AuthorizationExchange authorizationExchange;
/**
* Constructs an {@code OAuth2AuthorizationCodeGrantRequest} using the provided
* parameters.
* @param clientRegistration the client registration
* @param authorizationExchange the authorization exchange
*/
public OAuth2AuthorizationCodeGrantRequest(ClientRegistration clientRegistration,
OAuth2AuthorizationExchange authorizationExchange) {
super(AuthorizationGrantType.AUTHORIZATION_CODE, clientRegistration);
Assert.notNull(authorizationExchange, "authorizationExchange cannot be null");
this.authorizationExchange = authorizationExchange;
}
/**
* Returns the {@link OAuth2AuthorizationExchange authorization exchange}.
* @return the {@link OAuth2AuthorizationExchange}
*/
public OAuth2AuthorizationExchange getAuthorizationExchange() {
return this.authorizationExchange;
}
}
| 2,432 | 37.015625 | 98 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/ReactiveOAuth2AccessTokenResponseClient.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 reactor.core.publisher.Mono;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
/**
* A reactive 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 Rob Winch
* @since 5.1
* @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 ReactiveOAuth2AccessTokenResponseClient<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
*/
Mono<OAuth2AccessTokenResponse> getTokenResponse(T authorizationGrantRequest);
}
| 2,546 | 40.754098 | 109 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/OAuth2RefreshTokenGrantRequestEntityConverter.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 OAuth2RefreshTokenGrantRequest} to a
* {@link RequestEntity} representation of an OAuth 2.0 Access Token Request for the
* Refresh Token Grant.
*
* @author Joe Grandja
* @since 5.2
* @see AbstractOAuth2AuthorizationGrantRequestEntityConverter
* @see OAuth2RefreshTokenGrantRequest
* @see RequestEntity
*/
public class OAuth2RefreshTokenGrantRequestEntityConverter
extends AbstractOAuth2AuthorizationGrantRequestEntityConverter<OAuth2RefreshTokenGrantRequest> {
@Override
protected MultiValueMap<String, String> createParameters(OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest) {
ClientRegistration clientRegistration = refreshTokenGrantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.add(OAuth2ParameterNames.GRANT_TYPE, refreshTokenGrantRequest.getGrantType().getValue());
parameters.add(OAuth2ParameterNames.REFRESH_TOKEN, refreshTokenGrantRequest.getRefreshToken().getTokenValue());
if (!CollectionUtils.isEmpty(refreshTokenGrantRequest.getScopes())) {
parameters.add(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(refreshTokenGrantRequest.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,815 | 45.163934 | 116 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/WebClientReactivePasswordTokenResponseClient.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.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.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
/**
* An implementation of a {@link ReactiveOAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#PASSWORD password} 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 OAuth2PasswordGrantRequest
* @see OAuth2AccessTokenResponse
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.3.2">Section 4.3.2 Access Token Request
* (Resource Owner Password Credentials Grant)</a>
* @see <a target="_blank" href=
* "https://tools.ietf.org/html/rfc6749#section-4.3.3">Section 4.3.3 Access Token Response
* (Resource Owner Password Credentials Grant)</a>
* @deprecated The latest OAuth 2.0 Security Best Current Practice disallows the use of
* the Resource Owner Password Credentials grant. See reference <a target="_blank" href=
* "https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics-19#section-2.4">OAuth
* 2.0 Security Best Current Practice.</a>
*/
@Deprecated
public final class WebClientReactivePasswordTokenResponseClient
extends AbstractWebClientReactiveOAuth2AccessTokenResponseClient<OAuth2PasswordGrantRequest> {
@Override
ClientRegistration clientRegistration(OAuth2PasswordGrantRequest grantRequest) {
return grantRequest.getClientRegistration();
}
@Override
Set<String> scopes(OAuth2PasswordGrantRequest grantRequest) {
return grantRequest.getClientRegistration().getScopes();
}
@Override
BodyInserters.FormInserter<String> populateTokenRequestBody(OAuth2PasswordGrantRequest grantRequest,
BodyInserters.FormInserter<String> body) {
return super.populateTokenRequestBody(grantRequest, body)
.with(OAuth2ParameterNames.USERNAME, grantRequest.getUsername())
.with(OAuth2ParameterNames.PASSWORD, grantRequest.getPassword());
}
}
| 3,087 | 41.30137 | 101 | java |
null | spring-security-main/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/endpoint/DefaultJwtBearerTokenResponseClient.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.util.Arrays;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.security.oauth2.core.http.converter.OAuth2AccessTokenResponseHttpMessageConverter;
import org.springframework.util.Assert;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
/**
* The default implementation of an {@link OAuth2AccessTokenResponseClient} for the
* {@link AuthorizationGrantType#JWT_BEARER jwt-bearer} grant. This implementation uses a
* {@link RestOperations} when requesting an access token credential at the Authorization
* Server's Token Endpoint.
*
* @author Joe Grandja
* @since 5.5
* @see OAuth2AccessTokenResponseClient
* @see JwtBearerGrantRequest
* @see OAuth2AccessTokenResponse
* @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 DefaultJwtBearerTokenResponseClient
implements OAuth2AccessTokenResponseClient<JwtBearerGrantRequest> {
private static final String INVALID_TOKEN_RESPONSE_ERROR_CODE = "invalid_token_response";
private Converter<JwtBearerGrantRequest, RequestEntity<?>> requestEntityConverter = new ClientAuthenticationMethodValidatingRequestEntityConverter<>(
new JwtBearerGrantRequestEntityConverter());
private RestOperations restOperations;
public DefaultJwtBearerTokenResponseClient() {
RestTemplate restTemplate = new RestTemplate(
Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
this.restOperations = restTemplate;
}
@Override
public OAuth2AccessTokenResponse getTokenResponse(JwtBearerGrantRequest jwtBearerGrantRequest) {
Assert.notNull(jwtBearerGrantRequest, "jwtBearerGrantRequest cannot be null");
RequestEntity<?> request = this.requestEntityConverter.convert(jwtBearerGrantRequest);
ResponseEntity<OAuth2AccessTokenResponse> response = getResponse(request);
// As per spec, in Section 5.1 Successful Access Token Response
// https://tools.ietf.org/html/rfc6749#section-5.1
// If AccessTokenResponse.scope is empty, then we assume all requested scopes were
// granted.
// However, we use the explicit scopes returned in the response (if any).
return response.getBody();
}
private ResponseEntity<OAuth2AccessTokenResponse> getResponse(RequestEntity<?> request) {
try {
return this.restOperations.exchange(request, OAuth2AccessTokenResponse.class);
}
catch (RestClientException ex) {
OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE,
"An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: "
+ ex.getMessage(),
null);
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
/**
* Sets the {@link Converter} used for converting the {@link JwtBearerGrantRequest} to
* a {@link RequestEntity} representation of the OAuth 2.0 Access Token Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the Access Token Request
*/
public void setRequestEntityConverter(Converter<JwtBearerGrantRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the OAuth 2.0 Access Token
* Response.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link HttpMessageConverter}'s - {@link FormHttpMessageConverter} and
* {@link OAuth2AccessTokenResponseHttpMessageConverter}</li>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the Access
* Token Response
*/
public void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
| 5,778 | 43.79845 | 150 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.