Java Code Examples for io.vertx.reactivex.ext.web.RoutingContext#user()

The following examples show how to use io.vertx.reactivex.ext.web.RoutingContext#user() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogoutEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void invalidateSession(RoutingContext routingContext, Handler<AsyncResult<User>> handler) {
    io.gravitee.am.model.User endUser = null;
    // clear context and session
    if (routingContext.user() != null) {
        endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser();
        // audit event
        report(endUser, routingContext.request());
        // clear user
        routingContext.clearUser();
    }

    if (routingContext.session() != null) {
        routingContext.session().destroy();
    }

    handler.handle(Future.succeededFuture(endUser));
}
 
Example 2
Source File: SSOSessionHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // if no user in context, continue
    if (context.user() == null) {
        context.next();
        return;
    }

    authorizeUser(context, h -> {
        if (h.failed()) {
            Throwable cause = h.cause();
            LOGGER.debug("An error occurs while checking SSO Session upon the current user : {}", context.user().principal(), cause);
            if (cause instanceof AccountDisabledException) {
                // user has been disabled, invalidate session
                context.clearUser();
                context.session().destroy();
            } else if (cause instanceof InvalidRequestException) {
                context.fail(new HttpStatusException(403, "Invalid request for the current SSO context"));
                return;
            }
        }
        context.next();
    });

}
 
Example 3
Source File: SSOSessionHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void authorizeUser(RoutingContext context, Handler<AsyncResult<Void>> handler) {
    // retrieve end user and check if it's authorized to call the subsequence handlers
    User authenticatedUser = context.user();
    io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) authenticatedUser.getDelegate()).getUser();

    // check account status
    checkAccountStatus(endUser, accountHandler -> {
        if (accountHandler.failed()) {
            handler.handle(Future.failedFuture(accountHandler.cause()));
            return;
        }
        // additional check
        checkClient(context, endUser, clientHandler -> {
            if (clientHandler.failed()) {
                handler.handle(Future.failedFuture(clientHandler.cause()));
                return;
            }
            // continue
            handler.handle(Future.succeededFuture());
        });
    });
}
 
Example 4
Source File: AuthorizationRequestResolveHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    // get client
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);

    // get user
    final io.gravitee.am.model.User endUser = routingContext.user() != null ?
            ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) routingContext.user().getDelegate()).getUser() : null;

    // create authorization request
    final AuthorizationRequest authorizationRequest = resolveInitialAuthorizeRequest(routingContext);

    // compute authorization request
    computeAuthorizationRequest(authorizationRequest, client, endUser, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }
        // prepare context for the next handlers
        routingContext.session().put(OAuth2Constants.AUTHORIZATION_REQUEST, authorizationRequest);
        // continue
        routingContext.next();
    });
}
 
Example 5
Source File: AuthorizationRequestParseParametersHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
void parsePromptParameter(RoutingContext context) {
    String prompt = context.request().getParam(Parameters.PROMPT);

    if (prompt != null) {
        // retrieve prompt values (prompt parameter is a space delimited, case sensitive list of ASCII string values)
        // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
        List<String> promptValues = Arrays.asList(prompt.split("\\s+"));

        // The Authorization Server MUST NOT display any authentication or consent user interface pages.
        // An error is returned if an End-User is not already authenticated.
        if (promptValues.contains("none") && context.user() == null) {
            throw new LoginRequiredException("Login required");
        }

        // The Authentication Request contains the prompt parameter with the value login.
        // In this case, the Authorization Server MUST reauthenticate the End-User even if the End-User is already authenticated.
        if (promptValues.contains("login") && context.user() != null) {
            if (!returnFromLoginPage(context)) {
                context.clearUser();
            }
        }
    }
}
 
Example 6
Source File: FormLoginStep.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(RoutingContext routingContext, AuthenticationFlowChain flow) {
    if (routingContext.user() == null) {
        flow.exit(this);
    } else {
        flow.doNext(routingContext);
    }
}
 
Example 7
Source File: AbstractAuthorizationRequestParametersHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
protected void parseMaxAgeParameter(RoutingContext context) {
    // if user is already authenticated and if the last login date is greater than the max age parameter,
    // the OP MUST attempt to actively re-authenticate the End-User.
    User authenticatedUser = context.user();
    if (authenticatedUser == null || !(authenticatedUser.getDelegate() instanceof io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User)) {
        // user not authenticated, continue
        return;
    }

    String maxAge = context.request().getParam(Parameters.MAX_AGE);
    if (maxAge == null || !maxAge.matches("-?\\d+")) {
        // none or invalid max age, continue
        return;
    }

    io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) authenticatedUser.getDelegate()).getUser();
    Date loggedAt = endUser.getLoggedAt();
    if (loggedAt == null) {
        // user has no last login date, continue
        return;
    }

    // check the elapsed user session duration
    long elapsedLoginTime = (System.currentTimeMillis() - loggedAt.getTime()) / 1000L;
    Long maxAgeValue = Long.valueOf(maxAge);
    if (maxAgeValue < elapsedLoginTime) {
        // check if the user doesn't come from the login page
        if (!returnFromLoginPage(context)) {
            // should we logout the user or just force it to go to the login page ?
            context.clearUser();

            // check prompt parameter in case the user set 'none' option
            parsePromptParameter(context);
        }
    }
}
 
Example 8
Source File: AuthorizationEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // The authorization server authenticates the resource owner and obtains
    // an authorization decision (by asking the resource owner or by establishing approval via other means).
    User authenticatedUser = context.user();
    if (authenticatedUser == null || ! (authenticatedUser.getDelegate() instanceof io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User)) {
        throw new AccessDeniedException();
    }

    // get authorization request
    AuthorizationRequest request = context.session().get(OAuth2Constants.AUTHORIZATION_REQUEST);

    // get client
    Client client = context.get(CLIENT_CONTEXT_KEY);

    // get resource owner
    io.gravitee.am.model.User endUser = ((io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User) authenticatedUser.getDelegate()).getUser();

    flow.run(request, client, endUser)
            .subscribe(
                    authorizationResponse -> {
                        try {
                            // final step of the authorization flow, we can clean the session and redirect the user
                            cleanSession(context);
                            doRedirect(context.response(), authorizationResponse.buildRedirectUri());
                        } catch (Exception e) {
                            logger.error("Unable to redirect to client redirect_uri", e);
                            context.fail(new ServerErrorException());
                        }
                    },
                    error -> context.fail(error));

}
 
Example 9
Source File: AuthorizingAnnotationHandler.java    From redpipe with Apache License 2.0 4 votes vote down vote up
protected User getUser() {
	RoutingContext ctx = ResteasyProviderFactory.getContextData(RoutingContext.class);
	return ctx.user();
}
 
Example 10
Source File: AuthorizationRequestEndUserConsentHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final Session session = routingContext.session();
    final HttpServerRequest request = routingContext.request();
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
    final io.gravitee.am.model.User user = routingContext.user() != null ? ((User) routingContext.user().getDelegate()).getUser() : null;
    final AuthorizationRequest authorizationRequest = session.get(OAuth2Constants.AUTHORIZATION_REQUEST);
    final Set<String> requestedConsent = authorizationRequest.getScopes();
    // no consent to check, continue
    if (requestedConsent == null || requestedConsent.isEmpty()) {
        routingContext.next();
        return;
    }
    // check if user is already set its consent
    if (session.get(USER_CONSENT_COMPLETED_CONTEXT_KEY) != null && session.get(USER_CONSENT_COMPLETED_CONTEXT_KEY).equals(true)) {
        if (authorizationRequest.isApproved()) {
            routingContext.next();
            return;
        }
        // if prompt=none and the Client does not have pre-configured consent for the requested Claims, throw interaction_required exception
        // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
        String prompt = request.params().get(Parameters.PROMPT);
        if (prompt != null && Arrays.asList(prompt.split("\\s+")).contains("none")) {
            routingContext.fail(new InteractionRequiredException("Interaction required"));
        } else {
            routingContext.fail(new AccessDeniedException("User denied access"));
        }
        return;
    }
    // application has forced to prompt consent screen to the user
    // go to the user consent page
    if (request.params().contains(Parameters.PROMPT)
            && request.params().get(Parameters.PROMPT).contains("consent")) {
        session.put(REQUESTED_CONSENT_CONTEXT_KEY, requestedConsent);
        redirectToConsentPage(request);
        return;
    }
    // check if application has enabled skip consent option
    if (skipConsent(requestedConsent, client)) {
        authorizationRequest.setApproved(true);
        routingContext.next();
        return;
    }
    // check user consent
    checkUserConsent(client, user, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }
        Set<String> approvedConsent = h.result();
        // user approved consent, continue
        if (approvedConsent.containsAll(requestedConsent)) {
            authorizationRequest.setApproved(true);
            routingContext.next();
            return;
        }
        // else go to the user consent page
        Set<String> requiredConsent = requestedConsent.stream().filter(requestedScope -> !approvedConsent.contains(requestedScope)).collect(Collectors.toSet());
        session.put(REQUESTED_CONSENT_CONTEXT_KEY, requiredConsent);
        redirectToConsentPage(request);
    });
}