Search in sources :

Example 1 with OAuth2Exception

use of io.gravitee.am.common.exception.oauth2.OAuth2Exception in project dataverse by IQSS.

the class OIDCAuthProvider method getAccessToken.

/**
 * Retrieve the Access Token from provider. Encapsulate for testing.
 * @param grant
 * @return The bearer access token used in code (grant) flow. May be empty if SDK could not cast internally.
 */
Optional<BearerAccessToken> getAccessToken(AuthorizationGrant grant) throws IOException, OAuth2Exception {
    // Request token
    HTTPResponse response = new TokenRequest(this.idpMetadata.getTokenEndpointURI(), this.clientAuth, grant, Scope.parse(this.scope)).toHTTPRequest().send();
    // Parse response
    try {
        TokenResponse tokenRespone = OIDCTokenResponseParser.parse(response);
        // If error --> oauth2 ex
        if (!tokenRespone.indicatesSuccess()) {
            ErrorObject error = tokenRespone.toErrorResponse().getErrorObject();
            throw new OAuth2Exception(error.getHTTPStatusCode(), error.getDescription(), "auth.providers.token.failRetrieveToken");
        }
        // Success --> return token
        OIDCTokenResponse successResponse = (OIDCTokenResponse) tokenRespone.toSuccessResponse();
        return Optional.of(successResponse.getOIDCTokens().getBearerAccessToken());
    } catch (ParseException ex) {
        throw new OAuth2Exception(-1, ex.getMessage(), "auth.providers.token.failParseToken");
    }
}
Also used : OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ParseException(com.nimbusds.oauth2.sdk.ParseException) OAuth2Exception(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2Exception)

Example 2 with OAuth2Exception

use of io.gravitee.am.common.exception.oauth2.OAuth2Exception in project dataverse by IQSS.

the class OIDCAuthProvider method getUserRecord.

/**
 * Receive user data from OIDC provider after authn/z has been successfull. (Callback view uses this)
 * Request a token and access the resource, parse output and return user details.
 * @param code The authz code sent from the provider
 * @param redirectUrl The redirect URL (some providers require this when fetching the access token, e. g. Google)
 * @return A user record containing all user details accessible for us
 * @throws IOException Thrown when communication with the provider fails
 * @throws OAuth2Exception Thrown when we cannot access the user details for some reason
 * @throws InterruptedException Thrown when the requests thread is failing
 * @throws ExecutionException Thrown when the requests thread is failing
 */
@Override
public OAuth2UserRecord getUserRecord(String code, String redirectUrl) throws IOException, OAuth2Exception, InterruptedException, ExecutionException {
    // Create grant object
    AuthorizationGrant codeGrant = new AuthorizationCodeGrant(new AuthorizationCode(code), URI.create(redirectUrl));
    // Get Access Token first
    Optional<BearerAccessToken> accessToken = getAccessToken(codeGrant);
    // Now retrieve User Info
    if (accessToken.isPresent()) {
        Optional<UserInfo> userInfo = getUserInfo(accessToken.get());
        // Construct our internal user representation
        if (userInfo.isPresent()) {
            return getUserRecord(userInfo.get());
        }
    }
    // this should never happen, as we are throwing exceptions like champs before.
    throw new OAuth2Exception(-1, "", "auth.providers.token.failGetUser");
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) UserInfo(com.nimbusds.openid.connect.sdk.claims.UserInfo) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) OAuth2Exception(edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2Exception)

Example 3 with OAuth2Exception

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

the class ErrorHandler method handle.

@Override
public void handle(RoutingContext routingContext) {
    if (routingContext.failed()) {
        Throwable throwable = routingContext.failure();
        // management exception (resource not found, server error, ...)
        if (throwable instanceof AbstractManagementException) {
            AbstractManagementException technicalManagementException = (AbstractManagementException) throwable;
            handleException(routingContext, technicalManagementException.getHttpStatusCode(), technicalManagementException.getMessage());
        // oauth2 exception (token invalid exception)
        } else if (throwable instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable;
            handleException(routingContext, oAuth2Exception.getHttpStatusCode(), oAuth2Exception.getMessage());
        } else if (throwable instanceof PolicyChainException) {
            PolicyChainException policyChainException = (PolicyChainException) throwable;
            handleException(routingContext, policyChainException.statusCode(), policyChainException.key() + " : " + policyChainException.getMessage());
        } else if (throwable instanceof HttpException) {
            HttpException httpStatusException = (HttpException) throwable;
            handleException(routingContext, httpStatusException.getStatusCode(), httpStatusException.getPayload());
        } else {
            logger.error(throwable.getMessage(), throwable);
            if (routingContext.statusCode() != -1) {
                routingContext.response().setStatusCode(routingContext.statusCode()).end();
            } else {
                routingContext.response().setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end();
            }
        }
    }
}
Also used : AbstractManagementException(io.gravitee.am.service.exception.AbstractManagementException) HttpException(io.vertx.ext.web.handler.HttpException) PolicyChainException(io.gravitee.am.gateway.policy.PolicyChainException) OAuth2Exception(io.gravitee.am.common.exception.oauth2.OAuth2Exception)

Example 4 with OAuth2Exception

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

the class ErrorHandler method handle.

@Override
public void handle(RoutingContext routingContext) {
    if (routingContext.failed()) {
        Throwable throwable = routingContext.failure();
        // management exception (resource not found, server error, ...)
        if (throwable instanceof AbstractManagementException) {
            AbstractManagementException technicalManagementException = (AbstractManagementException) throwable;
            handleException(routingContext, "technical_error", technicalManagementException.getMessage());
        // oauth2 exception (token invalid exception)
        } else if (throwable instanceof OAuth2Exception) {
            OAuth2Exception oAuth2Exception = (OAuth2Exception) throwable;
            handleException(routingContext, oAuth2Exception.getOAuth2ErrorCode(), oAuth2Exception.getMessage());
        } else if (throwable instanceof PolicyChainException) {
            PolicyChainException policyChainException = (PolicyChainException) throwable;
            handleException(routingContext, policyChainException.key(), policyChainException.getMessage());
        } else if (throwable instanceof HttpException) {
            HttpException httpStatusException = (HttpException) throwable;
            handleException(routingContext, httpStatusException.getMessage(), httpStatusException.getPayload());
        } else {
            logger.error("An exception occurs while handling incoming request", throwable);
            if (routingContext.statusCode() != -1) {
                routingContext.response().setStatusCode(routingContext.statusCode()).end();
            } else {
                routingContext.response().setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end();
            }
        }
    }
}
Also used : AbstractManagementException(io.gravitee.am.service.exception.AbstractManagementException) HttpException(io.vertx.ext.web.handler.HttpException) PolicyChainException(io.gravitee.am.gateway.policy.PolicyChainException) OAuth2Exception(io.gravitee.am.common.exception.oauth2.OAuth2Exception)

Example 5 with OAuth2Exception

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

the class ApplicationServiceImpl method create.

@Override
public Single<Application> create(String domain, NewApplication newApplication, User principal) {
    LOGGER.debug("Create a new application {} for domain {}", newApplication, domain);
    Application application = new Application();
    application.setId(RandomString.generate());
    application.setName(newApplication.getName());
    application.setType(newApplication.getType());
    application.setDomain(domain);
    application.setMetadata(newApplication.getMetadata());
    // apply default oauth 2.0 settings
    ApplicationSettings applicationSettings = new ApplicationSettings();
    ApplicationOAuthSettings oAuthSettings = new ApplicationOAuthSettings();
    oAuthSettings.setClientId(newApplication.getClientId());
    oAuthSettings.setClientSecret(newApplication.getClientSecret());
    oAuthSettings.setTokenEndpointAuthMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
    oAuthSettings.setRedirectUris(newApplication.getRedirectUris());
    applicationSettings.setOauth(oAuthSettings);
    application.setSettings(applicationSettings);
    // apply templating
    applicationTemplateManager.apply(application);
    return create0(domain, application, principal).onErrorResumeNext(ex -> {
        if (ex instanceof AbstractManagementException || ex instanceof OAuth2Exception) {
            return Single.error(ex);
        }
        LOGGER.error("An error occurs while trying to create an application", ex);
        return Single.error(new TechnicalManagementException("An error occurs while trying to create an application", ex));
    });
}
Also used : ApplicationOAuthSettings(io.gravitee.am.model.application.ApplicationOAuthSettings) ApplicationSettings(io.gravitee.am.model.application.ApplicationSettings) PatchApplication(io.gravitee.am.service.model.PatchApplication) NewApplication(io.gravitee.am.service.model.NewApplication) Application(io.gravitee.am.model.Application) TopApplication(io.gravitee.am.service.model.TopApplication) OAuth2Exception(io.gravitee.am.common.exception.oauth2.OAuth2Exception)

Aggregations

OAuth2Exception (io.gravitee.am.common.exception.oauth2.OAuth2Exception)11 PolicyChainException (io.gravitee.am.gateway.policy.PolicyChainException)6 HttpException (io.vertx.ext.web.handler.HttpException)6 OAuth2ErrorResponse (io.gravitee.am.gateway.handler.oauth2.service.response.OAuth2ErrorResponse)4 OAuth2Exception (edu.harvard.iq.dataverse.authorization.providers.oauth2.OAuth2Exception)3 InvalidRequestObjectException (io.gravitee.am.common.exception.oauth2.InvalidRequestObjectException)3 Client (io.gravitee.am.model.oidc.Client)3 AbstractManagementException (io.gravitee.am.service.exception.AbstractManagementException)3 JWTOAuth2Exception (io.gravitee.am.gateway.handler.oauth2.exception.JWTOAuth2Exception)2 RedirectMismatchException (io.gravitee.am.gateway.handler.oauth2.exception.RedirectMismatchException)2 AuthorizationRequest (io.gravitee.am.gateway.handler.oauth2.service.request.AuthorizationRequest)2 URISyntaxException (java.net.URISyntaxException)2 OAuth2AccessToken (com.github.scribejava.core.model.OAuth2AccessToken)1 OAuthRequest (com.github.scribejava.core.model.OAuthRequest)1 Response (com.github.scribejava.core.model.Response)1 OAuth20Service (com.github.scribejava.core.oauth.OAuth20Service)1 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)1 AuthorizationCodeGrant (com.nimbusds.oauth2.sdk.AuthorizationCodeGrant)1 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)1