Search in sources :

Example 6 with ServiceAuthorizationException

use of com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException in project AuthGuard by AuthGuard.

the class OAuthService method exchangeAuthorizationCode.

/**
 * Exchanges an authorization code with OAuth tokens. It'll verify that
 * a session containing that state exists before performing the exchange.
 * If the state has expired or no record of it existed then the future
 * will complete with {@link ServiceAuthorizationException}.
 *
 * @param provider The name of a provider as stated in the configuration.
 * @param state The state the identity provider returned.
 * @param authorizationCode The authorization code generated by the identity provider.
 */
public CompletableFuture<TokensResponse> exchangeAuthorizationCode(final String provider, final String state, final String authorizationCode) {
    final OAuthServiceClient client = Optional.ofNullable(providersClients.get(provider)).orElseThrow(() -> new ServiceException(ErrorCode.GENERIC_AUTH_FAILURE, "Invalid identity provider"));
    return CompletableFuture.supplyAsync(() -> sessionsService.getByToken(state)).thenCompose(sessionOptional -> sessionOptional.map(session -> doExchange(client, authorizationCode, session)).orElseThrow(() -> new ServiceAuthorizationException(ErrorCode.TOKEN_EXPIRED_OR_DOES_NOT_EXIST, "The provided state is either invalid or has expired"))).thenApply(tokensResponse -> {
        if (client.getConfiguration().isAccountProvider()) {
            if (tokensResponse.getIdToken() == null) {
                LOG.warn("Provider {} was set as an account provider but no ID was found in the response", provider);
            } else {
                final AccountBO account = getOrCreateAccount(client, authorizationCode, tokensResponse.getIdToken());
                tokensResponse.setAccountId(account.getId());
            }
        }
        return tokensResponse;
    });
}
Also used : JWT(com.auth0.jwt.JWT) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) RequestContextBO(com.nexblocks.authguard.service.model.RequestContextBO) ImmutableOAuthConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthConfiguration) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) CompletableFuture(java.util.concurrent.CompletableFuture) SessionBO(com.nexblocks.authguard.service.model.SessionBO) AccountsService(com.nexblocks.authguard.service.AccountsService) Duration(java.time.Duration) Map(java.util.Map) ResponseType(com.nexblocks.authguard.jwt.oauth.ResponseType) Claim(com.auth0.jwt.interfaces.Claim) SessionsService(com.nexblocks.authguard.service.SessionsService) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) Logger(org.slf4j.Logger) AccountBO(com.nexblocks.authguard.service.model.AccountBO) ImmutableOAuthClientConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthClientConfiguration) TokensResponse(com.nexblocks.authguard.jwt.oauth.TokensResponse) AccountEmailBO(com.nexblocks.authguard.service.model.AccountEmailBO) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Try(io.vavr.control.Try) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) OAuthServiceClient(com.nexblocks.authguard.jwt.oauth.OAuthServiceClient) Optional(java.util.Optional) ConfigContext(com.nexblocks.authguard.config.ConfigContext) Named(com.google.inject.name.Named) AccountBO(com.nexblocks.authguard.service.model.AccountBO) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) OAuthServiceClient(com.nexblocks.authguard.jwt.oauth.OAuthServiceClient) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)

Example 7 with ServiceAuthorizationException

use of com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException in project AuthGuard by AuthGuard.

the class ExceptionHandlers method completionException.

// NOTE: this will go away when we move to async services
public static void completionException(final CompletionException e, final Context context) {
    final Throwable cause = e.getCause();
    if (cause == null) {
        LOG.error("A CompletionException was thrown without a cause", e);
        context.status(500).json(new Error("UNKNOWN", "An unknown error occurred"));
    } else if (cause instanceof ServiceAuthorizationException) {
        serviceAuthorizationException((ServiceAuthorizationException) cause, context);
    } else if (cause instanceof ServiceConflictException) {
        serviceConflictException((ServiceConflictException) cause, context);
    } else if (cause instanceof ServiceException) {
        serviceException((ServiceException) cause, context);
    } else if (cause instanceof RuntimeJsonException) {
        jsonMappingException((RuntimeJsonException) cause, context);
    } else if (cause instanceof RequestValidationException) {
        requestValidationException((RequestValidationException) cause, context);
    } else if (cause instanceof IdempotencyException) {
        idempotencyException((IdempotencyException) cause, context);
    } else if (cause instanceof TimeoutException) {
        timeoutException((TimeoutException) cause, context);
    } else {
        LOG.error("An unexpected exception was thrown", cause);
        context.status(500).json(new Error("UNKNOWN", "An unknown error occurred"));
    }
}
Also used : ServiceConflictException(com.nexblocks.authguard.service.exceptions.ServiceConflictException) ServiceException(com.nexblocks.authguard.service.exceptions.ServiceException) IdempotencyException(com.nexblocks.authguard.service.exceptions.IdempotencyException) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) Error(com.nexblocks.authguard.api.dto.entities.Error) RequestValidationError(com.nexblocks.authguard.api.dto.entities.RequestValidationError) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with ServiceAuthorizationException

use of com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException in project AuthGuard by AuthGuard.

the class ExchangeServiceImpl method exchangeFailure.

private void exchangeFailure(final AuthRequestBO authRequest, final RequestContextBO requestContext, final Exception e, final String fromTokenType, final String toTokenType) {
    if (ServiceAuthorizationException.class.isAssignableFrom(e.getClass())) {
        final ServiceAuthorizationException sae = (ServiceAuthorizationException) e;
        final AuthMessage authMessage = AuthMessage.failure(fromTokenType, toTokenType, sae.getEntityType(), sae.getEntityId(), sae);
        if (sae.getEntityType() == EntityType.ACCOUNT) {
            final ExchangeAttemptBO attempt = createBaseAttempt(authRequest, requestContext).exchangeFrom(fromTokenType).exchangeTo(toTokenType).successful(false).entityId(sae.getEntityId()).build();
            exchangeAttemptsService.create(attempt);
        }
        emb.publish(CHANNEL, Messages.auth(authMessage));
    } else {
        final AuthMessage authMessage = AuthMessage.failure(fromTokenType, toTokenType, e);
        emb.publish(CHANNEL, Messages.auth(authMessage));
    }
}
Also used : ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) AuthMessage(com.nexblocks.authguard.service.messaging.AuthMessage)

Example 9 with ServiceAuthorizationException

use of com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException in project AuthGuard by AuthGuard.

the class SessionTokenToSession method exchange.

@Override
public Either<Exception, AuthResponseBO> exchange(final AuthRequestBO request) {
    final Optional<SessionBO> sessionOpt = sessionsService.getByToken(request.getToken());
    if (sessionOpt.isEmpty()) {
        return Either.left(new ServiceAuthorizationException(ErrorCode.INVALID_TOKEN, "Session token does not exist"));
    }
    final SessionBO session = sessionOpt.get();
    if (session.getExpiresAt().isBefore(OffsetDateTime.now())) {
        return Either.left(new ServiceAuthorizationException(ErrorCode.EXPIRED_TOKEN, "Session token has expired"));
    }
    return Either.right(AuthResponseBO.builder().type(TOKEN_TYPE).token(session).entityType(EntityType.ACCOUNT).entityId(session.getAccountId()).build());
}
Also used : ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) SessionBO(com.nexblocks.authguard.service.model.SessionBO)

Example 10 with ServiceAuthorizationException

use of com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException in project AuthGuard by AuthGuard.

the class OAuthServiceClient method processFormDataResponse.

private void processFormDataResponse(final HttpResponse<Buffer> httpResponse, final String url, final CompletableFuture<TokensResponse> future) {
    final String formBody = httpResponse.bodyAsString();
    final Map<String, String> formData = Arrays.stream(formBody.split("&")).map(field -> field.split("=")).collect(Collectors.toMap(field -> field[0], field -> field[1]));
    final String error = formData.get("error");
    if (error != null) {
        LOG.warn("Call to {} returned an error {}", url, error);
        future.completeExceptionally(new ServiceAuthorizationException(ErrorCode.GENERIC_AUTH_FAILURE, "Unsuccessful call to the identity provider"));
    }
    final TokensResponse tokens = new TokensResponse().setAccessToken(formData.get("access_token")).setIdToken(formData.get("id_token")).setRefreshToken(formData.get("refresh_token"));
    future.complete(tokens);
}
Also used : ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) Arrays(java.util.Arrays) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) CryptographicRandom(com.nexblocks.authguard.service.random.CryptographicRandom) HttpResponse(io.vertx.ext.web.client.HttpResponse) Logger(org.slf4j.Logger) WebClient(io.vertx.ext.web.client.WebClient) MultiMap(io.vertx.core.MultiMap) LoggerFactory(org.slf4j.LoggerFactory) ImmutableOAuthClientConfiguration(com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthClientConfiguration) CompletableFuture(java.util.concurrent.CompletableFuture) Collectors(java.util.stream.Collectors) Buffer(io.vertx.core.buffer.Buffer) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) HttpUrl(okhttp3.HttpUrl) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)

Aggregations

ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)13 ErrorCode (com.nexblocks.authguard.service.exceptions.codes.ErrorCode)4 Inject (com.google.inject.Inject)3 ServiceException (com.nexblocks.authguard.service.exceptions.ServiceException)3 OffsetDateTime (java.time.OffsetDateTime)3 Optional (java.util.Optional)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 Logger (org.slf4j.Logger)3 LoggerFactory (org.slf4j.LoggerFactory)3 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)2 ImmutableOAuthClientConfiguration (com.nexblocks.authguard.jwt.oauth.config.ImmutableOAuthClientConfiguration)2 AccountsService (com.nexblocks.authguard.service.AccountsService)2 SessionBO (com.nexblocks.authguard.service.model.SessionBO)2 JsonObject (io.vertx.core.json.JsonObject)2 Map (java.util.Map)2 Collectors (java.util.stream.Collectors)2 JWT (com.auth0.jwt.JWT)1 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)1 Claim (com.auth0.jwt.interfaces.Claim)1 Maps (com.google.common.collect.Maps)1