com.auth0.jwt.JWT Java Examples

The following examples show how to use com.auth0.jwt.JWT. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JWTVerifierFactory.java    From spring-jwt-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("jwk")
public JWTVerifier create(@Value("${jwt.issuer}") String issuer, @Value("${jwt.audience}") String audience)
        throws JwkException, IOException {

    UrlJwkProvider urlJwkProvider = new UrlJwkProvider(issuer);
    RestTemplate restTemplate = new RestTemplate();

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(restTemplate.getForObject(issuer + "/.well-known/jwks.json", String.class));
    String kid = jsonNode.get("keys").get(0).get("kid").asText();

    Jwk jwk = urlJwkProvider.get(kid);

    return JWT.require(Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null))
            .withIssuer(issuer)
            .withAudience(audience)
            .build();
}
 
Example #2
Source File: AuthenticationEndpoint.java    From waltz with Apache License 2.0 6 votes vote down vote up
@Override
public void register() {

    post(mkPath(BASE_URL, "login"), (request, response) -> {

        LoginRequest login = readBody(request, LoginRequest.class);
        AuthenticationResponse authResponse = authenticate(login);

        if (authResponse.success()) {
            Algorithm algorithmHS = Algorithm.HMAC512(JWTUtilities.SECRET);

            String[] roles = userRoleService
                    .getUserRoles(authResponse.waltzUserName())
                    .toArray(new String[0]);

            String token = JWT.create()
                    .withIssuer(JWTUtilities.ISSUER)
                    .withSubject(authResponse.waltzUserName())
                    .withArrayClaim("roles", roles)
                    .withClaim("displayName", login.userName())
                    .withClaim("employeeId", login.userName())
                    .sign(algorithmHS);

            return newHashMap("token", token);
        } else {
            response.status(401);
            return authResponse.errorMessage();
        }
    }, transformer);

    before(mkPath("api", "*"), filter);

}
 
Example #3
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnECDSA256VerificationWithDERSignatureWithBothKeys() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA");
    exception.expectCause(isA(SignatureException.class));
    exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));

    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.MEYCIQDiJWTf5jShFPj0hpCWn7x1nhxPMjKWCs9MMusS9AIhAMcFPJVLe2A9uvb8hl8sRO2IpGoKDRpDmyH14ixNPAHW";
    Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
Example #4
Source File: IdTokenVerifierTest.java    From auth0-java-mvc-common with MIT License 5 votes vote down vote up
private IdTokenVerifier.Options configureOptions(String token) {
    DecodedJWT decodedJWT = JWT.decode(token);
    SignatureVerifier verifier = mock(SignatureVerifier.class);
    when(verifier.verifySignature(token)).thenReturn(decodedJWT);

    IdTokenVerifier.Options opts = new IdTokenVerifier.Options("https://" + DOMAIN + "/", AUDIENCE, verifier);
    opts.setClock(DEFAULT_CLOCK);
    return opts;
}
 
Example #5
Source File: JWTUtil.java    From SpringBootBucket with MIT License 5 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, String username, String secret) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier verifier = JWT.require(algorithm)
            .withClaim("username", username)
            .build();
    DecodedJWT jwt = verifier.verify(token);
    return true;
}
 
Example #6
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldFailECDSA512VerificationOnInvalidJOSESignatureLength() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withECDSA");
    exception.expectCause(isA(SignatureException.class));
    exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));

    byte[] bytes = new byte[131];
    new SecureRandom().nextBytes(bytes);
    String signature = Base64.encodeBase64URLSafeString(bytes);
    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;
    Algorithm algorithm = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(INVALID_PUBLIC_KEY_FILE_512, "EC"));
    algorithm.verify(JWT.decode(jwt));
}
 
Example #7
Source File: JwtUtil.java    From flash-waimai with MIT License 5 votes vote down vote up
public static Long getUserId(String token) {
    try {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("userId").asLong();
    } catch (JWTDecodeException e) {
        return null;
    }
}
 
Example #8
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldFailJOSEToDERConversionOnInvalidJOSESignatureLength() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA256withECDSA");
    exception.expectCause(isA(SignatureException.class));
    exception.expectCause(hasMessage(is("Invalid JOSE signature format.")));

    byte[] bytes = new byte[256];
    new SecureRandom().nextBytes(bytes);
    String signature = Base64.encodeBase64URLSafeString(bytes);
    String jwt = "eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9." + signature;

    ECPublicKey publicKey = (ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC");
    ECPrivateKey privateKey = mock(ECPrivateKey.class);
    ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey);
    Algorithm algorithm = new ECDSAAlgorithm("ES256", "SHA256withECDSA", 128, provider);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #9
Source File: ECDSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoECDSA256SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.ECDSA256((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_256, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_256, "EC"));
    byte[] signatureBytes = algorithm.sign(ES256HeaderBytes, auth0IssPayloadBytes);
    String jwtSignature = Base64.encodeBase64URLSafeString(signatureBytes);
    String jwt = String.format("%s.%s.%s", ES256Header, auth0IssPayload, jwtSignature);

    assertSignaturePresent(jwt);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #10
Source File: IlpOverHttpJwtEmitter.java    From quilt with Apache License 2.0 5 votes vote down vote up
/**
 * Emit a JWT that has enhanced security.
 */
private static void emitHs256JwtWithExpiry() {

  final String jwtString = JWT.create()
    .withSubject(SUBJECT)
    .withExpiresAt(Date.from(Instant.now().plus(730, ChronoUnit.DAYS)))
    .sign(ALGORITHM_HS256);

  LOGGER.info("JWT: {}", jwtString);
  LOGGER.info("JWT Length (bytes): {}", jwtString.length());

  // Log the JWT claims...
  JWT.decode(jwtString).getClaims().forEach((key, value) ->
    LOGGER.info("Claim -> \"{}\":\"{}\"", key, value.asString()
    ));

  // Valid token...
  final Verification verification = JWT.require(ALGORITHM_HS256).withSubject(SUBJECT);

  // Valid token...
  verification.build().verify(jwtString);

  // Invalid token...
  try {
    verification.withSubject("bob").build().verify(jwtString);
    throw new RuntimeException("Verify should have failed");
  } catch (InvalidClaimException e) {
    LOGGER.info("Invalid JWT for `bob` did not verify, as expected.");
  }
}
 
Example #11
Source File: RSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldFailRSA512VerificationWhenProvidedPublicKeyIsNull() throws Exception {
    exception.expect(SignatureVerificationException.class);
    exception.expectMessage("The Token's Signature resulted invalid when verified using the Algorithm: SHA512withRSA");
    exception.expectCause(isA(IllegalStateException.class));
    exception.expectCause(hasMessage(is("The given Public Key is null.")));
    RSAKeyProvider provider = mock(RSAKeyProvider.class);
    when(provider.getPublicKeyById("my-key-id")).thenReturn(null);
    String jwt = "eyJhbGciOiJSUzUxMiIsImtpZCI6Im15LWtleS1pZCJ9.eyJpc3MiOiJhdXRoMCJ9.GpHv85Q8tAU_6hNWsmO0GEpO1qz9lmK3NKeAcemysz9MGo4FXWn8xbD8NjCfzZ8EWphm65M0NArKSjpKHO5-gcNsQxLBVfSED1vzcoaZH_Vy5Rp1M76dGH7JghB_66KrpfyMxer_yRJb-KXesNvIroDGilLQF2ENG-IfLF5nBKlDiVHmPaqr3pm1q20fNLhegkSRca4BJ5VdIlT6kOqE_ykVyCBqzD_oXp3LKO_ARnxoeB9SegIW1fy_3tuxSTKYsCZiOfiyVEXXblAuY3pSLZnGvgeBRnfvmWXDWhP0vVUFtYJBF09eULvvUMVqWcrjUG9gDzzzT7veiY_fHd_x8g";
    Algorithm algorithm = Algorithm.RSA512(provider);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #12
Source File: RSAAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoRSA384Signing() throws Exception {
    Algorithm algorithmSign = Algorithm.RSA384((RSAKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE, "RSA"));
    Algorithm algorithmVerify = Algorithm.RSA384((RSAKey) readPublicKeyFromFile(PUBLIC_KEY_FILE, "RSA"));

    String jwt = asJWT(algorithmSign, RS384Header, auth0IssPayload);
    String expectedSignature = "Jx1PaTBnjd_U56MNjifFcY7w9ImDbseg0y8Ijr2pSiA1_wzQb_wy9undaWfzR5YqdIAXvjS8AGuZUAzIoTG4KMgOgdVyYDz3l2jzj6wI-lgqfR5hTy1w1ruMUQ4_wobpdxAiJ4fEbg8Mi_GljOiCO-P1HilxKnpiOJZidR8MQGwTInsf71tOUkK4x5UsdmUueuZbaU-CL5kPnRfXmJj9CcdxZbD9oMlbo23dwkP5BNMrS2LwGGzc9C_-ypxrBIOVilG3WZxcSmuG86LjcZbnL6LBEfph5NmKBgQav147uipb_7umBEr1m2dYiB_9u606n3bcoo3rnsYYK_Xfi1GAEQ";

    assertSignaturePresent(jwt);
    assertSignatureValue(jwt, expectedSignature);
    algorithmVerify.verify(JWT.decode(jwt));
}
 
Example #13
Source File: JwtUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 *
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
	try {
		DecodedJWT jwt = JWT.decode(token);
		return jwt.getClaim("username").asString();
	} catch (JWTDecodeException e) {
		return null;
	}
}
 
Example #14
Source File: JWTUtil.java    From notes with Apache License 2.0 5 votes vote down vote up
/**
 * 校验token是否正确
 *
 * @param token  密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
public static boolean verify(String token, Map<String,Object> userToken, String secret) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTVerifier verifier = JWT.require(algorithm)
            .withClaim("userId",userToken.get("userId").toString())
            .withClaim("userName", userToken.get("userName").toString())
            .withClaim("timestamp",Long.parseLong(userToken.get("timestamp").toString()))
            .build();
    DecodedJWT jwt = verifier.verify(token);
    return true;
}
 
Example #15
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoECDSA512Signing() throws Exception {
    Algorithm algorithmSign = Algorithm.ECDSA512((ECKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_512, "EC"));
    Algorithm algorithmVerify = Algorithm.ECDSA512((ECKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_512, "EC"));
    
    String jwt = asJWT(algorithmSign, ES512Header, auth0IssPayload);

    assertSignaturePresent(jwt);
    algorithmVerify.verify(JWT.decode(jwt));
}
 
Example #16
Source File: JwtUtil.java    From jeecg-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 生成签名,5min后过期
 *
 * @param username 用户名
 * @param secret   用户的密码
 * @return 加密的token
 */
public static String sign(String username, String secret) {
	Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
	Algorithm algorithm = Algorithm.HMAC256(secret);
	// 附带username信息
	return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);

}
 
Example #17
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldAuthenticateUsingJWKAndSeveralAllowedIssuers() throws Exception {
    Jwk jwk = mock(Jwk.class);
    JwkProvider jwkProvider = mock(JwkProvider.class);

    KeyPair keyPair = RSAKeyPair();
    when(jwkProvider.get(eq("key-id"))).thenReturn(jwk);
    when(jwk.getPublicKey()).thenReturn(keyPair.getPublic());
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider(jwkProvider, new String[]{"test-issuer1", "test-issuer2"}, "test-audience");
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer2")
            .withHeader(keyIdHeader)
            .sign(Algorithm.RSA256(null, (RSAPrivateKey) keyPair.getPrivate()));

    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    Authentication result = provider.authenticate(authentication);

    assertThat(result, is(notNullValue()));
    assertThat(result, is(not(equalTo(authentication))));
}
 
Example #18
Source File: JWTSecurityService.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
private static String createToken(String jwtKey, String path, Date expireDate) {
    UriComponents components = UriComponentsBuilder.fromUriString(path).build();
    String query = components.getQuery();
    String claim = components.getPath() + (!StringUtils.isBlank(query) ? "?" + components.getQuery() : "");
    LOG.debug("Creating token with claim " + claim);
    return JWT.create()
            .withClaim(CLAIM_PATH, claim)
            .withExpiresAt(expireDate)
            .sign(getAlgorithm(jwtKey));
}
 
Example #19
Source File: MCRJWTUtil.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static JWTCreator.Builder getJWTBuilder(MCRUserInformation userInformation) {
    String[] roles = MCRConfiguration2.getOrThrow(ROLES_PROPERTY, MCRConfiguration2::splitValue)
        .filter(userInformation::isUserInRole)
        .toArray(String[]::new);
    String subject = userInformation.getUserID();
    String email = userInformation.getUserAttribute(MCRUserInformation.ATT_EMAIL);
    String name = userInformation.getUserAttribute(MCRUserInformation.ATT_REAL_NAME);
    return JWT.create()
        .withIssuedAt(new Date())
        .withSubject(subject)
        .withArrayClaim("mcr:roles", roles)
        .withClaim("email", email)
        .withClaim("name", name);
}
 
Example #20
Source File: AuthenticationJsonWebTokenTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldGetNullPrincipalOnMissingSubjectClaim() throws Exception {
    String token = JWT.create()
            .sign(hmacAlgorithm);

    AuthenticationJsonWebToken auth = new AuthenticationJsonWebToken(token, verifier);
    assertThat(auth, is(notNullValue()));
    assertThat(auth.getPrincipal(), is(nullValue()));
}
 
Example #21
Source File: JwtAuthenticationProviderTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldAuthenticateUsingSecret() throws Exception {
    JwtAuthenticationProvider provider = new JwtAuthenticationProvider("secret".getBytes(), "test-issuer", "test-audience");
    String token = JWT.create()
            .withAudience("test-audience")
            .withIssuer("test-issuer")
            .sign(Algorithm.HMAC256("secret"));
    Authentication authentication = PreAuthenticatedAuthenticationJsonWebToken.usingToken(token);

    Authentication result = provider.authenticate(authentication);

    assertThat(result, is(notNullValue()));
    assertThat(result, is(not(equalTo(authentication))));
}
 
Example #22
Source File: ECDSABouncyCastleProviderTests.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoECDSA384SigningWithBothKeys() throws Exception {
    Algorithm algorithm = Algorithm.ECDSA384((ECPublicKey) readPublicKeyFromFile(PUBLIC_KEY_FILE_384, "EC"), (ECPrivateKey) readPrivateKeyFromFile(PRIVATE_KEY_FILE_384, "EC"));
    String jwt = asJWT(algorithm, ES384Header, auth0IssPayload);

    assertSignaturePresent(jwt);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #23
Source File: JwtUtil.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
/**
 * 生成签名,五分钟后过期
 * @param userId
 * @return
 */
public static String sign(String userId) {
    try {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                // 将 user id 保存到 token 里面
                .withAudience(userId)
                // 五分钟后token过期
                .withExpiresAt(date)
                // token 的密钥
                .sign(algorithm);
    } catch (Exception e) {
        return null;
    }
}
 
Example #24
Source File: JwtUtils.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * decode AccountEntity from token
 * f
 *
 * @param token token
 * @return AccountEntity
 */
public static AccountEntity decodeToken(String token, String privateSecret) {
    try {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(privateSecret)).build();
        DecodedJWT jwt = verifier.verify(token);
        // check expired date
        if (Calendar.getInstance().getTime().after(jwt.getExpiresAt())) {
            log.error("expired token at {}", jwt.getExpiresAt());
            return null;
        }
        return new AccountEntity(jwt.getIssuer());
    } catch (JWTVerificationException e) {
        log.error("invalid jwt token", e);
        return null;
    }
}
 
Example #25
Source File: JwtUtils.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * @param username
 * @param expiration
 * @return token
 */
public static String encodeToken(String username, String privateSecret, int expiration) {
    try {
        JWTCreator.Builder builder = JWT.create();
        builder.withIssuer(username);
        // set expired date
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, expiration);
        builder.withExpiresAt(now.getTime());
        return builder.sign(Algorithm.HMAC256(privateSecret));
    } catch (JWTCreationException e) {
        log.error("create jwt token failed", e);
        return "";
    }
}
 
Example #26
Source File: PreAuthenticatedAuthenticationJsonWebTokenTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldGetKeyId() throws Exception {
    Map<String, Object> keyIdHeader = Collections.singletonMap("kid", (Object) "key-id");
    String token = JWT.create()
            .withHeader(keyIdHeader)
            .sign(hmacAlgorithm);

    PreAuthenticatedAuthenticationJsonWebToken auth = usingToken(token);
    assertThat(auth, is(notNullValue()));
    assertThat(auth.getKeyId(), is("key-id"));
}
 
Example #27
Source File: HMACAlgorithmTest.java    From java-jwt with MIT License 5 votes vote down vote up
@Test
public void shouldDoHMAC512SigningWithBytes() throws Exception {
    Algorithm algorithm = Algorithm.HMAC512("secret".getBytes(StandardCharsets.UTF_8));

    String jwt = asJWT(algorithm, HS512Header, auth0IssPayload);
    String expectedSignature = "OXWyxmf-VcVo8viOiTFfLaEy6mrQqLEos5R82Xsx8mtFxQadJAQ1aVniIWN8qT2GNE_pMQPcdzk4x7Cqxsp1dw";

    assertSignaturePresent(jwt);
    assertSignatureValue(jwt, expectedSignature);
    algorithm.verify(JWT.decode(jwt));
}
 
Example #28
Source File: AuthenticationServiceJwtImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public AuthenticationServiceJwtImpl() throws Exception {
    File rsocketKeysDir = new File(System.getProperty("user.home"), ".rsocket");
    File publicKeyFile = new File(rsocketKeysDir, "jwt_rsa.pub");
    // generate RSA key pairs automatically
    if (!publicKeyFile.exists()) {
        if (!rsocketKeysDir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            rsocketKeysDir.mkdir();
        }
        generateRSAKeyPairs(rsocketKeysDir);
    }
    Algorithm algorithmRSA256Public = Algorithm.RSA256(readPublicKey(), null);
    this.verifiers.add(JWT.require(algorithmRSA256Public).withIssuer(iss).build());
}
 
Example #29
Source File: JwtUtil.java    From teaching with Apache License 2.0 5 votes vote down vote up
/**
 * 获得token中的信息无需secret解密也能获得
 *
 * @return token中包含的用户名
 */
public static String getUsername(String token) {
	try {
		DecodedJWT jwt = JWT.decode(token);
		return jwt.getClaim("username").asString();
	} catch (JWTDecodeException e) {
		return null;
	}
}
 
Example #30
Source File: AuthenticationJsonWebTokenTest.java    From auth0-spring-security-api with MIT License 5 votes vote down vote up
@Test
public void shouldGetStringToken() throws Exception {
    String token = JWT.create()
            .withIssuer("auth0")
            .sign(hmacAlgorithm);

    AuthenticationJsonWebToken auth = new AuthenticationJsonWebToken(token, verifier);
    assertThat(auth, is(notNullValue()));
    assertThat(auth.getToken(), is(token));
}