Search in sources :

Example 16 with Tokens

use of com.auth0.Tokens in project hopsworks by logicalclocks.

the class JWTController method renewServiceToken.

public Pair<String, String[]> renewServiceToken(String oneTimeRenewalToken, String serviceToken, Date newExpiration, Date newNotBefore, Long serviceJWTLifetimeMS, String username, List<String> userRoles, List<String> audience, String remoteHostname, String issuer, String defaultJWTSigningKeyName, boolean force) throws JWTException, NoSuchAlgorithmException {
    Map<String, Object> claims = new HashMap<>(4);
    claims.put(Constants.RENEWABLE, false);
    claims.put(Constants.EXPIRY_LEEWAY, 3600);
    claims.put(Constants.ROLES, userRoles.toArray(new String[1]));
    String renewalKeyName = getServiceOneTimeJWTSigningKeyname(username, remoteHostname);
    LocalDateTime masterExpiration = newExpiration.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    LocalDateTime notBefore = computeNotBefore4ServiceRenewalTokens(masterExpiration);
    LocalDateTime expiresAt = notBefore.plus(serviceJWTLifetimeMS, ChronoUnit.MILLIS);
    JsonWebToken jwtSpecs = new JsonWebToken();
    jwtSpecs.setSubject(username);
    jwtSpecs.setIssuer(issuer);
    jwtSpecs.setAudience(audience);
    jwtSpecs.setKeyId(renewalKeyName);
    jwtSpecs.setNotBefore(localDateTime2Date(notBefore));
    jwtSpecs.setExpiresAt(localDateTime2Date(expiresAt));
    try {
        // Then generate the new one-time tokens
        String[] renewalTokens = generateOneTimeTokens4ServiceJWTRenewal(jwtSpecs, claims, defaultJWTSigningKeyName);
        String signingKeyId = getSignKeyID(renewalTokens[0]);
        DecodedJWT serviceJWT = decodeToken(serviceToken);
        claims.clear();
        claims.put(Constants.RENEWABLE, false);
        claims.put(Constants.SERVICE_JWT_RENEWAL_KEY_ID, signingKeyId);
        claims.put(Constants.EXPIRY_LEEWAY, getExpLeewayClaim(serviceJWT));
        // Finally renew the service master token
        String renewedServiceToken = renewToken(serviceToken, newExpiration, newNotBefore, false, claims, force);
        invalidate(oneTimeRenewalToken);
        return Pair.of(renewedServiceToken, renewalTokens);
    } catch (JWTException | NoSuchAlgorithmException ex) {
        if (renewalKeyName != null) {
            deleteSigningKey(renewalKeyName);
        }
        throw ex;
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) JWTException(io.hops.hopsworks.jwt.exception.JWTException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 17 with Tokens

use of com.auth0.Tokens in project hopsworks by logicalclocks.

the class JWTController method invalidate.

/**
 * Invalidate a token by adding it to the invalid tokens table.
 *
 * @param token
 * @throws io.hops.hopsworks.jwt.exception.InvalidationException
 */
public void invalidate(String token) throws InvalidationException {
    if (token == null || token.isEmpty()) {
        return;
    }
    DecodedJWT jwt;
    try {
        jwt = verifyToken(token, null);
    } catch (Exception ex) {
        // no need to invalidate if not valid
        return;
    }
    int expLeeway = getExpLeewayClaim(jwt);
    invalidateJWT(jwt.getId(), jwt.getExpiresAt(), expLeeway);
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) NotRenewableException(io.hops.hopsworks.jwt.exception.NotRenewableException) DuplicateSigningKeyException(io.hops.hopsworks.jwt.exception.DuplicateSigningKeyException) AccessLocalException(javax.ejb.AccessLocalException) SigningKeyNotFoundException(io.hops.hopsworks.jwt.exception.SigningKeyNotFoundException) JWTException(io.hops.hopsworks.jwt.exception.JWTException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) VerificationException(io.hops.hopsworks.jwt.exception.VerificationException) InvalidationException(io.hops.hopsworks.jwt.exception.InvalidationException)

Example 18 with Tokens

use of com.auth0.Tokens in project auth0-java by auth0.

the class BlacklistsEntityTest method shouldGetBlacklistedTokens.

@Test
public void shouldGetBlacklistedTokens() throws Exception {
    Request<List<Token>> request = api.blacklists().getBlacklist("myapi");
    assertThat(request, is(notNullValue()));
    server.jsonResponse(MGMT_BLACKLISTED_TOKENS_LIST, 200);
    List<Token> response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();
    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/blacklists/tokens"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("aud", "myapi"));
    assertThat(response, is(notNullValue()));
    assertThat(response, hasSize(2));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) List(java.util.List) Token(com.auth0.json.mgmt.Token) Test(org.junit.Test)

Example 19 with Tokens

use of com.auth0.Tokens 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 20 with Tokens

use of com.auth0.Tokens in project AuthGuard by AuthGuard.

the class JwtTokenVerifierTest method validate.

@Test
void validate() {
    final StrategyConfig strategyConfig = strategyConfig(false);
    final JwtConfig jwtConfig = jwtConfig();
    final JwtTokenVerifier jwtTokenVerifier = newVerifierInstance(strategyConfig);
    final AccountBO account = RANDOM.nextObject(AccountBO.class);
    final AuthResponseBO tokens = generateToken(jwtConfig, account, null);
    final Either<Exception, DecodedJWT> validatedToken = jwtTokenVerifier.verify(tokens.getToken().toString());
    assertThat(validatedToken.isRight()).isTrue();
    verifyToken(validatedToken.get(), account.getId(), null, null, null);
}
Also used : AccountBO(com.nexblocks.authguard.service.model.AccountBO) JwtConfig(com.nexblocks.authguard.service.config.JwtConfig) StrategyConfig(com.nexblocks.authguard.service.config.StrategyConfig) AuthResponseBO(com.nexblocks.authguard.service.model.AuthResponseBO) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ServiceAuthorizationException(com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException) Test(org.junit.jupiter.api.Test)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)13 HashMap (java.util.HashMap)8 Test (org.junit.jupiter.api.Test)7 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 TokenHolder (com.auth0.json.auth.TokenHolder)4 TokenRequest (com.auth0.net.TokenRequest)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 Date (java.util.Date)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.JWTVerifier)3 ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)3 AccountBO (com.nexblocks.authguard.service.model.AccountBO)3 User (org.springframework.security.core.userdetails.User)3 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)2 Claim (com.auth0.jwt.interfaces.Claim)2 JsonPath (com.jayway.jsonpath.JsonPath)2 ReadContext (com.jayway.jsonpath.ReadContext)2 JwtConfig (com.nexblocks.authguard.service.config.JwtConfig)2 StrategyConfig (com.nexblocks.authguard.service.config.StrategyConfig)2 AuthResponseBO (com.nexblocks.authguard.service.model.AuthResponseBO)2