Skip to content

Add client_credentials grant type support #88

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationProvider;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.web.OAuth2AuthorizationEndpointFilter;
import org.springframework.security.oauth2.server.authorization.web.OAuth2ClientAuthenticationFilter;
Expand Down Expand Up @@ -88,7 +89,12 @@ public void init(B builder) {
new OAuth2AuthorizationCodeAuthenticationProvider(
getRegisteredClientRepository(builder),
getAuthorizationService(builder));

OAuth2ClientCredentialsAuthenticationProvider clientCredentialsAuthenticationProvider
= new OAuth2ClientCredentialsAuthenticationProvider();

builder.authenticationProvider(postProcess(authorizationCodeAuthenticationProvider));
builder.authenticationProvider(postProcess(clientCredentialsAuthenticationProvider));
}

@Override
Expand Down
1 change: 1 addition & 0 deletions core/spring-authorization-server-core.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dependencies {
testCompile 'org.assertj:assertj-core'
testCompile 'org.mockito:mockito-core'
testCompile 'com.squareup.okhttp3:mockwebserver'
testCompile 'com.jayway.jsonpath:json-path'

provided 'javax.servlet:javax.servlet-api'
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.oauth2.server.authorization.authentication;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.Set;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
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.OAuth2ErrorCodes;

/**
* An {@link AuthenticationProvider} implementation for the OAuth 2.0 Client Credentials Grant.
*
* @author Alexey Nesterov
* @since 0.0.1
* @see OAuth2ClientCredentialsAuthenticationToken
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4">Section 4.4 Client Credentials Grant</a>
* @see <a target="_blank" href="https://tools.ietf.org/html/rfc6749#section-4.4.2">Section 4.4.2 Access Token Request</a>
*/

public class OAuth2ClientCredentialsAuthenticationProvider implements AuthenticationProvider {

private final StringKeyGenerator accessTokenGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthenticationToken =
(OAuth2ClientCredentialsAuthenticationToken) authentication;

OAuth2ClientAuthenticationToken clientPrincipal = null;
if (OAuth2ClientAuthenticationToken.class.isAssignableFrom(clientCredentialsAuthenticationToken.getPrincipal().getClass())) {
clientPrincipal = (OAuth2ClientAuthenticationToken) clientCredentialsAuthenticationToken.getPrincipal();
}

if (clientPrincipal == null || !clientPrincipal.isAuthenticated()) {
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT));
}

Set<String> clientScopes = clientPrincipal.getRegisteredClient().getScopes();
Set<String> requestedScopes = clientCredentialsAuthenticationToken.getScopes();
if (!clientScopes.containsAll(requestedScopes)) {
throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_SCOPE));
}

if (requestedScopes == null || requestedScopes.isEmpty()) {
requestedScopes = clientScopes;
}

String tokenValue = this.accessTokenGenerator.generateKey();
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(1, ChronoUnit.HOURS); // TODO Allow configuration for access token lifespan
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
tokenValue, issuedAt, expiresAt, requestedScopes);

return new OAuth2AccessTokenAuthenticationToken(
clientPrincipal.getRegisteredClient(), clientPrincipal, accessToken);
}

@Override
public boolean supports(Class<?> authentication) {
return OAuth2ClientCredentialsAuthenticationToken.class.isAssignableFrom(authentication);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.security.oauth2.server.authorization.authentication;

import java.util.Collections;
import java.util.Set;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.server.authorization.Version;
import org.springframework.util.Assert;

/**
* An {@link Authentication} implementation used for the OAuth 2.0 Client Credentials Grant.
*
* @author Alexey Nesterov
* @since 0.0.1
* @see Authentication
* @see OAuth2ClientCredentialsAuthenticationProvider
*/
public class OAuth2ClientCredentialsAuthenticationToken extends AbstractAuthenticationToken {

private static final long serialVersionUID = Version.SERIAL_VERSION_UID;

private final Authentication clientPrincipal;
private final Set<String> scopes;

public OAuth2ClientCredentialsAuthenticationToken(Authentication clientPrincipal, Set<String> scopes) {
super(Collections.emptyList());
Assert.notNull(clientPrincipal, "clientPrincipal cannot be null");
Assert.notNull(scopes, "scopes cannot be null");
this.clientPrincipal = clientPrincipal;
this.scopes = scopes;
}

@SuppressWarnings("unchecked")
public OAuth2ClientCredentialsAuthenticationToken(OAuth2ClientAuthenticationToken clientPrincipal) {
this(clientPrincipal, Collections.EMPTY_SET);
}

@Override
public Object getCredentials() {
return "";
}

@Override
public Object getPrincipal() {
return this.clientPrincipal;
}

public Set<String> getScopes() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add @Nullable

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scopes is never null, do you mean @NonNull?

return this.scopes;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.security.oauth2.server.authorization.web;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Map;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
* A {@link Converter} that delegates actual conversion to one of the provided converters based on grant_type param of a request.
* Returns null is grant type is not specified or not supported.
*
* @author Alexey Nesterov
* @since 0.0.1
*/
public final class DelegatingAuthorizationGrantAuthenticationConverter implements Converter<HttpServletRequest, Authentication> {

private final Map<AuthorizationGrantType, Converter<HttpServletRequest, Authentication>> converters;

public DelegatingAuthorizationGrantAuthenticationConverter(Map<AuthorizationGrantType, Converter<HttpServletRequest, Authentication>> converters) {
Assert.notEmpty(converters, "converters cannot be empty");

this.converters = Collections.unmodifiableMap(converters);
}

@Override
public Authentication convert(HttpServletRequest request) {
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (StringUtils.isEmpty(grantType)) {
return null;
}

Converter<HttpServletRequest, Authentication> converter = this.converters.get(new AuthorizationGrantType(grantType));
if (converter == null) {
return null;
}

return converter.convert(request);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientCredentialsAuthenticationToken;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
Expand All @@ -48,6 +50,11 @@
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
* A {@code Filter} for the OAuth 2.0 Authorization Code Grant,
Expand Down Expand Up @@ -86,8 +93,8 @@ public class OAuth2TokenEndpointFilter extends OncePerRequestFilter {
private final AuthenticationManager authenticationManager;
private final OAuth2AuthorizationService authorizationService;
private final RequestMatcher tokenEndpointMatcher;
private final Converter<HttpServletRequest, Authentication> authorizationGrantAuthenticationConverter =
new AuthorizationCodeAuthenticationConverter();
private final Converter<HttpServletRequest, Authentication> authorizationGrantAuthenticationConverter;

private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter =
new OAuth2AccessTokenResponseHttpMessageConverter();
private final HttpMessageConverter<OAuth2Error> errorHttpResponseConverter =
Expand Down Expand Up @@ -119,6 +126,11 @@ public OAuth2TokenEndpointFilter(AuthenticationManager authenticationManager,
this.authenticationManager = authenticationManager;
this.authorizationService = authorizationService;
this.tokenEndpointMatcher = new AntPathRequestMatcher(tokenEndpointUri, HttpMethod.POST.name());

Map<AuthorizationGrantType, Converter<HttpServletRequest, Authentication>> converters = new HashMap<>();
converters.put(AuthorizationGrantType.AUTHORIZATION_CODE, new AuthorizationCodeAuthenticationConverter());
converters.put(AuthorizationGrantType.CLIENT_CREDENTIALS, new ClientCredentialsAuthenticationConverter());
this.authorizationGrantAuthenticationConverter = new DelegatingAuthorizationGrantAuthenticationConverter(converters);
}

@Override
Expand All @@ -131,8 +143,16 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

try {
Authentication authorizationGrantAuthentication =
this.authorizationGrantAuthenticationConverter.convert(request);
String[] grantTypes = request.getParameterValues(OAuth2ParameterNames.GRANT_TYPE);
if (grantTypes == null || grantTypes.length == 0) {
throwError(OAuth2ErrorCodes.INVALID_REQUEST, "grant_type");
}

Authentication authorizationGrantAuthentication = this.authorizationGrantAuthenticationConverter.convert(request);
if (authorizationGrantAuthentication == null) {
throwError(OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE, "grant_type");
}

OAuth2AccessTokenAuthenticationToken accessTokenAuthentication =
(OAuth2AccessTokenAuthenticationToken) this.authenticationManager.authenticate(authorizationGrantAuthentication);
sendAccessTokenResponse(response, accessTokenAuthentication.getAccessToken());
Expand Down Expand Up @@ -161,7 +181,7 @@ private void sendErrorResponse(HttpServletResponse response, OAuth2Error error)
this.errorHttpResponseConverter.write(error, null, httpResponse);
}

private static OAuth2AuthenticationException throwError(String errorCode, String parameterName) {
private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName,
"https://tools.ietf.org/html/rfc6749#section-5.2");
throw new OAuth2AuthenticationException(error);
Expand Down Expand Up @@ -214,4 +234,29 @@ public Authentication convert(HttpServletRequest request) {
new OAuth2AuthorizationCodeAuthenticationToken(code, clientId, redirectUri);
}
}

private static class ClientCredentialsAuthenticationConverter implements Converter<HttpServletRequest, Authentication> {

@Override
public Authentication convert(HttpServletRequest request) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
final OAuth2ClientAuthenticationToken clientAuthenticationToken = (OAuth2ClientAuthenticationToken) authentication;

// grant_type (REQUIRED)
String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
if (!AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equals(grantType)) {
throwError(OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE, OAuth2ParameterNames.GRANT_TYPE);
}

// scope (OPTIONAL)
// https://tools.ietf.org/html/rfc6749#section-4.4.2
String scopeParameter = request.getParameter(OAuth2ParameterNames.SCOPE);
if (StringUtils.isEmpty(scopeParameter)) {
return new OAuth2ClientCredentialsAuthenticationToken(clientAuthenticationToken);
}

Set<String> requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scopeParameter, " ")));
return new OAuth2ClientCredentialsAuthenticationToken(clientAuthenticationToken, requestedScopes);
}
}
}
Loading