Search in sources :

Example 6 with InvalidRequestException

use of io.gravitee.am.common.exception.oauth2.InvalidRequestException in project gravitee-access-management by gravitee-io.

the class AccountFactorsEndpointHandler method verifyFactor.

/**
 * Verify a factor for the current user
 *
 * @param routingContext the routingContext holding the current user
 */
public void verifyFactor(RoutingContext routingContext) {
    try {
        if (routingContext.getBodyAsString() == null) {
            routingContext.fail(new InvalidRequestException("Unable to parse body message"));
            return;
        }
        final User user = routingContext.get(ConstantKeys.USER_CONTEXT_KEY);
        final String factorId = routingContext.request().getParam("factorId");
        final String code = routingContext.getBodyAsJson().getString("code");
        // code is required
        if (isEmpty(code)) {
            routingContext.fail(new InvalidRequestException("Field [code] is required"));
            return;
        }
        // find factor
        findFactor(factorId, h -> {
            if (h.failed()) {
                routingContext.fail(h.cause());
                return;
            }
            final FactorProvider factorProvider = factorManager.get(factorId);
            if (factorProvider == null) {
                routingContext.fail(new FactorNotFoundException(factorId));
                return;
            }
            // get enrolled factor for the current user
            Optional<EnrolledFactor> optionalEnrolledFactor = user.getFactors().stream().filter(enrolledFactor -> factorId.equals(enrolledFactor.getFactorId())).findFirst();
            if (!optionalEnrolledFactor.isPresent()) {
                routingContext.fail(new FactorNotFoundException(factorId));
                return;
            }
            // if factor is already activated, continue
            final EnrolledFactor enrolledFactor = optionalEnrolledFactor.get();
            if (FactorStatus.ACTIVATED.equals(enrolledFactor.getStatus())) {
                AccountResponseHandler.handleDefaultResponse(routingContext, enrolledFactor);
                return;
            }
            // verify factor
            verifyFactor(code, enrolledFactor, factorProvider, vh -> {
                if (vh.failed()) {
                    routingContext.fail(vh.cause());
                    return;
                }
                // verify successful, change the EnrolledFactor Status
                enrolledFactor.setStatus(FactorStatus.ACTIVATED);
                accountService.upsertFactor(user.getId(), enrolledFactor, new DefaultUser(user)).subscribe(__ -> AccountResponseHandler.handleDefaultResponse(routingContext, enrolledFactor), error -> routingContext.fail(error));
            });
        });
    } catch (DecodeException ex) {
        routingContext.fail(new InvalidRequestException("Unable to parse body message"));
    }
}
Also used : SHARED_SECRET(io.gravitee.am.common.factor.FactorSecurityType.SHARED_SECRET) FactorType(io.gravitee.am.common.factor.FactorType) Factor(io.gravitee.am.model.Factor) Json(io.vertx.core.json.Json) java.util(java.util) Client(io.gravitee.am.model.oidc.Client) DecodeException(io.vertx.core.json.DecodeException) Completable(io.reactivex.Completable) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) EnrolledFactorChannel(io.gravitee.am.model.factor.EnrolledFactorChannel) SecureRandom(java.security.SecureRandom) KEY_USER(io.gravitee.am.factor.api.FactorContext.KEY_USER) RECOVERY_CODE(io.gravitee.am.common.factor.FactorSecurityType.RECOVERY_CODE) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) Type(io.gravitee.am.model.factor.EnrolledFactorChannel.Type) FactorStatus(io.gravitee.am.model.factor.FactorStatus) Observable(io.reactivex.Observable) Schedulers(io.reactivex.schedulers.Schedulers) JsonObject(io.vertx.core.json.JsonObject) Objects.isNull(java.util.Objects.isNull) AsyncResult(io.vertx.core.AsyncResult) User(io.gravitee.am.model.User) InvalidFactorAttributeException(io.gravitee.am.common.exception.mfa.InvalidFactorAttributeException) UpdateEnrolledFactor(io.gravitee.am.gateway.handler.account.model.UpdateEnrolledFactor) FactorNotFoundException(io.gravitee.am.service.exception.FactorNotFoundException) RoutingContextHelper.getEvaluableAttributes(io.gravitee.am.gateway.handler.common.utils.RoutingContextHelper.getEvaluableAttributes) FactorDataKeys(io.gravitee.am.common.factor.FactorDataKeys) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest) Future(io.vertx.core.Future) RoutingContext(io.vertx.reactivex.ext.web.RoutingContext) ApplicationContext(org.springframework.context.ApplicationContext) Collectors(java.util.stream.Collectors) AccountService(io.gravitee.am.gateway.handler.account.services.AccountService) Maps(io.gravitee.common.util.Maps) StandardCharsets(java.nio.charset.StandardCharsets) EnrollmentAccount(io.gravitee.am.gateway.handler.account.model.EnrollmentAccount) EnrolledFactorSecurity(io.gravitee.am.model.factor.EnrolledFactorSecurity) EvaluableRequest(io.gravitee.gateway.api.el.EvaluableRequest) RecoveryFactor(io.gravitee.am.factor.api.RecoveryFactor) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StringUtils.isEmpty(org.springframework.util.StringUtils.isEmpty) FactorContext(io.gravitee.am.factor.api.FactorContext) Enrollment(io.gravitee.am.factor.api.Enrollment) Handler(io.vertx.core.Handler) FactorProvider(io.gravitee.am.factor.api.FactorProvider) FactorManager(io.gravitee.am.gateway.handler.common.factor.FactorManager) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) User(io.gravitee.am.model.User) EnrolledFactor(io.gravitee.am.model.factor.EnrolledFactor) UpdateEnrolledFactor(io.gravitee.am.gateway.handler.account.model.UpdateEnrolledFactor) FactorNotFoundException(io.gravitee.am.service.exception.FactorNotFoundException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) DecodeException(io.vertx.core.json.DecodeException) FactorProvider(io.gravitee.am.factor.api.FactorProvider)

Example 7 with InvalidRequestException

use of io.gravitee.am.common.exception.oauth2.InvalidRequestException in project gravitee-access-management by gravitee-io.

the class AccountEndpointHandler method changePassword.

public void changePassword(RoutingContext routingContext) {
    try {
        // update user password value from parameters
        final JsonObject bodyAsJson = routingContext.getBodyAsJson();
        if (isNull(bodyAsJson) || bodyAsJson.isEmpty()) {
            routingContext.fail(new InvalidRequestException("Body is null or empty"));
            return;
        }
        final Client client = routingContext.get(ConstantKeys.CLIENT_CONTEXT_KEY);
        final User user = getUserFromContext(routingContext);
        final DefaultUser principal = convertUserToPrincipal(routingContext, user);
        final String password = bodyAsJson.getString(PASSWORD_KEY);
        // user password is required
        if (isEmpty(password)) {
            routingContext.fail(new InvalidRequestException("Field [password] is required"));
            return;
        }
        accountService.resetPassword(user, client, password, principal).subscribe(__ -> handleNoBodyResponse(routingContext), error -> {
            if (error instanceof UserProviderNotFoundException) {
                handleUpdateUserResponse(routingContext, "Action forbidden", FORBIDDEN_403);
            } else {
                routingContext.fail(error);
            }
        });
    } catch (DecodeException ex) {
        routingContext.fail(new InvalidRequestException("Unable to parse body message"));
    }
}
Also used : DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) User(io.gravitee.am.model.User) UserProviderNotFoundException(io.gravitee.am.service.exception.UserProviderNotFoundException) JsonObject(io.vertx.core.json.JsonObject) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) Client(io.gravitee.am.model.oidc.Client) DecodeException(io.vertx.core.json.DecodeException)

Example 8 with InvalidRequestException

use of io.gravitee.am.common.exception.oauth2.InvalidRequestException in project gravitee-access-management by gravitee-io.

the class PermissionEndpoint method extractRequest.

/**
 * Specification state :
 * Requesting multiple permissions might be appropriate, for example, in cases where the resource server expects the requesting party
 * to need access to several related resources if they need access to any one of the resources
 *
 * Means : Body can either be a JsonArray or a JsonObject, we need to handle both case.
 *
 * See <a href="https://docs.kantarainitiative.org/uma/wg/rec-oauth-uma-federated-authz-2.0.html#permission-endpoint">here</a>
 * @param context RoutingContext
 * @return List of PermissionRequest
 */
private Single<List<PermissionTicketRequest>> extractRequest(RoutingContext context) {
    List<PermissionTicketRequest> result;
    Object json;
    try {
        json = context.getBody().toJson();
    } catch (RuntimeException err) {
        return Single.error(new InvalidRequestException("Unable to parse body permission request"));
    }
    if (json instanceof JsonArray) {
        result = convert(((JsonArray) json).getList());
    } else {
        result = Arrays.asList(((JsonObject) json).mapTo(PermissionTicketRequest.class));
    }
    return Single.just(result);
}
Also used : JsonArray(io.vertx.core.json.JsonArray) PermissionTicketRequest(io.gravitee.am.gateway.handler.uma.resources.request.PermissionTicketRequest) JsonObject(io.vertx.core.json.JsonObject) JsonObject(io.vertx.core.json.JsonObject) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException)

Example 9 with InvalidRequestException

use of io.gravitee.am.common.exception.oauth2.InvalidRequestException in project gravitee-access-management by gravitee-io.

the class ResourceAccessPoliciesEndpoint method extractRequest.

private AccessPolicy extractRequest(RoutingContext context) {
    try {
        // get body request
        JsonObject body = context.getBodyAsJson();
        // check missing values
        Arrays.asList("name", "type", "description", "condition").forEach(key -> {
            if (!body.containsKey(key)) {
                throw new InvalidRequestException("[" + key + ": must not be null]");
            }
        });
        // check type value
        AccessPolicyType accessPolicyType = AccessPolicyType.fromString(body.getString("type"));
        // check condition value
        AccessPolicyCondition condition = body.getJsonObject("condition").mapTo(accessPolicyType.getConditionClazz());
        // create access policy object
        AccessPolicy accessPolicy = new AccessPolicy();
        accessPolicy.setType(accessPolicyType);
        accessPolicy.setName(body.getString("name"));
        accessPolicy.setDescription(body.getString("description"));
        accessPolicy.setCondition(condition.toString());
        accessPolicy.setEnabled(body.getBoolean("enabled", true));
        return accessPolicy;
    } catch (DecodeException ex) {
        throw new InvalidRequestException("Bad request payload");
    } catch (Exception ex) {
        throw new InvalidRequestException(ex.getMessage());
    }
}
Also used : AccessPolicyCondition(io.gravitee.am.model.uma.policy.AccessPolicyCondition) AccessPolicyType(io.gravitee.am.model.uma.policy.AccessPolicyType) JsonObject(io.vertx.core.json.JsonObject) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) DecodeException(io.vertx.core.json.DecodeException) AccessPolicy(io.gravitee.am.model.uma.policy.AccessPolicy) DecodeException(io.vertx.core.json.DecodeException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) AccessPolicyNotFoundException(io.gravitee.am.service.exception.AccessPolicyNotFoundException)

Example 10 with InvalidRequestException

use of io.gravitee.am.common.exception.oauth2.InvalidRequestException in project gravitee-access-management by gravitee-io.

the class CibaTokenGranter method parseRequest.

@Override
protected Single<TokenRequest> parseRequest(TokenRequest tokenRequest, Client client) {
    MultiValueMap<String, String> parameters = tokenRequest.parameters();
    final String authReqId = parameters.getFirst(Parameters.AUTH_REQ_ID);
    if (isEmpty(authReqId)) {
        return Single.error(new InvalidRequestException("Missing parameter: auth_req_id"));
    }
    return super.parseRequest(tokenRequest, client).flatMap(tokenRequest1 -> authenticationRequestService.retrieve(domain, authReqId).map(cibaRequest -> {
        if (!cibaRequest.getClientId().equals(client.getClientId())) {
            logger.warn("client_id '{}' requests token using not owned authentication request '{}'", client.getId(), authReqId);
            throw new AuthenticationRequestNotFoundException("Authentication request not found");
        }
        return cibaRequest;
    }).map(cibaRequest -> {
        // set resource owner
        tokenRequest1.setSubject(cibaRequest.getSubject());
        // set original scopes
        tokenRequest1.setScopes(cibaRequest.getScopes());
        // store only the AuthenticationFlowContext.data attributes in order to simplify EL templating
        // and provide an up to date set of data if the enrichAuthFlow Policy ius used multiple time in a step
        // {#context.attributes['authFlow']['entry']}
        tokenRequest1.getContext().put(AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, emptyMap());
        return tokenRequest1;
    }));
}
Also used : InvalidGrantException(io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException) Collections.emptyMap(java.util.Collections.emptyMap) GrantType(io.gravitee.am.common.oauth2.GrantType) Logger(org.slf4j.Logger) 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) LoggerFactory(org.slf4j.LoggerFactory) AuthenticationRequestService(io.gravitee.am.gateway.handler.ciba.service.AuthenticationRequestService) Domain(io.gravitee.am.model.Domain) ConstantKeys(io.gravitee.am.common.utils.ConstantKeys) AbstractTokenGranter(io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter) TokenService(io.gravitee.am.gateway.handler.oauth2.service.token.TokenService) Single(io.reactivex.Single) Parameters(io.gravitee.am.common.ciba.Parameters) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException) TokenRequestResolver(io.gravitee.am.gateway.handler.oauth2.service.request.TokenRequestResolver) StringUtils.isEmpty(org.springframework.util.StringUtils.isEmpty) User(io.gravitee.am.model.User) AuthenticationRequestNotFoundException(io.gravitee.am.gateway.handler.ciba.exception.AuthenticationRequestNotFoundException) AuthenticationRequestNotFoundException(io.gravitee.am.gateway.handler.ciba.exception.AuthenticationRequestNotFoundException) InvalidRequestException(io.gravitee.am.common.exception.oauth2.InvalidRequestException)

Aggregations

InvalidRequestException (io.gravitee.am.common.exception.oauth2.InvalidRequestException)37 Client (io.gravitee.am.model.oidc.Client)20 ConstantKeys (io.gravitee.am.common.utils.ConstantKeys)10 User (io.gravitee.am.model.User)9 RoutingContext (io.vertx.reactivex.ext.web.RoutingContext)9 JsonObject (io.vertx.core.json.JsonObject)8 Domain (io.gravitee.am.model.Domain)6 ParseException (java.text.ParseException)6 Date (java.util.Date)6 Parameters (io.gravitee.am.common.oauth2.Parameters)5 DefaultUser (io.gravitee.am.identityprovider.api.DefaultUser)5 Handler (io.vertx.core.Handler)5 Collectors (java.util.stream.Collectors)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 AsyncResult (io.vertx.core.AsyncResult)4 Future (io.vertx.core.Future)4 HttpServerRequest (io.vertx.reactivex.core.http.HttpServerRequest)4 StandardCharsets (java.nio.charset.StandardCharsets)4