public String getBearerToken(String subject) { checkState(jwtSigner.isPresent(), "not configured"); JwtBuilder jwt = Jwts.builder() .setSubject(subject) .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant())); jwtSigner.get().accept(jwt); jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId)); jwtIssuer.ifPresent(jwt::setIssuer); jwtAudience.ifPresent(jwt::setAudience); return jwt.compact(); }
/** * Create token * * @param authentication auth info * @return token */ public String createToken(Authentication authentication) { /** * Current time */ long now = (new Date()).getTime(); /** * Validity date */ Date validity; validity = new Date(now + this.tokenValidityInMilliseconds); /** * create token */ return Jwts.builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, "") .setExpiration(validity) .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); }
/** * 生成token */ private static String doGenerateToken(Map<String, Object> claims, String subject) { final Date createdDate = new Date(); final Date expirationDate = new Date(createdDate.getTime() + JwtConstants.EXPIRATION * 1000); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(createdDate) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, JwtConstants.SECRET) .compact(); }
public String createJWT(String id, String subject, long ttlMillis) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); SecretKey key = jwtConfig.generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(now) .setSubject(subject) .signWith(signatureAlgorithm, key); if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } }
/** * 根据负责生成JWT的token */ private String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
String encode(JwtSession jwtSession) { checkIsStarted(); long now = system2.now(); JwtBuilder jwtBuilder = Jwts.builder() .setId(uuidFactory.create()) .setSubject(jwtSession.getUserLogin()) .setIssuedAt(new Date(now)) .setExpiration(new Date(now + jwtSession.getExpirationTimeInSeconds() * 1000)) .signWith(SIGNATURE_ALGORITHM, secretKey); for (Map.Entry<String, Object> entry : jwtSession.getProperties().entrySet()) { jwtBuilder.claim(entry.getKey(), entry.getValue()); } return jwtBuilder.compact(); }
.claim(USERNAME_CLAIM, username) .claim(KEY_ID_CLAIM, key.getId()) .setExpiration(expiration.getTime()) .setIssuedAt(Calendar.getInstance().getTime()) .signWith(SIGNATURE_ALGORITHM, keyBytes).compact();
private String doGenerateToken(Map<String, Object> claims, String subject) { final Date createdDate = clock.now(); final Date expirationDate = calculateExpirationDate(createdDate); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(createdDate) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
@Test public void return_no_token_when_expiration_date_is_reached() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuedAt(new Date(system2.now())) .setExpiration(new Date(system2.now())) .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); assertThat(underTest.decode(token)).isEmpty(); }
@Test public void return_no_token_when_secret_key_has_changed() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setSubject(USER_LOGIN) .setIssuedAt(new Date(system2.now())) .setExpiration(new Date(system2.now() + 20 * 60 * 1000)) .signWith(SignatureAlgorithm.HS256, decodeSecretKey("LyWgHktP0FuHB2K+kMs3KWMCJyFHVZDdDSqpIxAMVaQ=")) .compact(); assertThat(underTest.decode(token)).isEmpty(); }
@Test public void testExpiredToken() throws Exception { // create keypair KeyPair kp = RsaProvider.generateKeyPair(1024); PublicKey publicKey = kp.getPublic(); PrivateKey privateKey = kp.getPrivate(); // create provider with private key ApigeeSSO2Provider provider = new MockApigeeSSO2Provider(); provider.setManagement( setup.getMgmtSvc() ); provider.setPublicKey( publicKey ); // create user, claims and a token for those things User user = createUser(); long exp = System.currentTimeMillis() - 1500; Map<String, Object> claims = createClaims( user.getUsername(), user.getEmail(), exp ); String token = Jwts.builder() .setClaims(claims) .setExpiration( new Date() ) .signWith( SignatureAlgorithm.RS256, privateKey) .compact(); Thread.sleep(500); // wait for claims to timeout // test that token is expired try { provider.validateAndReturnTokenInfo( token, 86400L ); Assert.fail("Should have failed due to expired token"); } catch ( BadTokenException e ) { Assert.assertTrue( e.getCause() instanceof ExpiredJwtException ); } }
@Test public void fail_to_decode_token_when_no_subject() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuer("sonarqube") .setIssuedAt(new Date(system2.now())) .setExpiration(new Date(system2.now() + 20 * 60 * 1000)) .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); expectedException.expect(authenticationException().from(Source.jwt()).withoutLogin().andNoPublicMessage()); expectedException.expectMessage("Token subject hasn't been found"); underTest.decode(token); }
@Test public void fail_to_decode_token_when_no_id() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setSubject(USER_LOGIN) .setIssuer("sonarqube") .setIssuedAt(new Date(system2.now())) .setExpiration(new Date(system2.now() + 20 * 60 * 1000)) .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); expectedException.expectMessage("Token id hasn't been found"); underTest.decode(token); }
@Test public void fail_to_decode_token_when_no_creation_date() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setSubject(USER_LOGIN) .setExpiration(new Date(system2.now() + 20 * 60 * 1000)) .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); expectedException.expectMessage("Token creation date hasn't been found"); underTest.decode(token); }
/** * 获取Token * @param uid 用户ID * @param exp 失效时间,单位分钟 * @return */ public static String getToken(String uid, int exp) { long endTime = System.currentTimeMillis() + 1000 * 60 * exp; return Jwts.builder().setSubject(uid).setExpiration(new Date(endTime)) .signWith(SignatureAlgorithm.RS512, priKey).compact(); }
/** * 获取Token * @param uid 用户ID * @return */ public String getToken(String uid) { long endTime = System.currentTimeMillis() + 1000 * 60 * 1440; return Jwts.builder().setSubject(uid).setExpiration(new Date(endTime)) .signWith(SignatureAlgorithm.RS512, priKey).compact(); }
public JwtToken createRefreshToken(UserContext userContext) { if (StringUtils.isBlank(userContext.getUsername())) { throw new IllegalArgumentException("Cannot create JWT Token without username"); } LocalDateTime currentTime = LocalDateTime.now(); Claims claims = Jwts.claims().setSubject(userContext.getUsername()); claims.put("scopes", Arrays.asList(Scopes.REFRESH_TOKEN.authority())); String token = Jwts.builder() .setClaims(claims) .setIssuer(settings.getTokenIssuer()) .setId(UUID.randomUUID().toString()) .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant())) .setExpiration(Date.from(currentTime .plusMinutes(settings.getRefreshTokenExpTime()) .atZone(ZoneId.systemDefault()).toInstant())) .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()) .compact(); return new AccessJwtToken(token, claims); } }
/** * Factory method for issuing new JWT Tokens. * * @param username * @param roles * @return */ public AccessJwtToken createAccessJwtToken(UserContext userContext) { if (StringUtils.isBlank(userContext.getUsername())) throw new IllegalArgumentException("Cannot create JWT Token without username"); if (userContext.getAuthorities() == null || userContext.getAuthorities().isEmpty()) throw new IllegalArgumentException("User doesn't have any privileges"); Claims claims = Jwts.claims().setSubject(userContext.getUsername()); claims.put("scopes", userContext.getAuthorities().stream().map(s -> s.toString()).collect(Collectors.toList())); LocalDateTime currentTime = LocalDateTime.now(); String token = Jwts.builder() .setClaims(claims) .setIssuer(settings.getTokenIssuer()) .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant())) .setExpiration(Date.from(currentTime .plusMinutes(settings.getTokenExpirationTime()) .atZone(ZoneId.systemDefault()).toInstant())) .signWith(SignatureAlgorithm.HS512, settings.getTokenSigningKey()) .compact(); return new AccessJwtToken(token, claims); }
/** * 从用户中创建一个jwt Token * * @param userDTO 用户 * @return token */ public String create(TokenUserDTO userDTO) { return Jwts.builder() .setExpiration(new Date(System.currentTimeMillis() + VALIDITY_TIME_MS)) .setSubject(userDTO.getUsername()) .claim("id", userDTO.getId()) .claim("avatar", userDTO.getAvatar()) .claim("email", userDTO.getEmail()) .claim("roles", userDTO.getRoles()) .signWith(SignatureAlgorithm.HS256, secret) .compact(); }
/** * 生成 Token * * @param userDetails 用户信息 * @return String */ public String generateToken(UserDetails userDetails) { String token = Jwts.builder() .setSubject(userDetails.getUsername()) .setExpiration(generateExpired()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); String key = REDIS_PREFIX_AUTH + userDetails.getUsername(); redisRepository.setExpire(key, token, expiration); putUserDetails(userDetails); return token; }