Search in sources :

Example 1 with AuthenticationFlowContext

use of io.gravitee.am.model.AuthenticationFlowContext in project gravitee-access-management by gravitee-io.

the class PolicyChainHandlerImpl method handle.

@Override
public void handle(RoutingContext context) {
    // do not call the policy chain if there is error, success or warning parameters
    // it means that the policy chain has been already executed
    final HttpServerRequest request = context.request();
    if (request.params() != null && (request.params().contains(ConstantKeys.ERROR_PARAM_KEY) || request.params().contains(ConstantKeys.WARNING_PARAM_KEY) || request.params().contains(ConstantKeys.SUCCESS_PARAM_KEY))) {
        context.next();
        return;
    }
    // prepare execution context
    prepareContext(context, contextHandler -> {
        if (contextHandler.failed()) {
            logger.error("An error occurs while preparing execution context", contextHandler.cause());
            context.fail(contextHandler.cause());
            return;
        }
        // resolve policies
        ExecutionContext executionContext = contextHandler.result();
        resolve(executionContext, handler -> {
            if (handler.failed()) {
                logger.error("An error occurs while resolving policies", handler.cause());
                context.fail(handler.cause());
                return;
            }
            List<Policy> policies = handler.result();
            // if no policies continue
            if (policies.isEmpty()) {
                context.next();
                return;
            }
            // call the policy chain
            executePolicyChain(policies, executionContext, policyChainHandler -> {
                if (policyChainHandler.failed()) {
                    logger.debug("An error occurs while executing the policy chain", policyChainHandler.cause());
                    context.fail(policyChainHandler.cause());
                    return;
                }
                // update context attributes
                ExecutionContext processedExecutionContext = policyChainHandler.result();
                processedExecutionContext.getAttributes().forEach((k, v) -> {
                    if (ConstantKeys.AUTH_FLOW_CONTEXT_KEY.equals(k)) {
                        final AuthenticationFlowContext authFlowContext = (AuthenticationFlowContext) v;
                        if (authFlowContext != null) {
                            // update authentication flow context version into the session
                            context.session().put(ConstantKeys.AUTH_FLOW_CONTEXT_VERSION_KEY, authFlowContext.getVersion());
                        }
                    }
                    context.put(k, v);
                });
                // continue
                context.next();
            });
        });
    });
}
Also used : Policy(io.gravitee.am.gateway.policy.Policy) ExecutionContext(io.gravitee.gateway.api.ExecutionContext) SimpleExecutionContext(io.gravitee.gateway.api.context.SimpleExecutionContext) AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest)

Example 2 with AuthenticationFlowContext

use of io.gravitee.am.model.AuthenticationFlowContext in project gravitee-access-management by gravitee-io.

the class AuthorizationRequestFactory method create.

public AuthorizationRequest create(RoutingContext context) {
    HttpServerRequest request = context.request();
    AuthorizationRequest authorizationRequest = new AuthorizationRequest();
    // set technical information
    authorizationRequest.setTimestamp(System.currentTimeMillis());
    authorizationRequest.setId(RandomString.generate());
    if (context.session() != null) {
        authorizationRequest.setTransactionId(context.session().get(ConstantKeys.TRANSACTION_ID_KEY));
    }
    if (context.get(ConstantKeys.AUTH_FLOW_CONTEXT_KEY) != null) {
        AuthenticationFlowContext authFlowContext = context.get(ConstantKeys.AUTH_FLOW_CONTEXT_KEY);
        authorizationRequest.setContextVersion(authFlowContext.getVersion());
        authorizationRequest.getContext().put(ConstantKeys.AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, authFlowContext.getData());
    }
    authorizationRequest.setUri(request.uri());
    authorizationRequest.setOrigin(extractOrigin(context));
    authorizationRequest.setContextPath(request.path() != null ? request.path().split("/")[0] : null);
    authorizationRequest.setPath(request.path());
    authorizationRequest.setHeaders(extractHeaders(request));
    authorizationRequest.setParameters(extractRequestParameters(request));
    authorizationRequest.setSslSession(request.sslSession());
    authorizationRequest.setMethod(request.method() != null ? HttpMethod.valueOf(request.method().name()) : null);
    authorizationRequest.setScheme(request.scheme());
    authorizationRequest.setVersion(request.version() != null ? HttpVersion.valueOf(request.version().name()) : null);
    authorizationRequest.setRemoteAddress(request.remoteAddress() != null ? request.remoteAddress().host() : null);
    authorizationRequest.setLocalAddress(request.localAddress() != null ? request.localAddress().host() : null);
    authorizationRequest.setHttpResponse(new VertxHttpServerResponse(request.getDelegate(), new VertxHttpServerRequest(request.getDelegate()).metrics()));
    // set OAuth 2.0 information
    authorizationRequest.setClientId(request.params().get(Parameters.CLIENT_ID));
    authorizationRequest.setResponseType(getOAuthParameter(context, Parameters.RESPONSE_TYPE));
    authorizationRequest.setRedirectUri(getOAuthParameter(context, Parameters.REDIRECT_URI));
    String scope = getOAuthParameter(context, Parameters.SCOPE);
    authorizationRequest.setScopes(scope != null && !scope.isEmpty() ? new HashSet<>(Arrays.asList(scope.split("\\s+"))) : null);
    authorizationRequest.setState(getOAuthParameter(context, Parameters.STATE));
    authorizationRequest.setResponseMode(getOAuthParameter(context, Parameters.RESPONSE_MODE));
    authorizationRequest.setAdditionalParameters(extractAdditionalParameters(request));
    authorizationRequest.setApproved(context.session() != null && Boolean.TRUE.equals(context.session().get(ConstantKeys.USER_CONSENT_APPROVED_KEY)));
    // set OIDC information
    String prompt = getOAuthParameter(context, io.gravitee.am.common.oidc.Parameters.PROMPT);
    authorizationRequest.setPrompts(prompt != null ? new HashSet<>(Arrays.asList(prompt.split("\\s+"))) : Collections.emptySet());
    if (authorizationRequest.getParameters() == null) {
        authorizationRequest.setParameters(new LinkedMultiValueMap<>());
    }
    String nonce = getOAuthParameter(context, io.gravitee.am.common.oidc.Parameters.NONCE);
    if (nonce != null) {
        authorizationRequest.getParameters().put(io.gravitee.am.common.oidc.Parameters.NONCE, List.of(nonce));
    }
    String codeChallenge = getOAuthParameter(context, Parameters.CODE_CHALLENGE);
    if (codeChallenge != null) {
        authorizationRequest.getParameters().put(Parameters.CODE_CHALLENGE, List.of(codeChallenge));
    }
    String codeChallengeMethod = getOAuthParameter(context, Parameters.CODE_CHALLENGE_METHOD);
    if (codeChallengeMethod != null) {
        authorizationRequest.getParameters().put(Parameters.CODE_CHALLENGE_METHOD, List.of(codeChallengeMethod));
    }
    // store authorization request in context for later use
    context.put(ConstantKeys.AUTHORIZATION_REQUEST_CONTEXT_KEY, authorizationRequest);
    return authorizationRequest;
}
Also used : AuthorizationRequest(io.gravitee.am.gateway.handler.oauth2.service.request.AuthorizationRequest) AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) HttpServerRequest(io.vertx.reactivex.core.http.HttpServerRequest) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest) VertxHttpServerResponse(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerResponse) RandomString(io.gravitee.am.common.utils.RandomString) VertxHttpServerRequest(io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest)

Example 3 with AuthenticationFlowContext

use of io.gravitee.am.model.AuthenticationFlowContext in project gravitee-access-management by gravitee-io.

the class AuthenticationFlowContextRepositoryTest method generateAuthContext.

protected AuthenticationFlowContext generateAuthContext(Instant now, int version) {
    AuthenticationFlowContext entity = new AuthenticationFlowContext();
    entity.setVersion(version);
    entity.setTransactionId(TRANSACTION_ID);
    entity.setData(Collections.singletonMap("Key", "Value"));
    entity.setCreatedAt(new Date(now.toEpochMilli()));
    entity.setExpireAt(new Date(now.plus(2, ChronoUnit.MINUTES).toEpochMilli()));
    return entity;
}
Also used : AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) Date(java.util.Date)

Example 4 with AuthenticationFlowContext

use of io.gravitee.am.model.AuthenticationFlowContext in project gravitee-access-management by gravitee-io.

the class AuthenticationFlowContextRepositoryTest method shouldDeleteSingle.

@Test
public void shouldDeleteSingle() {
    AuthenticationFlowContext entity = generateAuthContext();
    authenticationFlowContextRepository.create(entity).blockingGet();
    entity = generateAuthContext(Instant.now(), 2);
    authenticationFlowContextRepository.create(entity).blockingGet();
    TestSubscriber<AuthenticationFlowContext> testList = authenticationFlowContextRepository.findByTransactionId(TRANSACTION_ID).test();
    testList.awaitTerminalEvent();
    testList.assertNoErrors();
    testList.assertValueCount(2);
    TestObserver<Void> testObserver = authenticationFlowContextRepository.delete(TRANSACTION_ID, 1).test();
    testObserver.awaitTerminalEvent();
    testObserver.assertNoErrors();
    testList = authenticationFlowContextRepository.findByTransactionId(TRANSACTION_ID).test();
    testList.awaitTerminalEvent();
    testList.assertNoErrors();
    testList.assertValueCount(1);
    AuthenticationFlowContext readValue = authenticationFlowContextRepository.findByTransactionId(TRANSACTION_ID).blockingFirst();
    assertNotNull(readValue);
    assertEquals("Expected version 2 because version 1 should be deleted", 2, readValue.getVersion());
}
Also used : AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) Test(org.junit.Test) AbstractManagementTest(io.gravitee.am.repository.management.AbstractManagementTest)

Example 5 with AuthenticationFlowContext

use of io.gravitee.am.model.AuthenticationFlowContext in project gravitee-access-management by gravitee-io.

the class EnrichAuthFlowPolicy method enrichAuthFlowContext.

private Single<AuthenticationFlowContext> enrichAuthFlowContext(ExecutionContext executionContext) {
    Map<String, Object> data = new HashMap<>();
    TemplateEngine tplEngine = executionContext.getTemplateEngine();
    for (Property property : configuration.getProperties()) {
        Object value = tplEngine.getValue(property.getValue(), String.class);
        data.put(property.getKey(), value);
    }
    final Instant now = Instant.now();
    final AuthenticationFlowContextRepository authContextRepository = executionContext.getComponent(AuthenticationFlowContextRepository.class);
    final Environment environment = executionContext.getComponent(Environment.class);
    final Integer expiration = environment.getProperty("authenticationFlow.expirationTimeOut", Integer.class, 300);
    AuthenticationFlowContext authContext = (AuthenticationFlowContext) executionContext.getAttribute(ConstantKeys.AUTH_FLOW_CONTEXT_KEY);
    authContext.setVersion(authContext.getVersion() + 1);
    if (authContext.getData() != null) {
        // data already present, do not remove them but override same entries
        authContext.getData().putAll(data);
    } else {
        authContext.setData(data);
    }
    authContext.setCreatedAt(new Date(now.toEpochMilli()));
    authContext.setExpireAt(new Date(now.plus(expiration, ChronoUnit.SECONDS).toEpochMilli()));
    return authContextRepository.create(authContext);
}
Also used : TemplateEngine(io.gravitee.el.TemplateEngine) AuthenticationFlowContextRepository(io.gravitee.am.repository.management.api.AuthenticationFlowContextRepository) HashMap(java.util.HashMap) AuthenticationFlowContext(io.gravitee.am.model.AuthenticationFlowContext) Instant(java.time.Instant) Environment(org.springframework.core.env.Environment) Property(io.gravitee.am.policy.enrich.auth.configuration.Property) Date(java.util.Date)

Aggregations

AuthenticationFlowContext (io.gravitee.am.model.AuthenticationFlowContext)15 Test (org.junit.Test)7 AbstractManagementTest (io.gravitee.am.repository.management.AbstractManagementTest)5 VertxHttpServerRequest (io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerRequest)2 HttpServerRequest (io.vertx.reactivex.core.http.HttpServerRequest)2 Instant (java.time.Instant)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 Environment (org.springframework.core.env.Environment)2 InvalidRequestException (io.gravitee.am.common.exception.oauth2.InvalidRequestException)1 CodeChallengeMethod (io.gravitee.am.common.oauth2.CodeChallengeMethod)1 GrantType (io.gravitee.am.common.oauth2.GrantType)1 Parameters (io.gravitee.am.common.oauth2.Parameters)1 ConstantKeys (io.gravitee.am.common.utils.ConstantKeys)1 RandomString (io.gravitee.am.common.utils.RandomString)1 UserAuthenticationManager (io.gravitee.am.gateway.handler.common.auth.user.UserAuthenticationManager)1 VertxHttpServerResponse (io.gravitee.am.gateway.handler.common.vertx.core.http.VertxHttpServerResponse)1 InvalidGrantException (io.gravitee.am.gateway.handler.oauth2.exception.InvalidGrantException)1 AuthorizationCodeService (io.gravitee.am.gateway.handler.oauth2.service.code.AuthorizationCodeService)1 AbstractTokenGranter (io.gravitee.am.gateway.handler.oauth2.service.granter.AbstractTokenGranter)1