@Override public String createNewToken(UUID jobId) { try { return JWT.create() .withIssuer(JWTTokenManager.ISSUER) .withClaim(JWTTokenManager.ID_CLAIM_KEY, jobId.toString()) .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME_MILLIS)) .sign(algorithm); } catch (JWTCreationException e) { throw new RuntimeException("Error creating token for: " + jobId); } } }
@Override public String newId() { final Instant now = Instant.now(); final int un2 = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE) & 0x7fffffff; return JWT.create() .withIssuer(issuer) .withIssuedAt(Date.from(now)) .withExpiresAt(Date.from(now.plus(validSeconds, ChronoUnit.SECONDS))) // To make multiple tokens issued in the same second unique, we add uniquifiers. .withClaim(CLAIM_NAME_UNIQUIFIER1, un1) .withClaim(CLAIM_NAME_UNIQUIFIER2, un2) .sign(algorithm); }
/** * 生成签名,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); }
public String createJWT(Map<String, String> map) { String sign = null; try { Date date = DateUtils.addDateDays(new Date(), 1); JWTCreator.Builder builder = JWT.create(); map.forEach((k, v) -> { builder.withClaim(k, v); }); sign = builder.withIssuer(ISSUER).withExpiresAt(date).sign(Algorithm.HMAC256(SECRET)); } catch (UnsupportedEncodingException e) { logger.error("create jwt error:{}", e); } return sign; }
@Override public String digestParams(RestInvocation restInvocation) { String path = "/" + restInvocation.getMethodPath(); String queryString = restInvocation.getQueryString(); if (queryString != null && queryString.length() > 0) path += "?" + restInvocation.getQueryString(); return builder .withClaim("path", path) .withClaim("nonce", String.valueOf(nonceFactory.createValue())) .withClaim("token_id", tokenID) .sign(Algorithm.HMAC256(userSecret)); } }
protected String createToken() { try { JWTCreator.Builder _create = JWT.create(); final Procedure1<JWTCreator.Builder> _function = (JWTCreator.Builder it) -> { it.withClaim("id", "johndoe"); it.withClaim("name", "John Doe"); it.withClaim("email", "john@example.org"); }; final JWTCreator.Builder builder = ObjectExtensions.<JWTCreator.Builder>operator_doubleArrow(_create, _function); return builder.sign(Algorithm.HMAC256("secret")); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
private String createToken() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); Algorithm algorithm = Algorithm.RSA256(( RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate()); return JWT.create() .withExpiresAt(Date.from(Instant.now().plusSeconds(120))) .withClaim("uid", "test") .sign(algorithm); }
@Override public String newId() { final Instant now = Instant.now(); final int un2 = ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE) & 0x7fffffff; return JWT.create() .withIssuer(issuer) .withIssuedAt(Date.from(now)) .withExpiresAt(Date.from(now.plus(validSeconds, ChronoUnit.SECONDS))) // To make multiple tokens issued in the same second unique, we add uniquifiers. .withClaim(CLAIM_NAME_UNIQUIFIER1, un1) .withClaim(CLAIM_NAME_UNIQUIFIER2, un2) .sign(algorithm); }
String generateJWT(final SmockinUser user) { return JWT.create() .withIssuer(jwtIssuer) .withClaim(jwtRoleKey, user.getRole().name()) .withClaim(jwtFullNameKey, user.getFullName()) .withClaim(jwtUserNameKey, user.getUsername()) .withSubject(jwtSubjectKey) .withIssuedAt(GeneralUtils.getCurrentDate()) .withExpiresAt(GeneralUtils.toDate(GeneralUtils.getCurrentDateTime().plusDays(99))) .sign(jwtAlgorithm); }
public static Optional<String> getToken(MCRUserInformation userInformation, String remoteIp) { ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC); return Optional.ofNullable(userInformation) .map(MCRJWTUtil::getJWTBuilder) .map(b -> { return b.withAudience(AUDIENCE) .withClaim(MCRJWTUtil.JWT_CLAIM_IP, remoteIp) .withExpiresAt(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant())) .withNotBefore(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())) .sign(MCRJWTUtil.getJWTAlgorithm()); }); }
/** * 生成签名,5min后过期 * @param username 用户名 * @param secret 用户的密码 * @return 加密的token */ public static String sign(String username, String secret) { try { Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } catch (UnsupportedEncodingException e) { return null; } } }
@Test public void shouldAcceptCustomClaimOfTypeDouble() throws Exception { String jwt = JWTCreator.init() .withClaim("name", 23.45) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjoyMy40NX0")); }
@Test public void shouldAcceptCustomClaimOfTypeString() throws Exception { String jwt = JWTCreator.init() .withClaim("name", "value") .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjoidmFsdWUifQ")); }
@Override public String digestParams(RestInvocation restInvocation) { String path = "/" + restInvocation.getMethodPath(); String queryString = restInvocation.getQueryString(); if (queryString != null && queryString.length() > 0) path += "?" + restInvocation.getQueryString(); return builder .withClaim("path", path) .withClaim("nonce", String.valueOf(nonceFactory.createValue())) .withClaim("token_id", tokenID) .sign(Algorithm.HMAC256(userSecret)); } }
@Test public void shouldAcceptCustomClaimOfTypeDate() throws Exception { Date date = new Date(1478891521000L); String jwt = JWTCreator.init() .withClaim("name", date) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjoxNDc4ODkxNTIxfQ")); }
@Test public void shouldAcceptCustomClaimOfTypeLong() throws Exception { String jwt = JWTCreator.init() .withClaim("name", Long.MAX_VALUE) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjo5MjIzMzcyMDM2ODU0Nzc1ODA3fQ")); }
@Test public void shouldThrowOnNullCustomClaimName() throws Exception { exception.expect(IllegalArgumentException.class); exception.expectMessage("The Custom Claim's name can't be null."); JWTCreator.init() .withClaim(null, "value"); }
@Test public void shouldAcceptCustomClaimOfTypeBoolean() throws Exception { String jwt = JWTCreator.init() .withClaim("name", true) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjp0cnVlfQ")); }
@Test public void shouldAcceptCustomClaimOfTypeInteger() throws Exception { String jwt = JWTCreator.init() .withClaim("name", 123) .sign(Algorithm.HMAC256("secret")); assertThat(jwt, is(notNullValue())); String[] parts = jwt.split("\\."); assertThat(parts[1], is("eyJuYW1lIjoxMjN9")); }