Search in sources :

Example 1 with ServiceAuthorizationException

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

the class UnboundLdapService method authenticate.

@Override
public AccountBO authenticate(final String username, final String password) {
    // search
    final SearchResult searchResult;
    final Map<String, String[]> attributes;
    try {
        searchResult = ldapSearch.findUser(username);
        attributes = ldapAccountMapper.getAttributes(searchResult);
    } catch (final LDAPException e) {
        LOG.error("Failed to establish a connection the LDAP server or perform a search", e);
        throw new ServiceAuthorizationException(ErrorCode.LDAP_ERROR, "Could not perform an LDAP search");
    }
    if (attributes.isEmpty()) {
        throw new ServiceAuthorizationException(ErrorCode.IDENTIFIER_DOES_NOT_EXIST, "Username not found");
    }
    // bind
    try {
        ldapBind.bind(searchResult.getSearchEntries().get(0).getDN(), password);
    } catch (final LDAPBindException e) {
        throw new ServiceAuthorizationException(ErrorCode.GENERIC_AUTH_FAILURE, "Failed to authenticate user");
    } catch (final LDAPException e) {
        LOG.error("Failed to establish a connection the LDAP server or perform a bind", e);
        throw new ServiceAuthorizationException(ErrorCode.LDAP_ERROR, "Could not perform an LDAP search");
    }
    return ldapAccountMapper.mapAttributes(attributes, config.getFieldMapping()).build();
}
Also used : LDAPException(com.unboundid.ldap.sdk.LDAPException) LDAPBindException(com.unboundid.ldap.sdk.LDAPBindException) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) SearchResult(com.unboundid.ldap.sdk.SearchResult)

Example 2 with ServiceAuthorizationException

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

the class OAuthServiceClient method authorize.

/**
 * Sends a request to exchange the authorization code with ID, access,
 * and refresh tokens.
 */
public CompletableFuture<TokensResponse> authorize(final String code) {
    final MultiMap form = MultiMap.caseInsensitiveMultiMap().set("code", code).set("client_id", clientConfiguration.getClientId()).set("client_secret", clientConfiguration.getClientSecret()).set("redirect_uri", clientConfiguration.getTokenRedirectUrl()).set("grant_type", GrantType.AUTHORIZATION_CODE.type());
    final String url = clientConfiguration.getTokenUrl();
    final CompletableFuture<TokensResponse> future = new CompletableFuture<>();
    final String path = tokenUrl.encodedPath();
    webClient.post(tokenUrl.port(), tokenUrl.host(), path).timeout(5000).ssl(tokenUrl.isHttps()).putHeader("Accept", "application/json").sendForm(form, response -> {
        if (response.succeeded()) {
            final HttpResponse<Buffer> httpResponse = response.result();
            final String body = httpResponse.bodyAsString();
            LOG.info("Body {}", body);
            if (httpResponse.statusCode() == 200) {
                processResponse(httpResponse, url, future);
            } else {
                LOG.warn("Call to {} returned status code {}", url, httpResponse.statusCode());
                future.completeExceptionally(new ServiceAuthorizationException(ErrorCode.GENERIC_AUTH_FAILURE, "Unsuccessful call to the identity provider"));
            }
        } else {
            LOG.error("Call to {} failed", url, response.cause());
            future.completeExceptionally(new ServiceAuthorizationException(ErrorCode.GENERIC_AUTH_FAILURE, "Unexpected identity provider connection error"));
        }
    });
    return future;
}
Also used : Buffer(io.vertx.core.buffer.Buffer) MultiMap(io.vertx.core.MultiMap) CompletableFuture(java.util.concurrent.CompletableFuture) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)

Example 3 with ServiceAuthorizationException

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

the class OtpVerifier method verifyAccountToken.

@Override
public Either<Exception, String> verifyAccountToken(final String token) {
    // TODO: no need to have a special format for the token, just receive the two parts in the request
    final String[] parts = token.split(":");
    if (parts.length != 2) {
        return Either.left(new ServiceAuthorizationException(ErrorCode.INVALID_AUTHORIZATION_FORMAT, "Invalid OTP token format"));
    }
    final String passwordId = parts[0];
    final String otp = parts[1];
    final Optional<OneTimePasswordBO> generatedOpt = otpRepository.getById(passwordId).thenApply(optional -> optional.map(serviceMapper::toBO)).join();
    if (generatedOpt.isPresent()) {
        final OneTimePasswordBO generated = generatedOpt.get();
        if (generated.getExpiresAt().isBefore(OffsetDateTime.now())) {
            return Either.left(new ServiceAuthorizationException(ErrorCode.EXPIRED_TOKEN, "OTP " + passwordId + " has expired", EntityType.ACCOUNT, generated.getAccountId()));
        }
        if (generated.getPassword().equals(otp)) {
            return Either.right(generated.getAccountId());
        } else {
            return Either.left(new ServiceAuthorizationException(ErrorCode.PASSWORDS_DO_NOT_MATCH, "OTP " + passwordId + " values did not match", EntityType.ACCOUNT, generated.getAccountId()));
        }
    } else {
        return Either.left(new ServiceAuthorizationException(ErrorCode.INVALID_TOKEN, "Invalid OTP ID"));
    }
}
Also used : ServiceMapper(com.nexblocks.authguard.service.mappers.ServiceMapper) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) ErrorCode(com.nexblocks.authguard.service.exceptions.codes.ErrorCode) OffsetDateTime(java.time.OffsetDateTime) AuthVerifier(com.nexblocks.authguard.service.auth.AuthVerifier) EntityType(com.nexblocks.authguard.service.model.EntityType) Either(io.vavr.control.Either) Inject(com.google.inject.Inject) Optional(java.util.Optional) OneTimePasswordBO(com.nexblocks.authguard.service.model.OneTimePasswordBO) OtpRepository(com.nexblocks.authguard.dal.cache.OtpRepository) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) OneTimePasswordBO(com.nexblocks.authguard.service.model.OneTimePasswordBO)

Example 4 with ServiceAuthorizationException

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

the class PasswordlessProvider method generateToken.

@Override
public AuthResponseBO generateToken(final AccountBO account) {
    if (!account.isActive()) {
        throw new ServiceAuthorizationException(ErrorCode.ACCOUNT_INACTIVE, "Account was deactivated");
    }
    final String token = randomToken();
    final AccountTokenDO accountToken = AccountTokenDO.builder().id(ID.generate()).associatedAccountId(account.getId()).token(token).expiresAt(OffsetDateTime.now().plus(tokenTtl)).build();
    accountTokensRepository.save(accountToken);
    final PasswordlessMessageBody messageBody = new PasswordlessMessageBody(accountToken, account);
    messageBus.publish(PASSWORDLESS_CHANNEL, Messages.passwordlessGenerated(messageBody));
    return AuthResponseBO.builder().type(TOKEN_TYPE).token(accountToken.getId()).entityType(EntityType.ACCOUNT).entityId(account.getId()).build();
}
Also used : AccountTokenDO(com.nexblocks.authguard.dal.model.AccountTokenDO) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)

Example 5 with ServiceAuthorizationException

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

the class AuthenticationServiceImpl method authenticate.

@Override
public Optional<AuthResponseBO> authenticate(final AuthRequestBO authRequest, final RequestContextBO requestContext) {
    final AuthResponseBO tokens = exchangeService.exchange(authRequest, FROM_TOKEN_TYPE, generateTokenType, requestContext);
    final Collection<AccountLockBO> locks = accountLocksService.getActiveLocksByAccountId(tokens.getEntityId());
    if (locks == null || locks.isEmpty()) {
        return Optional.of(tokens);
    } else {
        throw new ServiceAuthorizationException(ErrorCode.ACCOUNT_IS_LOCKED, "There is an active lock on account " + tokens.getEntityId());
    }
}
Also used : AccountLockBO(com.nexblocks.authguard.service.model.AccountLockBO) AuthResponseBO(com.nexblocks.authguard.service.model.AuthResponseBO) 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