@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); }
@Test public void shouldAddIssuer() throws Exception { String signed = JWTCreator.init() .withIssuer("auth0") .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJpc3MiOiJhdXRoMCJ9")); }
JWTCreator.Builder builder = JWT.create(); if (jwtProperty.getIssuer() != null) { builder.withIssuer(jwtProperty.getIssuer());
long now = System.currentTimeMillis(); token = JWT.create() .withIssuer(clientId) .withSubject(userId) .withAudience(oAuthBasePath)
long now = System.currentTimeMillis(); JWTCreator.Builder builder = JWT.create() .withIssuer(clientId) .withAudience(oAuthBasePath) .withIssuedAt(new Date(now))
@PermitAll public String generateAuthenticatorTokenForApplication(@NonNull Application application) { RsaKeyPair activeApplicationKey = null; try { activeApplicationKey = signingKKeyPairsProvider.getApplicationSigningKey(application); } catch (NoSigningKeyException e) { throw new AuthenticatorRuntimeException("No signing key to create authenticator token for application " + application.getName(), e); } Algorithm algorithm = getAlgorithm(activeApplicationKey); String[] audience = this.getMyApplicationAudiences(application); String[] applicationRoles = new String[]{ AuthenticatorConstants.ROLE_APPLICATION }; Date expirationDate = this.getNewTokenExpirationDate(); Date issuedDate = new Date(); String applicationName = application.getName(); String tokenId = this.generateNewTokenId(applicationName); String token = JWT.create() .withIssuer(tokenIssuer) .withKeyId(activeApplicationKey.getName()) .withSubject(AuthenticatorConstants.AUTHENTICAOTOR_PRINCIPAL_NAME) .withExpiresAt(expirationDate) .withIssuedAt(issuedDate) .withJWTId(tokenId) .withAudience(audience) .withClaim(AuthenticatorConstants.MP_JWT_USER_PRINCIPAL_CLAIM_NAME, AuthenticatorConstants.AUTHENTICAOTOR_PRINCIPAL_NAME) .withArrayClaim(AuthenticatorConstants.MP_JWT_GROUPS_CLAIM_NAME, applicationRoles) .sign(algorithm); return token; }
@RolesAllowed({AuthenticatorConstants.ROLE_USER}) public String generateUserTokenForApplication(@NonNull UserApplication userApplication) throws NoSigningKeyException, UnauthorizedOperationException { User user = userApplication.getUser(); Application application = userApplication.getApplication(); RsaKeyPair activeApplicationKey = signingKKeyPairsProvider.getApplicationSigningKey(application); Algorithm algorithm = getAlgorithm(activeApplicationKey); String[] audience = this.getApplicationAudience(application); String[] userRoles = findUserApplicationRoles(application, user); Date expirationDate = this.getNewTokenExpirationDate(); Date issuedDate = new Date(); String tokenId = this.generateNewTokenId(application.getName()); Long userId = user.getId(); String userName = user.getName(); String token = JWT.create() .withIssuer(tokenIssuer) .withKeyId(activeApplicationKey.getName()) .withSubject(userName) .withExpiresAt(expirationDate) .withIssuedAt(issuedDate) .withJWTId(tokenId) .withAudience(audience) .withClaim(AuthenticatorConstants.MP_JWT_USER_PRINCIPAL_CLAIM_NAME, userName) .withArrayClaim(AuthenticatorConstants.MP_JWT_GROUPS_CLAIM_NAME, userRoles) .withClaim(AuthenticatorConstants.USER_ID_CLAIM_NAME, userId) .sign(algorithm); return token; }
@RolesAllowed({AuthenticatorConstants.ROLE_ADMIN}) public String generateApplicationTokenForAuthenticator(@NonNull Application application) throws NoSigningKeyException { RsaKeyPair keyForApplicationSecrets = signingKKeyPairsProvider.getActiveAuthenticatorKeyForApplicationSecrets(); Algorithm algorithm = getAlgorithm(keyForApplicationSecrets); Long applicationId = application.getId(); String[] audience = this.getMyAudience(); String[] applicationRoles = new String[]{ AuthenticatorConstants.ROLE_APPLICATION, AuthenticatorConstants.ROLE_APPLICATION_RESTRICTION + applicationId, AuthenticatorConstants.ROLE_APP_MANAGEMENT, AuthenticatorConstants.ROLE_ACTIVE }; Date expirationDate = this.getApplicationSecretTokenExpirationDate(); Date issuedDate = new Date(); String tokenId = this.generateNewTokenId(""); String principalName = callerQueryService.createApplicationPrincipalName(application); String token = JWT.create() .withIssuer(tokenIssuer) .withKeyId(keyForApplicationSecrets.getName()) .withSubject(principalName) .withExpiresAt(expirationDate) .withIssuedAt(issuedDate) .withJWTId(tokenId) .withAudience(audience) .withClaim(AuthenticatorConstants.MP_JWT_USER_PRINCIPAL_CLAIM_NAME, principalName) .withArrayClaim(AuthenticatorConstants.MP_JWT_GROUPS_CLAIM_NAME, applicationRoles) .withClaim(AuthenticatorConstants.APPLICATION_ID_CLAIM_NAME, applicationId) .sign(algorithm); return token; }
@RolesAllowed({AuthenticatorConstants.ROLE_USER}) public String generateUserTokenForAuthenticator(@NonNull User user) throws NoSigningKeyException { RsaKeyPair activeProviderKey = signingKKeyPairsProvider.getAuthenticatorSigningKey(); Algorithm algorithm = getAlgorithm(activeProviderKey); String[] audience = this.getMyAudience(); String[] userRoles = findUserProviderRoles(user); Date expirationDate = this.getNewTokenExpirationDate(); Date issuedDate = new Date(); String tokenId = this.generateNewTokenId(""); Long userId = user.getId(); String userName = user.getName(); String token = JWT.create() .withIssuer(tokenIssuer) .withKeyId(activeProviderKey.getName()) .withSubject(userName) .withExpiresAt(expirationDate) .withIssuedAt(issuedDate) .withJWTId(tokenId) .withAudience(audience) .withClaim(AuthenticatorConstants.MP_JWT_USER_PRINCIPAL_CLAIM_NAME, userName) .withArrayClaim(AuthenticatorConstants.MP_JWT_GROUPS_CLAIM_NAME, userRoles) .withClaim(AuthenticatorConstants.USER_ID_CLAIM_NAME, userId) .sign(algorithm); return token; }
/** * * @param username 用户名 * @param secret 用户的密码 * @return 加密的token */ public static String sign(Long userId, String username, String secret, Long storeId) { try { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create() .withClaim("userId", userId) .withClaim("username", username) .withClaim("storeId", storeId) .withIssuer(ISSUER) .withExpiresAt(date) .sign(algorithm); } catch (UnsupportedEncodingException e) { return null; } }
@Override public synchronized IDevice create(_MatrixID user, String name) { // FIXME use RWLock String id; do { id = RandomStringUtils.randomAlphabetic(12); } while (devById.containsKey(id)); String token = JWT.create() .withIssuer(global.getDomain()) .withExpiresAt(Date.from(Instant.ofEpochMilli(Long.MAX_VALUE))) .withClaim(DeviceIdClaim, id) .withClaim(DeviceNameClaim, name) .withClaim(UserIdClaim, Objects.requireNonNull(user).getId()) .sign(jwtAlgo); IDevice dev = new Device(id, token, name, user); devById.put(id, dev); devByToken.put(token, dev); log.info("Created new device {} for user {}", id, user.getId()); return dev; }
public String genToken(Map<String, String> claims) { try { Algorithm algorithmHS = buildHMAC256(); JWTCreator.Builder jwtBuilder = JWT.create(); jwtBuilder.withSubject("waf-token") .withIssuer("yangguo.info"); //Set token expire time if (Optional.fromNullable(jwtExpireAfter).isPresent()) { DateTime nowTime = DateTime.now(); DateTime newTime = nowTime.plusMinutes(jwtExpireAfter); jwtBuilder.withExpiresAt(newTime.toDate()); } claims.entrySet().stream().forEach(claim -> { jwtBuilder.withClaim(claim.getKey(), String.valueOf(claim.getValue())); }); return jwtBuilder.sign(algorithmHS); } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); throw new RuntimeException(e); } }
public static String createToken(KeyPair keyPair, String issuer, Date issuedAt, Date expiresAt, String level) throws NoSuchAlgorithmException, NoSuchProviderException, DynamicLogLevelException { Algorithm rsa256 = Algorithm.RSA256((RSAPublicKey) keyPair.getPublic(), (RSAPrivateKey) keyPair.getPrivate()); if (ALLOWED_DYNAMIC_LOGLEVELS.contains(level)) { return JWT.create().withIssuer(issuer).// withIssuedAt(issuedAt). // withExpiresAt(expiresAt).// withClaim("level", level).sign(rsa256); } else { throw new DynamicLogLevelException("Dynamic Log-Level [" + level + "] provided in header is not valid. Allowed Values are " + ALLOWED_DYNAMIC_LOGLEVELS.toString()); } }
public String getToken(Principal p, UnaryOperator<JWTCreator.Builder> filler) { JWTCreator.Builder builder = JWT.create() .withIssuer(issuer) .withSubject(p.getName()) .withIssuedAt(new Date()); if (validity != null) { Instant end = ZonedDateTime.now(ZoneOffset.UTC).plus(validity).toInstant(); builder.withExpiresAt(Date.from(end)); } if (filler != null) { builder = filler.apply(builder); } return builder.sign(alg); }
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; }
public JWTBuilderImpl() { builder = JWT.create(); // default Nuxeo issuer, checked during validation builder.withIssuer(NUXEO_ISSUER); // default to current principal as subject String subject = ClientLoginModule.getCurrentPrincipal().getActingUser(); if (subject == null) { throw new NuxeoException("No currently logged-in user"); } builder.withSubject(subject); // default TTL withTTL(0); }
@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); }
@Test public void shouldRemoveClaimWhenPassingNull() throws Exception { String signed = JWTCreator.init() .withIssuer("iss") .withIssuer(null) .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("e30")); }