@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 shouldAddIssuedAt() throws Exception { String signed = JWTCreator.init() .withIssuedAt(new Date(1477592000)) .sign(Algorithm.HMAC256("secret")); assertThat(signed, is(notNullValue())); assertThat(TokenUtils.splitToken(signed)[1], is("eyJpYXQiOjE0Nzc1OTJ9")); }
public static String createToken(Map<String, String> data, Date expireTime) throws UnsupportedEncodingException { Map<String, Object> map = Maps.newHashMap(); map.put("alg", "HS256"); map.put("typ", "JWT"); if (data == null) { data = new HashMap<>(0); } // 过期时间 Date now = new Date(); if (expireTime == null) { Calendar time = Calendar.getInstance(); time.add(Calendar.DATE, DEFAULT_EXPIRE_DAYS); expireTime = time.getTime(); } JWTCreator.Builder builder = JWT.create().withHeader(map).withClaim("iss", data.containsKey("iss") ? data.remove("iss") : DEFAULT_ISS); for (Map.Entry<String, String> entry : data.entrySet()) { builder = builder.withClaim(entry.getKey(), entry.getValue()); } String token = builder.withIssuedAt(now) .withExpiresAt(expireTime) .sign(Algorithm.HMAC256(SECRET)); return token; }
.withIssuer(clientId) .withAudience(oAuthBasePath) .withIssuedAt(new Date(now)) .withClaim("scope", scopes) .withExpiresAt(new Date(now + expiresIn * 1000));
@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; }
/** * WT生成Token. * @param obj * @return str */ public String createToken(Object obj) { Date iatDate = new Date(); // expire time Calendar nowTime = Calendar.getInstance(); nowTime.add(calendarField, calendarInterval); Date expiresDate = nowTime.getTime(); // header Map Map<String, Object> map = new HashMap<>(); map.put("alg", "HS256"); map.put("typ", "JWT"); // header JWTCreator.Builder builder = JWT.create().withHeader(map); // payload JSONObject json = JSONObject.parseObject(JSON.toJSONString(obj)); for (String key : json.keySet()) { builder.withClaim(key, json.get(key).toString()); } builder.withIssuedAt(iatDate); // sign time builder.withExpiresAt(expiresDate); // expire time String token = builder.sign(Algorithm.HMAC256(SECRET)); // signature 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; }
@Override public String createJWT(Map<String, String> data) { Assert.notNull(apiConfig, "apiConfig尚未初始化"); Builder builder = JWT.create().withHeader(headerClaims); Set<Entry<String, String>> entrySet = data.entrySet(); for (Entry<String, String> entry : entrySet) { builder.withClaim(entry.getKey(), entry.getValue()); } Calendar expiredTime = Calendar.getInstance(); expiredTime.add(Calendar.SECOND, apiConfig.getJwtExpireIn()); try { return builder // 过期时间 .withExpiresAt(expiredTime.getTime()) // 创建时间 .withIssuedAt(new Date()) // 签名 .sign(Algorithm.HMAC256(apiConfig.getJwtSecret())); } catch (Exception e) { logger.error(e.getMessage(), e); throw Errors.ERROR_OPT_JWT.getException(); } }
/** * 生成签名,expireTime后过期 * @param username 用户名 * @param time 过期时间s * @return 加密的token */ public static String sign(String username, String salt, long time) { try { Date date = new Date(System.currentTimeMillis()+time*1000); Algorithm algorithm = Algorithm.HMAC256(salt); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .withIssuedAt(new Date()) .sign(algorithm); } catch (UnsupportedEncodingException e) { return null; } }
public static String createToken(String username, String userId) { Map<String, Object> header = new HashMap<>(2); header.put("alg", "HS256"); header.put("typ", "JWT"); Calendar calendar = Calendar.getInstance(); Date now = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, 3); Date expireDate = calendar.getTime(); return JWT.create().withHeader(header) .withClaim("iss", "hera") .withClaim("aud", "2dfire") .withClaim("username", username) .withClaim("userId", userId) .withIssuedAt(now) .withExpiresAt(expireDate) .sign(algorithm); }
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()); } }
/** * 登录成功 * * @param userDetails 用户信息 * @return token */ public String loginSuccess(UserDetails userDetails) { Algorithm algorithm = Algorithm.HMAC256(salt); Date date = new Date(System.currentTimeMillis() + 3600 * 1000); return JWT.create() .withSubject(userDetails.getUsername()) .withExpiresAt(date) .withIssuedAt(new Date()) .sign(algorithm); }
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); }
@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); }