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

The following examples show how to use io.vertx.reactivex.ext.web.RoutingContext#get() . 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: ErrorHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
private void handleException(RoutingContext routingContext, String errorCode, String errorDetail) {
    try {
        final HttpServerRequest request = routingContext.request();
        // prepare query parameters
        Map<String, String> parameters = new LinkedHashMap<>();
        // get client if exists
        Client client = routingContext.get(CLIENT_CONTEXT_KEY);
        if (client != null) {
            parameters.put(Parameters.CLIENT_ID, client.getClientId());
        } else if (request.getParam(Parameters.CLIENT_ID) != null) {
            parameters.put(Parameters.CLIENT_ID, (request.getParam(Parameters.CLIENT_ID)));
        }
        // append error information
        parameters.put("error", errorCode);
        if (errorDetail != null) {
            parameters.put("error_description", errorDetail);
        }
        // redirect
        String proxiedErrorPage = UriBuilderRequest.resolveProxyRequest(request,  errorPage, parameters, true);
        doRedirect(routingContext.response(), proxiedErrorPage);
    } catch (Exception e) {
        logger.error("Unable to handle root error response", e);
        doRedirect(routingContext.response(),  errorPage);
    }
}
 
Example 2
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * https://docs.kantarainitiative.org/uma/wg/rec-oauth-uma-federated-authz-2.0.html#reg-api
 * The spec state that if the resource can not be found, it must result in a 404.
 * By the way this may be better than a 403 to avoid confirming ids to a potential attacks.
 * @param context
 */
public void update(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String resource_id = context.request().getParam(RESOURCE_ID);

    this.extractRequest(context)
            .flatMap(request -> this.resourceService.update(request, domain.getId(), client.getId(), accessToken.getSub(), resource_id))
            .subscribe(
                    resource -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(ResourceResponse.from(resource)))
                    , error -> context.fail(error)
            );
}
 
Example 3
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void create(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String basePath = UriBuilderRequest.extractBasePath(context);

    this.extractRequest(context)
            .flatMap(request -> this.resourceService.create(request, domain.getId(), client.getId(), accessToken.getSub()))
            .subscribe(
                    resource -> {
                        final String resourceLocation = resourceLocation(basePath, resource);
                        context.response()
                                .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                                .putHeader(HttpHeaders.PRAGMA, "no-cache")
                                .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                                .putHeader(HttpHeaders.LOCATION, resourceLocation)
                                .setStatusCode(HttpStatusCode.CREATED_201)
                                .end(Json.encodePrettily(ResourceResponse.from(resource, resourceLocation)));
                    }
                    , error -> context.fail(error)
            );
}
 
Example 4
Source File: DynamicClientAccessTokenHandler.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final JWT token = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    if (token.hasScope(Scope.DCR_ADMIN.getKey())) {
        context.next();
        return;
    }

    // if not dcr admin, access token must match client registration token
    final String rawToken = context.get(OAuth2AuthHandler.RAW_TOKEN_CONTEXT_KEY);
    if (rawToken == null || !rawToken.equals(client.getRegistrationAccessToken())) {
        context.fail(new ClientRegistrationForbiddenException("Non matching registration_access_token"));
        return;
    }

    // registration token sub must match the client_id parameter
    final String clientIdPathParameter = context.request().getParam(Parameters.CLIENT_ID);
    if (!isRequestPathClientIdMatching(token, clientIdPathParameter)) {
        context.fail(new ClientRegistrationForbiddenException("Not allowed to access to : " + clientIdPathParameter));
        return;
    }

    context.next();
}
 
Example 5
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void delete(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    String resource_id = context.request().getParam(RESOURCE_ID);

    this.resourceService.delete(domain.getId(), client.getId(), accessToken.getSub(), resource_id)
            .subscribe(
                    () -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.NO_CONTENT_204)
                            .end()
                    , error -> context.fail(error)
            );
}
 
Example 6
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 7
Source File: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void get(RoutingContext context) {
    final JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    final String resource = context.request().getParam(RESOURCE_ID);
    final String accessPolicyId = context.request().getParam(POLICY_ID);

    resourceService.findAccessPolicy(domain.getId(), client.getId(), accessToken.getSub(), resource, accessPolicyId)
            .switchIfEmpty(Single.error(new AccessPolicyNotFoundException(accessPolicyId)))
            .subscribe(
                    response -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .end(Json.encodePrettily(response))
                    , error -> context.fail(error)
            );
}
 
Example 8
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    this.resourceService.listByDomainAndClientAndUser(domain.getId(), client.getId(), accessToken.getSub())
            .flatMapPublisher(Flowable::fromIterable)
            .map(Resource::getId)
            .collect(JsonArray::new, JsonArray::add)
            .subscribe(
                    buffer -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(buffer.isEmpty()?HttpStatusCode.NO_CONTENT_204:HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(buffer))
                    , error -> context.fail(error)
            );
}
 
Example 9
Source File: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void create(RoutingContext context) {
    final JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    final String resource = context.request().getParam(RESOURCE_ID);
    final String basePath = UriBuilderRequest.extractBasePath(context);

    // extract access policy payload
    AccessPolicy accessPolicy = extractRequest(context);

    // store the access policy
    resourceService.createAccessPolicy(accessPolicy, domain.getId(), client.getId(), accessToken.getSub(), resource)
            .subscribe(
                    p ->
                        context.response()
                                .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                                .putHeader(HttpHeaders.PRAGMA, "no-cache")
                                .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                                .putHeader(HttpHeaders.LOCATION, resourceLocation(basePath, p))
                                .setStatusCode(HttpStatusCode.CREATED_201)
                                .end(Json.encodePrettily(p))
                    , error -> context.fail(error)
            );
}
 
Example 10
Source File: ForgotPasswordEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final Client client = routingContext.get("client");
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(PARAM_CONTEXT_KEY, Collections.singletonMap(Parameters.CLIENT_ID, request.getParam(Parameters.CLIENT_ID)));

    // render the forgot password page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render forgot password page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 11
Source File: UserConsentFailureHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void handleException(RoutingContext context, String errorCode, String errorDescription) {
    try {
        Map<String, String> params = new LinkedHashMap<>();

        // retrieve client
        Client client = context.get(CLIENT_CONTEXT_KEY);
        if (client != null) {
            params.put(Parameters.CLIENT_ID, client.getClientId());
        }

        // add error messages
        params.put("error", "user_consent_failed");
        if (errorCode != null) {
            params.put("error_code", errorCode);
        }
        if (errorDescription != null) {
            params.put("error_description", errorDescription);
        }

        // go back to login page
        String uri = UriBuilderRequest.resolveProxyRequest(context.request(), "/" + domain.getPath() + "/login", params);
        doRedirect(context.response(), uri);
    } catch (Exception ex) {
        logger.error("An error occurs while redirecting to {}", context.request().absoluteURI(), ex);
        context.fail(503);
    }
}
 
Example 12
Source File: RequestObjectRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // Confidential clients or other clients issued client credentials MUST
    // authenticate with the authorization server when making requests to the request object registration endpoint.
    Client client = context.get(CLIENT_CONTEXT_KEY);
    if (client == null) {
        throw new InvalidClientException();
    }

    RequestObjectRegistrationRequest request = new RequestObjectRegistrationRequest();
    request.setRequest(context.getBodyAsString());
    request.setOrigin(extractOrigin(context.request()));

    requestObjectService.registerRequestObject(request, client)
            .subscribe(new Consumer<RequestObjectRegistrationResponse>() {
                @Override
                public void accept(RequestObjectRegistrationResponse response) throws Exception {
                    context.response()
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .end(Json.encodePrettily(response));
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    context.fail(throwable);
                }
            });
}
 
Example 13
Source File: ResetPasswordEndpoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final String error = request.getParam(ERROR_PARAM);
    final String success = request.getParam(SUCCESS_PARAM);
    final String warning = request.getParam(WARNING_PARAM);
    final String token = request.getParam(TOKEN_PARAM);
    // add query params to context
    routingContext.put(ERROR_PARAM, error);
    routingContext.put(SUCCESS_PARAM, success);
    routingContext.put(WARNING_PARAM, warning);
    routingContext.put(TOKEN_PARAM, token);

    // retrieve user who want to reset password
    User user = routingContext.get("user");
    routingContext.put("user", user);

    // retrieve client (if exists)
    Client client = routingContext.get("client");

    // render the reset password page
    engine.render(routingContext.data(), getTemplateFileName(client), res -> {
        if (res.succeeded()) {
            routingContext.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            routingContext.response().end(res.result());
        } else {
            logger.error("Unable to render reset password page", res.cause());
            routingContext.fail(res.cause());
        }
    });
}
 
Example 14
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 15
Source File: LoginCallbackOpenIDConnectFlowHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    final String providerId = context.request().getParam(PROVIDER_PARAMETER);
    final AuthenticationProvider authenticationProvider = context.get(PROVIDER_PARAMETER);

    // identity provider type is not OpenID Connect or the implicit flow is not used, continue
    if (!canHandle(authenticationProvider)) {
        context.next();
        return;
    }

    // if method is post, the OpenID Connect implicit flow response hash url must be present, add it to the execution context
    if (context.request().method().equals(HttpMethod.POST)) {
        final String hashValue = context.request().getParam(HASH_VALUE_PARAMETER);
        if (hashValue == null) {
            context.fail(new InternalAuthenticationServiceException("No URL hash value found"));
            return;
        }
        // decode hash value and put data in the execution context
        Map<String, String> hashValues = getParams(hashValue.substring(1)); // remove # symbol
        hashValues.forEach((k, v) -> context.put(k, v));
        context.next();
        return;
    }

    // implicit flow, we need to retrieve hash url from the browser to get access_token, id_token, ...
    engine.render(Collections.singletonMap("providerId", providerId), "login_callback", res -> {
        if (res.succeeded()) {
            context.response().putHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML);
            context.response().end(res.result());
        } else {
            logger.error("Unable to render login callback page", res.cause());
            context.fail(res.cause());
        }
    });
}
 
Example 16
Source File: ResetPasswordSubmissionEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // retrieve the client in context
    Client client = context.get("client");

    // retrieve the user in context
    User user = context.get("user");

    // set user password entered during reset password process
    String password = context.request().getParam(passwordParam);
    user.setPassword(password);

    // reset password
    resetPassword(client, user, getAuthenticatedUser(context), h -> {
        // prepare response
        Map<String, String> queryParams = new HashMap<>();
        // add client_id parameter for future use
        if (client != null) {
            queryParams.put(Parameters.CLIENT_ID, client.getClientId());
        }

        // if failure, return to the reset password page with an error
        if (h.failed()) {
            LOGGER.error("An error occurs while ending user reset password process", h.cause());
            queryParams.put("error", "reset_password_failed");
            redirectToPage(context, queryParams, h.cause());
            return;
        }
        // handle response
        ResetPasswordResponse resetPasswordResponse = h.result();
        // if auto login option is enabled add the user to the session
        if (resetPasswordResponse.isAutoLogin()) {
            context.setUser(io.vertx.reactivex.ext.auth.User.newInstance(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(resetPasswordResponse.getUser())));
        }
        // no redirect uri has been set, redirect to the default page
        if (resetPasswordResponse.getRedirectUri() == null || resetPasswordResponse.getRedirectUri().isEmpty()) {
            queryParams.put("success", "reset_password_completed");
            redirectToPage(context, queryParams);
            return;
        }
        // else, redirect to the custom redirect_uri
        context.response()
                .putHeader(HttpHeaders.LOCATION, resetPasswordResponse.getRedirectUri())
                .setStatusCode(302)
                .end();
    });
}
 
Example 17
Source File: RegisterConfirmationSubmissionEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // retrieve the client in context
    Client client = context.get("client");

    // retrieve the user in context
    User user = context.get("user");

    // set user password entered during confirmation registration process
    String password = context.request().getParam(passwordParam);
    user.setPassword(password);

    // confirm registration
    confirmRegistration(client, user, getAuthenticatedUser(context), h -> {
        // prepare response
        Map<String, String> queryParams = new HashMap<>();
        // add client_id parameter for future use
        if (client != null) {
            queryParams.put(Parameters.CLIENT_ID, client.getClientId());
        }

        // if failure, return to the registration confirmation page with an error
        if (h.failed()) {
            LOGGER.error("An error occurs while ending user registration", h.cause());
            queryParams.put("error", "registration_failed");
            redirectToPage(context, queryParams, h.cause());
            return;
        }
        // handle response
        RegistrationResponse registrationResponse = h.result();
        // if auto login option is enabled add the user to the session
        if (registrationResponse.isAutoLogin()) {
            context.setUser(io.vertx.reactivex.ext.auth.User.newInstance(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(registrationResponse.getUser())));
        }
        // no redirect uri has been set, redirect to the default page
        if (registrationResponse.getRedirectUri() == null || registrationResponse.getRedirectUri().isEmpty()) {
            queryParams.put("success", "registration_completed");
            redirectToPage(context, queryParams);
            return;
        }
        // else, redirect to the custom redirect_uri
        context.response()
                .putHeader(HttpHeaders.LOCATION, registrationResponse.getRedirectUri())
                .setStatusCode(302)
                .end();
    });
}
 
Example 18
Source File: RegisterSubmissionEndpoint.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    // retrieve the client in context
    Client client = context.get("client");

    // create the user
    MultiMap params = context.request().formAttributes();
    User user = convert(params);

    // register the user
    register(client, user, getAuthenticatedUser(context), h -> {
        // prepare response
        Map<String, String> queryParams = new HashMap<>();
        // add client_id parameter for future use
        if (client != null) {
            queryParams.put(Parameters.CLIENT_ID, client.getClientId());
        }

        // if failure, return to the register page with an error
        if (h.failed()) {
            if (h.cause() instanceof InvalidUserException) {
                queryParams.put(WARNING_PARAM, "invalid_user_information");
            } else if (h.cause() instanceof EmailFormatInvalidException) {
                queryParams.put(WARNING_PARAM, "invalid_email");
            } else {
                LOGGER.error("An error occurs while ending user registration", h.cause());
                queryParams.put(ERROR_PARAM, "registration_failed");
            }
            redirectToPage(context, queryParams, h.cause());
            return;
        }

        // handle response
        RegistrationResponse registrationResponse = h.result();
        // if auto login option is enabled add the user to the session
        if (registrationResponse.isAutoLogin()) {
            context.setUser(io.vertx.reactivex.ext.auth.User.newInstance(new io.gravitee.am.gateway.handler.common.vertx.web.auth.user.User(registrationResponse.getUser())));
        }
        // no redirect uri has been set, redirect to the default page
        if (registrationResponse.getRedirectUri() == null || registrationResponse.getRedirectUri().isEmpty()) {
            queryParams.put(SUCCESS_PARAM, "registration_succeed");
            redirectToPage(context, queryParams);
            return;
        }
        // else, redirect to the custom redirect_uri
        context.response()
                .putHeader(HttpHeaders.LOCATION, registrationResponse.getRedirectUri())
                .setStatusCode(302)
                .end();
    });
}
 
Example 19
Source File: UserConsentProcessHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    final HttpServerRequest request = routingContext.request();
    final Session session = routingContext.session();
    final Client client = routingContext.get(CLIENT_CONTEXT_KEY);
    final io.gravitee.am.model.User user = ((User) routingContext.user().getDelegate()).getUser();
    final Set<String> requestedConsent = session.get(REQUESTED_CONSENT_CONTEXT_KEY);
    final AuthorizationRequest authorizationRequest = session.get(OAuth2Constants.AUTHORIZATION_REQUEST);

    // get user consent
    MultiMap params = routingContext.request().formAttributes();
    Map<String, String> userConsent = params.entries().stream()
            .filter(entry -> entry.getKey().startsWith(SCOPE_PREFIX))
            .collect(Collectors.toMap(scopeEntry -> scopeEntry.getKey(), scopeEntry -> params.get(USER_OAUTH_APPROVAL)));

    // compute user consent that have been approved / denied
    Set<String> approvedConsent = new HashSet<>();
    List<ScopeApproval> approvals = new ArrayList<>();
    for (String requestedScope : requestedConsent) {
        String approvalParameter = requestedScope;
        String value = userConsent.get(SCOPE_PREFIX + approvalParameter);
        value = value == null ? "" : value.toLowerCase();
        if ("true".equals(value) || value.startsWith("approve")) {
            approvedConsent.add(requestedScope);
            approvals.add(new ScopeApproval(authorizationRequest.transactionId(), user.getId(), client.getClientId(), domain.getId(),
                    requestedScope, ScopeApproval.ApprovalStatus.APPROVED));
        }
        else {
            approvals.add(new ScopeApproval(authorizationRequest.transactionId(), user.getId(), client.getClientId(), domain.getId(),
                    requestedScope, ScopeApproval.ApprovalStatus.DENIED));
        }
    }

    // save consent
    saveConsent(request, user, client, approvals, h -> {
        if (h.failed()) {
            routingContext.fail(h.cause());
            return;
        }

        boolean approved = (approvedConsent.isEmpty() && !requestedConsent.isEmpty()) ? false : true;
        authorizationRequest.setApproved(approved);
        authorizationRequest.setScopes(approvedConsent);
        authorizationRequest.setConsents(h.result());
        session.put(USER_CONSENT_COMPLETED_CONTEXT_KEY, true);
        routingContext.next();
    });
}
 
Example 20
Source File: AuthorizationRequestFailureHandler.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void handle(RoutingContext routingContext) {
    if (routingContext.failed()) {
        try {
            AuthorizationRequest request = resolveInitialAuthorizeRequest(routingContext);
            Client client = routingContext.get(CLIENT_CONTEXT_KEY);
            String defaultErrorURL = UriBuilderRequest.resolveProxyRequest(routingContext.request(), defaultErrorPath, null);
            Throwable throwable = routingContext.failure();
            if (throwable instanceof OAuth2Exception) {
                OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable;
                // Manage exception
                processOAuth2Exception(request, oAuth2Exception, client, defaultErrorURL, h -> {
                    if (h.failed()) {
                        logger.error("An errors has occurred while handling authorization error response", h.cause());
                        routingContext.response().setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end();
                        return;
                    }
                    // redirect user to the error page with error code and description
                    doRedirect(routingContext.response(), h.result());
                });
            } else if (throwable instanceof HttpStatusException) {
                // in case of http status exception, go to the default error page
                request.setRedirectUri(defaultErrorURL);
                HttpStatusException httpStatusException = (HttpStatusException) throwable;
                doRedirect(routingContext.response(), buildRedirectUri(httpStatusException.getMessage(), httpStatusException.getPayload(), request));
            } else {
                logger.error("An exception has occurred while handling authorization request", throwable);
                if (routingContext.statusCode() != -1) {
                    routingContext
                            .response()
                            .setStatusCode(routingContext.statusCode())
                            .end();
                } else {
                    routingContext
                            .response()
                            .setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
                            .end();
                }
            }
        } catch (Exception e) {
            logger.error("Unable to handle authorization error response", e);
            doRedirect(routingContext.response(), defaultErrorPath);
        } finally {
            // clean session
            cleanSession(routingContext);
        }
    }
}