Search in sources :

Example 1 with InvalidGrantException

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");
        }
    }
}
Also used : InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)

Example 2 with InvalidGrantException

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();
}
Also used : InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) GrantType(io.gravitee.am.common.oauth2.GrantType) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) Single(io.reactivex.Single) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) USERNAME(io.gravitee.am.common.oauth2.Parameters.USERNAME) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication) TokenRequestResolver(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver) PASSWORD(io.gravitee.am.common.oauth2.Parameters.PASSWORD) User(io.gravitee.am.model.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) EndUserAuthentication(io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)

Example 3 with InvalidGrantException

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);
}
Also used : RequiredClaims(io.gravitee.am.common.exception.uma.RequiredClaims) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)

Example 4 with InvalidGrantException

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")));
    });
}
Also used : DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule) PermissionTicket(io.gravitee.am.model.uma.PermissionTicket) ResourceService(io.gravitee.am.service.ResourceService) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) MultiValueMap(io.gravitee.common.util.MultiValueMap) Maybe(io.reactivex.Maybe) InvalidTokenException(io.gravitee.am.common.exception.oauth2.InvalidTokenException) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) TechnicalException(io.gravitee.am.repository.exceptions.TechnicalException) InvalidScopeException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidScopeException) Single(io.reactivex.Single) JWTService(io.gravitee.am.gateway.handler.common.jwt.JWTService) RulesEngine(io.gravitee.am.gateway.handler.uma.policy.RulesEngine) JsonObject(io.vertx.core.json.JsonObject) Rule(io.gravitee.am.gateway.handler.uma.policy.Rule) PermissionTicketService(io.gravitee.am.service.PermissionTicketService) TokenType(io.gravitee.am.common.oauth2.TokenType) User(io.gravitee.am.model.User) ExecutionContextFactory(io.gravitee.am.gateway.handler.context.ExecutionContextFactory) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) GrantType(io.gravitee.am.common.oauth2.GrantType) ClientProperties(io.gravitee.am.model.safe.ClientProperties) PermissionRequest(io.gravitee.am.model.uma.PermissionRequest) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) JWT(io.gravitee.am.common.jwt.JWT) UserAuthenticationManager(io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager) TokenRequest(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest) UmaException(io.gravitee.am.common.exception.uma.UmaException) Domain(io.gravitee.am.model.Domain) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) Resource(io.gravitee.am.model.uma.Resource) UserInvalidException(io.gravitee.am.service.exception.UserInvalidException) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) RequiredClaims(io.gravitee.am.common.exception.uma.RequiredClaims) Token(io.gravitee.am.gateway.handler.oauth2.service.token.Token) DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule) ApplicationScopeSettings(io.gravitee.am.model.application.ApplicationScopeSettings) UserProperties(io.gravitee.am.model.safe.UserProperties) OAuth2Request(io.gravitee.am.gateway.handler.oauth2.service.request.OAuth2Request) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) Parameters(io.gravitee.am.common.oauth2.Parameters) StringUtils(org.springframework.util.StringUtils) PermissionRequest(io.gravitee.am.model.uma.PermissionRequest) ClientProperties(io.gravitee.am.model.safe.ClientProperties) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) UserProperties(io.gravitee.am.model.safe.UserProperties) Rule(io.gravitee.am.gateway.handler.uma.policy.Rule) DefaultRule(io.gravitee.am.gateway.handler.uma.policy.DefaultRule)

Example 5 with InvalidGrantException

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);
}
Also used : LinkedMultiValueMap(io.gravitee.common.util.LinkedMultiValueMap) Client(io.gravitee.am.model.oidc.Client) InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) Test(org.junit.Test)

Aggregations

InvalidGrantException (io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)6 Client (io.gravitee.am.model.oidc.Client)4 UserAuthenticationManager (io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager)3 AbstractTokenGranter (io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter)3 TokenRequest (io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequest)3 TokenService (io.gravitee.am.gateway.handler.oauth2.service.token.TokenService)3 User (io.gravitee.am.model.User)3 Maybe (io.reactivex.Maybe)3 Single (io.reactivex.Single)3 InvalidRequestException (io.gravitee.am.common.exception.oauth2.InvalidRequestException)2 RequiredClaims (io.gravitee.am.common.exception.uma.RequiredClaims)2 GrantType (io.gravitee.am.common.oauth2.GrantType)2 EndUserAuthentication (io.gravitee.am.gateway.handler.common.auth.user.EndUserAuthentication)2 TokenRequestResolver (io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver)2 SimpleAuthenticationContext (io.gravitee.am.identityprovider.api.SimpleAuthenticationContext)2 InvalidTokenException (io.gravitee.am.common.exception.oauth2.InvalidTokenException)1 UmaException (io.gravitee.am.common.exception.uma.UmaException)1 JWT (io.gravitee.am.common.jwt.JWT)1 Parameters (io.gravitee.am.common.oauth2.Parameters)1 PASSWORD (io.gravitee.am.common.oauth2.Parameters.PASSWORD)1