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));
}
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;
}
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);
}
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;
}
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);
}
Aggregations