Search in sources :

Example 1 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project Team_Ahpuh_Surf_BE by prgrms-web-devcourse.

the class Jwt method sign.

public String sign(final Claims claims) {
    final Date now = new Date();
    final JWTCreator.Builder builder = com.auth0.jwt.JWT.create();
    builder.withIssuer(issuer);
    builder.withIssuedAt(now);
    if (expirySeconds > 0) {
        builder.withExpiresAt(new Date(now.getTime() + expirySeconds * 1_000L));
    }
    builder.withClaim("user_id", claims.userId);
    builder.withClaim("email", claims.email);
    builder.withArrayClaim("roles", claims.roles);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Date(java.util.Date)

Example 2 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions 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 3 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project auth0-java-mvc-common by auth0.

the class RequestProcessorTest method shouldReturnTokensOnProcessIfCodeRequestPassesIdTokenVerification.

@Test
public void shouldReturnTokensOnProcessIfCodeRequestPassesIdTokenVerification() throws Exception {
    doNothing().when(tokenVerifier).verify(eq("backIdToken"), eq(verifyOptions));
    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));
    TokenRequest codeExchangeRequest = mock(TokenRequest.class);
    TokenHolder tokenHolder = mock(TokenHolder.class);
    when(tokenHolder.getIdToken()).thenReturn("backIdToken");
    when(tokenHolder.getAccessToken()).thenReturn("backAccessToken");
    when(tokenHolder.getRefreshToken()).thenReturn("backRefreshToken");
    when(codeExchangeRequest.execute()).thenReturn(tokenHolder);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);
    RequestProcessor handler = new RequestProcessor.Builder(client, "code", verifyOptions).withIdTokenVerifier(tokenVerifier).build();
    Tokens tokens = handler.process(request, response);
    verify(tokenVerifier).verify("backIdToken", verifyOptions);
    verifyNoMoreInteractions(tokenVerifier);
    assertThat(tokens, is(notNullValue()));
    assertThat(tokens.getIdToken(), is("backIdToken"));
    assertThat(tokens.getAccessToken(), is("backAccessToken"));
    assertThat(tokens.getRefreshToken(), is("backRefreshToken"));
}
Also used : Cookie(javax.servlet.http.Cookie) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TokenRequest(com.auth0.net.TokenRequest) TokenHolder(com.auth0.json.auth.TokenHolder) Test(org.junit.jupiter.api.Test)

Example 4 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project auth0-java-mvc-common by auth0.

the class RequestProcessorTest method shouldReturnTokensOnProcessIfIdTokenCodeRequestPassesIdTokenVerification.

@Test
public void shouldReturnTokensOnProcessIfIdTokenCodeRequestPassesIdTokenVerification() throws Exception {
    doNothing().when(tokenVerifier).verify(eq("frontIdToken"), eq(verifyOptions));
    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    params.put("id_token", "frontIdToken");
    params.put("expires_in", "8400");
    params.put("token_type", "frontTokenType");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));
    TokenRequest codeExchangeRequest = mock(TokenRequest.class);
    TokenHolder tokenHolder = mock(TokenHolder.class);
    when(tokenHolder.getIdToken()).thenReturn("backIdToken");
    when(tokenHolder.getExpiresIn()).thenReturn(4800L);
    when(tokenHolder.getTokenType()).thenReturn("backTokenType");
    when(codeExchangeRequest.execute()).thenReturn(tokenHolder);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);
    RequestProcessor handler = new RequestProcessor.Builder(client, "id_token code", verifyOptions).withIdTokenVerifier(tokenVerifier).build();
    Tokens tokens = handler.process(request, response);
    // Should not verify the ID Token twice
    verify(tokenVerifier).verify("frontIdToken", verifyOptions);
    verify(tokenVerifier, never()).verify("backIdToken", verifyOptions);
    verifyNoMoreInteractions(tokenVerifier);
    assertThat(tokens, is(notNullValue()));
    assertThat(tokens.getIdToken(), is("frontIdToken"));
    assertThat(tokens.getType(), is("frontTokenType"));
    assertThat(tokens.getExpiresIn(), is(8400L));
}
Also used : Cookie(javax.servlet.http.Cookie) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TokenRequest(com.auth0.net.TokenRequest) TokenHolder(com.auth0.json.auth.TokenHolder) Test(org.junit.jupiter.api.Test)

Example 5 with com.auth0.jwt.exceptions

use of com.auth0.jwt.exceptions in project auth0-java-mvc-common by auth0.

the class RequestProcessorTest method shouldThrowOnProcessIfCodeRequestFailsToExecuteCodeExchange.

@Test
public void shouldThrowOnProcessIfCodeRequestFailsToExecuteCodeExchange() throws Exception {
    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));
    TokenRequest codeExchangeRequest = mock(TokenRequest.class);
    when(codeExchangeRequest.execute()).thenThrow(Auth0Exception.class);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);
    RequestProcessor handler = new RequestProcessor.Builder(client, "code", verifyOptions).withIdTokenVerifier(tokenVerifier).build();
    IdentityVerificationException e = assertThrows(IdentityVerificationException.class, () -> handler.process(request, response));
    assertThat(e, IdentityVerificationExceptionMatcher.hasCode("a0.api_error"));
    assertEquals("An error occurred while exchanging the authorization code.", e.getMessage());
}
Also used : Cookie(javax.servlet.http.Cookie) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TokenRequest(com.auth0.net.TokenRequest) Test(org.junit.jupiter.api.Test)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)8 TokenRequest (com.auth0.net.TokenRequest)8 Test (org.junit.jupiter.api.Test)8 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)8 TokenHolder (com.auth0.json.auth.TokenHolder)7 Date (java.util.Date)7 HashMap (java.util.HashMap)7 JWTCreator (com.auth0.jwt.JWTCreator)6 JWTVerifier (com.auth0.jwt.JWTVerifier)6 Cookie (javax.servlet.http.Cookie)6 ECKey (java.security.interfaces.ECKey)3 AuthorizeUrlBuilder (com.auth0.client.auth.AuthorizeUrlBuilder)2 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 ViewModelProvider (androidx.lifecycle.ViewModelProvider)1 NavController (androidx.navigation.NavController)1 TipoUsuario (br.com.propague.api.model.TipoUsuario)1 Usuario (br.com.propague.api.model.Usuario)1 JWT (com.auth0.android.jwt.JWT)1 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)1