Search in sources :

Example 86 with Token

use of com.auth0.json.mgmt.Token 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 87 with Token

use of com.auth0.json.mgmt.Token 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 88 with Token

use of com.auth0.json.mgmt.Token in project localstack-pro-samples by localstack.

the class Test method convert.

public void convert(@NonNull final String token) throws MalformedURLException {
    final URL kidStore = new URL(awsProperties.getCognito().getKidStoreUrl());
    final JwkProvider jwkProvider = new JwkProviderBuilder(kidStore).build();
    final DecodedJWT decodedJWT = JWT.decode(token);
    final AwsCognitoRSAKeyProvider awsCognitoRSAKeyProvider = new AwsCognitoRSAKeyProvider(jwkProvider);
    JWT.require(Algorithm.RSA256(awsCognitoRSAKeyProvider)).acceptLeeway(ACCEPT_LEEWAY_SECONDS).withClaim(TOKEN_USE, ACCESS).build().verify(decodedJWT);
    final Claim clientIdClaim = decodedJWT.getClaim(CLIENT_ID);
    final Claim userNameClaim = decodedJWT.getClaim(USER_NAME);
    final Claim scopeClaim = decodedJWT.getClaim(SCOPE);
    final List<String> roles = Arrays.stream(scopeClaim.asString().split(" ")).map(scope -> scope.substring(scope.lastIndexOf("/") + 1)).collect(Collectors.toList());
    System.out.println("" + clientIdClaim + " " + userNameClaim + " " + roles);
// return new InsureSignToken()
// .setClientId(clientIdClaim.asString())
// .setUserName(userNameClaim.asString())
// .setRoles(roles);
}
Also used : Claim(com.auth0.jwt.Claim) RSAKeyProvider(com.auth0.jwt.interfaces.RSAKeyProvider) JWT(com.auth0.jwt.JWT) Arrays(java.util.Arrays) List(java.util.List) JwkProvider(com.auth0.jwk.JwkProvider) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) Algorithm(com.auth0.jwt.Algorithm) Collectors(java.util.stream.Collectors) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) JwkProvider(com.auth0.jwk.JwkProvider) JwkProviderBuilder(com.auth0.jwk.JwkProviderBuilder) URL(java.net.URL) Claim(com.auth0.jwt.Claim)

Example 89 with Token

use of com.auth0.json.mgmt.Token in project seckill by yt-King.

the class JWTUtils method verify.

/**
 * 校验token是否正确
 * @param token 密钥
 * @param password 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String password) {
    Algorithm algorithm = Algorithm.HMAC256(password);
    JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
    DecodedJWT jwt = verifier.verify(token);
    return true;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 90 with Token

use of com.auth0.json.mgmt.Token in project seckill by yt-King.

the class JWTUtils method sign.

/**
 * 生成签名
 * @param username 用户名
 * @param password 用户的密码
 * @return 加密的token
 */
public static String sign(String username, String password) {
    // 设置过期时间
    Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
    // 加密密码
    Algorithm algorithm = Algorithm.HMAC256(password);
    // 附带username信息
    return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17