use of io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException in project gravitee-access-management by gravitee-io.
the class AuthorizationCodeTokenGranter method checkPKCE.
/**
* // https://tools.ietf.org/html/rfc7636#section-4.6
* @param tokenRequest
* @param authorizationCode
*/
private void checkPKCE(TokenRequest tokenRequest, AuthorizationCode authorizationCode) {
String codeVerifier = tokenRequest.parameters().getFirst(Parameters.CODE_VERIFIER);
MultiValueMap<String, String> parameters = authorizationCode.getRequestParameters();
String codeChallenge = parameters.getFirst(Parameters.CODE_CHALLENGE);
String codeChallengeMethod = parameters.getFirst(Parameters.CODE_CHALLENGE_METHOD);
if (codeChallenge != null && codeVerifier == null) {
logger.debug("PKCE code_verifier parameter is missing, even if a code_challenge was initially defined");
throw new InvalidGrantException("Missing parameter: code_verifier");
}
if (codeChallenge != null) {
// Check that code challenge is valid
if (!PKCEUtils.validCodeVerifier(codeVerifier)) {
logger.debug("PKCE code_verifier is not valid");
throw new InvalidGrantException("Invalid parameter: code_verifier");
}
// By default, assume a plain code_challenge_method
String encodedCodeVerifier = codeVerifier;
// Otherwise, generate is using s256
if (CodeChallengeMethod.S256.equalsIgnoreCase(codeChallengeMethod)) {
try {
encodedCodeVerifier = PKCEUtils.getS256CodeChallenge(codeVerifier);
} catch (Exception ex) {
logger.error("Not able to generate the codeChallenge from the given code verifier according to S256 algorithm");
throw new InvalidGrantException("Not supported algorithm");
}
}
if (!codeChallenge.equals(encodedCodeVerifier)) {
throw new InvalidGrantException("Invalid code_verifier");
}
}
}
use of io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException in project gravitee-access-management by gravitee-io.
the class ResourceOwnerPasswordCredentialsTokenGranter method resolveResourceOwner.
@Override
protected Maybe<User> resolveResourceOwner(TokenRequest tokenRequest, Client client) {
String username = tokenRequest.getUsername();
String password = tokenRequest.getPassword();
return userAuthenticationManager.authenticate(client, new EndUserAuthentication(username, password, new SimpleAuthenticationContext(tokenRequest))).onErrorResumeNext(ex -> Single.error(new InvalidGrantException(ex.getMessage()))).toMaybe();
}
use of io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException in project gravitee-access-management by gravitee-io.
the class UMATokenGranter method parseRequest.
@Override
protected Single<TokenRequest> parseRequest(TokenRequest tokenRequest, Client client) {
MultiValueMap<String, String> parameters = tokenRequest.parameters();
String ticket = parameters.getFirst(TICKET);
String claimToken = parameters.getFirst(CLAIM_TOKEN);
String claimTokenFormat = parameters.getFirst(CLAIM_TOKEN_FORMAT);
String persistedClaimsToken = parameters.getFirst(PCT);
String requestingPartyToken = parameters.getFirst(RPT);
if (ticket == null) {
return Single.error(new InvalidGrantException("Missing parameter: ticket"));
}
// if there's only one of both informed
if (claimToken != null ^ claimTokenFormat != null) {
return Single.error(UmaException.needInfoBuilder(ticket).requiredClaims(Arrays.asList(new RequiredClaims(CLAIM_TOKEN).setFriendlyName("Requesting party token"), new RequiredClaims(CLAIM_TOKEN_FORMAT).setFriendlyName("supported claims token format").setClaimTokenFormat(CLAIM_TOKEN_FORMAT_SUPPORTED))).build());
}
if (!StringUtils.isEmpty(claimTokenFormat) && !CLAIM_TOKEN_FORMAT_SUPPORTED.contains(claimTokenFormat)) {
return Single.error(UmaException.needInfoBuilder(ticket).requiredClaims(Arrays.asList(new RequiredClaims(CLAIM_TOKEN_FORMAT).setFriendlyName("supported claims token format").setClaimTokenFormat(CLAIM_TOKEN_FORMAT_SUPPORTED))).build());
}
// set required parameters
tokenRequest.setTicket(ticket);
// set optional parameters
tokenRequest.setClaimToken(claimToken);
tokenRequest.setClaimTokenFormat(claimTokenFormat);
tokenRequest.setPersistedClaimsToken(persistedClaimsToken);
tokenRequest.setRequestingPartyToken(requestingPartyToken);
return super.parseRequest(tokenRequest, client);
}
use of io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException in project gravitee-access-management by gravitee-io.
the class UMATokenGranter method executePolicies.
/**
* The resource owner works with the authorization server to configure policy conditions (authorization grant rules), which the authorization server executes in the process of issuing access tokens.
* The authorization process makes use of claims gathered from the requesting party and client in order to satisfy all operative operative policy conditions.
* @param oAuth2Request OAuth 2.0 Token Request
* @param client client
* @param endUser requesting party
* @return
*/
private Single<OAuth2Request> executePolicies(OAuth2Request oAuth2Request, Client client, User endUser) {
List<PermissionRequest> permissionRequests = oAuth2Request.getPermissions();
if (permissionRequests == null || permissionRequests.isEmpty()) {
return Single.just(oAuth2Request);
}
List<String> resourceIds = permissionRequests.stream().map(PermissionRequest::getResourceId).collect(Collectors.toList());
// find access policies for the given resources
return resourceService.findAccessPoliciesByResources(resourceIds).map(accessPolicy -> {
Rule rule = new DefaultRule(accessPolicy);
Optional<PermissionRequest> permission = permissionRequests.stream().filter(permissionRequest -> permissionRequest.getResourceId().equals(accessPolicy.getResource())).findFirst();
if (permission.isPresent()) {
((DefaultRule) rule).setMetadata(Collections.singletonMap("permissionRequest", permission.get()));
}
return rule;
}).toList().flatMap(rules -> {
// no policy registered, continue
if (rules.isEmpty()) {
return Single.just(oAuth2Request);
}
// prepare the execution context
ExecutionContext simpleExecutionContext = new SimpleExecutionContext(oAuth2Request, oAuth2Request.getHttpResponse());
ExecutionContext executionContext = executionContextFactory.create(simpleExecutionContext);
executionContext.setAttribute("client", new ClientProperties(client));
if (endUser != null) {
executionContext.setAttribute("user", new UserProperties(endUser));
}
// execute the policies
return rulesEngine.fire(rules, executionContext).toSingleDefault(oAuth2Request).onErrorResumeNext(ex -> Single.error(new InvalidGrantException("Policy conditions are not met for actual request parameters")));
});
}
use of io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException in project gravitee-access-management by gravitee-io.
the class RefreshTokenGranterTest method shouldNotGenerateAnAccessToken_invalidGrant.
@Test
public void shouldNotGenerateAnAccessToken_invalidGrant() {
String refreshToken = "refresh-token";
LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
parameters.set("refresh_token", refreshToken);
Client client = new Client();
client.setClientId("my-client-id");
client.setAuthorizedGrantTypes(Arrays.asList(new String[] { "refresh_token" }));
when(tokenRequest.parameters()).thenReturn(parameters);
when(tokenService.refresh(refreshToken, tokenRequest, client)).thenReturn(Single.error(new InvalidGrantException()));
granter.grant(tokenRequest, client).test().assertError(InvalidGrantException.class);
}
Aggregations