Search in sources :

Example 1 with JWTCreationException

use of com.auth0.jwt.exceptions.JWTCreationException in project supertokens-core by supertokens.

the class JWTSigningFunctions method createJWTToken.

/**
 * Creates and returns a JWT string
 *
 * @param main
 * @param algorithm   The signing algorithm to use when creating the token. Refer to
 *                    {@link JWTSigningKey.SupportedAlgorithms}
 * @param payload     JSON object containing user defined claims to be added to the JWT payload
 * @param jwksDomain  Used as the issuer in the JWT payload
 * @param jwtValidity Used to set iat anf exp claims in the JWT payload
 * @return String token
 * @throws StorageQueryException                   If there is an error interacting with the database
 * @throws StorageTransactionLogicException        If there is an error interacting with the database
 * @throws NoSuchAlgorithmException                If there is an error when using Java's cryptography packages
 * @throws InvalidKeySpecException                 If there is an error when using Java's cryptography packages
 * @throws JWTCreationException                    If there is an error when creating JWTs
 * @throws UnsupportedJWTSigningAlgorithmException If the algorithm provided does not match any of the supported
 *                                                 algorithms
 */
@SuppressWarnings("unchecked")
public static String createJWTToken(Main main, String algorithm, JsonObject payload, String jwksDomain, long jwtValidity) throws StorageQueryException, StorageTransactionLogicException, NoSuchAlgorithmException, InvalidKeySpecException, JWTCreationException, UnsupportedJWTSigningAlgorithmException {
    // TODO: In the future we will have a way for the user to send a custom key id to use
    JWTSigningKey.SupportedAlgorithms supportedAlgorithm;
    try {
        supportedAlgorithm = JWTSigningKey.SupportedAlgorithms.valueOf(algorithm);
    } catch (IllegalArgumentException e) {
        // If it enters this block then the string value provided does not match the algorithms we support
        throw new UnsupportedJWTSigningAlgorithmException();
    }
    JWTSigningKeyInfo keyToUse = JWTSigningKey.getInstance(main).getOrCreateAndGetKeyForAlgorithm(supportedAlgorithm);
    // Get an instance of auth0's Algorithm which is needed when signing using auth0's package
    Algorithm signingAlgorithm = getAuth0Algorithm(supportedAlgorithm, keyToUse);
    // Create the claims for the JWT header
    Map<String, Object> headerClaims = new HashMap<>();
    // All examples in the RFC have the algorithm
    headerClaims.put("alg", supportedAlgorithm.name().toUpperCase());
    // in upper case
    headerClaims.put("typ", "JWT");
    headerClaims.put("kid", keyToUse.keyId);
    long currentTimeInMillis = System.currentTimeMillis();
    // JWT Expiry is seconds from epoch not millis
    long jwtExpiry = Double.valueOf(Math.ceil((currentTimeInMillis / 1000.0))).longValue() + (jwtValidity);
    // Add relevant claims to the payload, note we only add/override ones that we absolutely need to.
    Map<String, Object> jwtPayload = new Gson().fromJson(payload, HashMap.class);
    jwtPayload.putIfAbsent("iss", jwksDomain);
    jwtPayload.put("exp", jwtExpiry);
    // JWT uses seconds from epoch not millis
    jwtPayload.put("iat", currentTimeInMillis / 1000);
    return com.auth0.jwt.JWT.create().withPayload(jwtPayload).withHeader(headerClaims).sign(signingAlgorithm);
}
Also used : UnsupportedJWTSigningAlgorithmException(io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException) JWTSigningKeyInfo(io.supertokens.pluginInterface.jwt.JWTSigningKeyInfo) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Example 2 with JWTCreationException

use of com.auth0.jwt.exceptions.JWTCreationException in project teamapps by teamapps-org.

the class MediaSoupV3TokenGenerator method generateJwtToken.

public static String generateJwtToken(String secret, MediaSoupV3ApiOperation operation, String streamUuid, Duration tokenValidityDuration) {
    if (secret == null) {
        return "";
    }
    try {
        Algorithm algorithm = Algorithm.HMAC512(secret);
        JWTCreator.Builder builder = JWT.create();
        if (operation != null) {
            builder = builder.withClaim("operation", operation.ordinal());
        }
        if (streamUuid != null) {
            builder = builder.withClaim("stream", streamUuid);
        }
        if (tokenValidityDuration != null) {
            builder = builder.withExpiresAt(new Date(Instant.now().plus(tokenValidityDuration).toEpochMilli()));
        }
        return builder.sign(algorithm);
    } catch (JWTCreationException exception) {
        throw new RuntimeException("Could not create auth token - this should never happen!");
    }
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Example 3 with JWTCreationException

use of com.auth0.jwt.exceptions.JWTCreationException in project einstein-bot-sdk-java by forcedotcom.

the class JwtBearerOAuth method getToken.

@Override
public String getToken() {
    Optional<String> token = cache.flatMap(c -> c.get(getCacheKey()));
    if (token.isPresent()) {
        logger.debug("Found cached OAuth token.");
        return token.get();
    }
    logger.debug("Did not find OAuth token in cache. Will retrieve from OAuth server.");
    Instant now = Instant.now();
    String jwt = null;
    try {
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("alg", "RS256");
        Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
        jwt = JWT.create().withHeader(headers).withAudience(loginEndpoint).withExpiresAt(Date.from(now.plus(jwtExpiryMinutes, ChronoUnit.MINUTES))).withIssuer(connectedAppId).withSubject(userId).sign(algorithm);
        logger.debug("Generated jwt: {} ", jwt);
    } catch (JWTCreationException exception) {
        // Invalid Signing configuration / Couldn't convert Claims.
        throw new RuntimeException(exception);
    }
    String response = webClient.post().uri("/services/oauth2/token").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).body(BodyInserters.fromFormData("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer").with("assertion", jwt)).retrieve().bodyToMono(String.class).block();
    String oAuthToken = null;
    try {
        ObjectNode node = new ObjectMapper().readValue(response, ObjectNode.class);
        oAuthToken = node.get("access_token").asText();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    IntrospectionResult iResult = introspector.introspect(oAuthToken);
    if (!iResult.isActive()) {
        throw new RuntimeException("OAuth token is not active.");
    }
    Instant expiry = Instant.ofEpochSecond(iResult.getExp());
    long ttl = Math.max(0, Instant.now().until(expiry, ChronoUnit.SECONDS) - 300);
    if (cache.isPresent()) {
        cache.get().set(getCacheKey(), oAuthToken, ttl);
    }
    return oAuthToken;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HashMap(java.util.HashMap) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) OAuthResponseException(com.salesforce.einsteinbot.sdk.exception.OAuthResponseException) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with JWTCreationException

use of com.auth0.jwt.exceptions.JWTCreationException in project toy by gmoon92.

the class JwtUtil method generate.

public String generate(User user) {
    try {
        ZonedDateTime today = ZonedDateTime.now();
        String token = JWT.create().withIssuer(apiVersion).withClaim("username", user.getUsername()).withClaim("role", user.getRole().name()).withIssuedAt(Date.from(today.toInstant())).withExpiresAt(Date.from(today.plusDays(DAY_OF_EXPIRATION).toInstant())).sign(algorithm);
        return String.format("%s %s", AuthenticationSchema.BEARER.getName(), token);
    } catch (JWTCreationException e) {
        throw new JWTCreationException("Invalid Signing configuration or Couldn't convert Claims.", e);
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Example 5 with JWTCreationException

use of com.auth0.jwt.exceptions.JWTCreationException in project cryptography by norkator.

the class JWT method createECDSA256Jwt.

/**
 * Create elliptic curve based JWT
 *
 * @param privatePem of EC keypair
 * @param issuer     party name
 * @return json web token
 * @throws JWTCreationException if jwt creation fails
 */
public static String createECDSA256Jwt(String privatePem, String issuer) throws InvalidKeySpecException, NoSuchAlgorithmException {
    ECKey privateKey = (ECKey) PEMToKey.getPemPrivateKey(privatePem, "ECDSA");
    Algorithm algorithm = Algorithm.ECDSA256(privateKey);
    return com.auth0.jwt.JWT.create().withIssuer(issuer).withClaim("test claim", "test claim value").sign(algorithm);
}
Also used : ECKey(java.security.interfaces.ECKey) Algorithm(com.auth0.jwt.algorithms.Algorithm)

Aggregations

JWTCreationException (com.auth0.jwt.exceptions.JWTCreationException)11 Algorithm (com.auth0.jwt.algorithms.Algorithm)8 ZonedDateTime (java.time.ZonedDateTime)4 Date (java.util.Date)4 Gson (com.google.gson.Gson)2 IOException (java.io.IOException)2 Principal (java.security.Principal)2 HashMap (java.util.HashMap)2 JWTCreator (com.auth0.jwt.JWTCreator)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1 PemReader (com.google.api.client.util.PemReader)1 JsonObject (com.google.gson.JsonObject)1 OAuthResponseException (com.salesforce.einsteinbot.sdk.exception.OAuthResponseException)1 ByteBuf (io.netty.buffer.ByteBuf)1 UnsupportedJWTSigningAlgorithmException (io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException)1 JWTSigningKeyInfo (io.supertokens.pluginInterface.jwt.JWTSigningKeyInfo)1 File (java.io.File)1 StringReader (java.io.StringReader)1 KeyFactory (java.security.KeyFactory)1