/** * 根据负责生成JWT的token */ private String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
@Test public void fail_to_decode_token_when_no_expiration_date() { setSecretKey(A_SECRET_KEY); underTest.start(); String token = Jwts.builder() .setId("123") .setIssuer("sonarqube") .setSubject(USER_LOGIN) .setIssuedAt(new Date(system2.now())) .signWith(SignatureAlgorithm.HS256, decodeSecretKey(A_SECRET_KEY)) .compact(); expectedException.expect(authenticationException().from(Source.jwt()).withLogin(USER_LOGIN).andNoPublicMessage()); expectedException.expectMessage("Token expiration date hasn't been found"); underTest.decode(token); }
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(); }
@Test(expectedExceptions = SQLException.class, expectedExceptionsMessageRegExp = "Authentication failed: Unsigned Claims JWTs are not supported.") public void testFailedUnsigned() throws Exception { String accessToken = Jwts.builder() .setSubject("test") .compact(); try (Connection connection = createConnection(ImmutableMap.of("accessToken", accessToken))) { try (Statement statement = connection.createStatement()) { statement.execute("SELECT 123"); } } }
public String generateToken(User user, Date expiry) { if (expiry == null) { expiry = new Date(System.currentTimeMillis() + DEFAULT_EXPIRY); } JwtBuilder builder = this.newToken(user.getUsername(), expiry) .claim(USER_ID_CLAIM, user.getId()) .claim(USER_TOKEN_VERSION_CLAIM, user.getTokenVersion()); return this.sign(builder); }
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); } }
private String issueToken(String login) { Key key = keyGenerator.generateKey(); ZonedDateTime now = ZonedDateTime.now(); return Jwts.builder() .signWith(SignatureAlgorithm.HS512, key) .compressWith(CompressionCodecs.DEFLATE) .setSubject(login) .setIssuer(uriInfo.getAbsolutePath().toString()) .setIssuedAt(Date.from(now.toInstant())) .setExpiration(Date.from(now.plusMinutes(tokenValidity).toInstant())) .compact(); } }
private static Optional<Consumer<JwtBuilder>> setupJwtSigner(File file, String password) { if (file == null) { return Optional.empty(); } try { PrivateKey key = PemReader.loadPrivateKey(file, Optional.ofNullable(password)); if (!(key instanceof RSAPrivateKey)) { throw new IOException("Only RSA private keys are supported"); } return Optional.of(jwt -> jwt.signWith(SignatureAlgorithm.RS256, key)); } catch (IOException e) { throw new RuntimeException("Failed to load key file: " + file, e); } catch (GeneralSecurityException ignored) { } try { byte[] base64Key = readAllBytes(file.toPath()); byte[] key = Base64.getMimeDecoder().decode(base64Key); return Optional.of(jwt -> jwt.signWith(SignatureAlgorithm.HS256, key)); } catch (IOException | IllegalArgumentException e) { throw new RuntimeException("Failed to load key file: " + file, e); } } }
private static void processAuthPermissions(JwtBuilder builder, Authentication authentication) { builder.claim(AuthenticationClaims.CLAIM_NAME_ROOT, Boolean.valueOf(authentication.isRoot())); Collection<Permission> permissions = authentication.getPermissions(); if (permissions != null && !permissions.isEmpty()) { Collection<String> ps = new ArrayList<>(permissions.size()); for (Permission permission : permissions) { permission.getPermission().ifPresent(p -> ps.add(p)); } if (!ps.isEmpty()) { builder.claim(AuthenticationClaims.CLAIM_NAME_PERMISSIONS, ps); } } }
public String generateToken(User user, Date expirationDate) { if (expirationDate == null) { int expiryDuration = SystemSettingsDao.instance.getIntValue(EXPIRY_SYSTEM_SETTING, DEFAULT_EXPIRY_DURATION); expirationDate = new Date(System.currentTimeMillis() + expiryDuration * 1000); } JwtBuilder builder = this.newToken(user.getUsername(), expirationDate) .claim(USER_ID_CLAIM, user.getId()) .claim(USER_PASSWORD_VERSION_CLAIM, user.getPasswordVersion()); return this.sign(builder); }
/** * 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); }
/** * 生成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(); } }
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(); }
/** * 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(); }
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(); }
public String refreshToken(String token) { final Date createdDate = clock.now(); final Date expirationDate = calculateExpirationDate(createdDate); final Claims claims = getAllClaimsFromToken(token); claims.setIssuedAt(createdDate); claims.setExpiration(expirationDate); return Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, secret) .compact(); }
@Test(expectedExceptions = SQLException.class, expectedExceptionsMessageRegExp = "Authentication failed: Unknown signing key ID") public void testFailedUnknownPublicKey() throws Exception { String accessToken = Jwts.builder() .setSubject("test") .setHeaderParam(KEY_ID, "unknown") .signWith(SignatureAlgorithm.RS256, privateKey33) .compact(); try (Connection connection = createConnection(ImmutableMap.of("accessToken", accessToken))) { try (Statement statement = connection.createStatement()) { statement.execute("SELECT 123"); } } }
@Test(expectedExceptions = SQLException.class, expectedExceptionsMessageRegExp = "Authentication failed: JWT signature does not match.*") public void testFailedWrongPublicKey() throws Exception { String accessToken = Jwts.builder() .setSubject("test") .setHeaderParam(KEY_ID, "42") .signWith(SignatureAlgorithm.RS256, privateKey33) .compact(); try (Connection connection = createConnection(ImmutableMap.of("accessToken", accessToken))) { try (Statement statement = connection.createStatement()) { statement.execute("SELECT 123"); } } }