下面列出了怎么用io.jsonwebtoken.security.Keys的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 为指定用户生成token
*
* @param user 用户信息
* @return token
*/
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>(3);
claims.put(USER_ID, user.getId());
claims.put(USERNAME, user.getUsername());
claims.put(ROLES, user.getRoles());
Date createdTime = new Date();
Date expirationTime = this.getExpirationTime();
byte[] keyBytes = this.lightSecurityProperties.getJwt().getSecret().getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdTime)
.setExpiration(expirationTime)
.signWith(key)
.compact();
}
/**
* 为指定用户生成token
*
* @param user 用户信息
* @return token
*/
public String generateToken(User user) {
Map<String, Object> claims = new HashMap<>(3);
claims.put(USER_ID, user.getId());
claims.put(USERNAME, user.getUsername());
claims.put(ROLES, user.getRoles());
Date createdTime = new Date();
Date expirationTime = this.getExpirationTime();
byte[] keyBytes = this.reactiveLightSecurityProperties.getJwt().getSecret().getBytes();
SecretKey key = Keys.hmacShaKeyFor(keyBytes);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(createdTime)
.setExpiration(expirationTime)
.signWith(key)
.compact();
}
@Override
public void afterPropertiesSet() throws Exception {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain, Authentication authentication) {
var user = ((User) authentication.getPrincipal());
var roles = user.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
var signingKey = SecurityConstants.JWT_SECRET.getBytes();
var token = Jwts.builder()
.signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
.setHeaderParam("typ", SecurityConstants.TOKEN_TYPE)
.setIssuer(SecurityConstants.TOKEN_ISSUER)
.setAudience(SecurityConstants.TOKEN_AUDIENCE)
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.claim("rol", roles)
.compact();
response.addHeader(SecurityConstants.TOKEN_HEADER, SecurityConstants.TOKEN_PREFIX + token);
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
public static String getJwt(String issuer, String nonce, Date expiredDate, Date issuedAt,
String... audience) {
JwtBuilder builder = Jwts.builder();
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
Map<String, Object> map = new HashMap<>();
map.put(Claims.AUDIENCE, Arrays.asList(audience));
return builder
.addClaims(map)
.claim("nonce", nonce)
.setIssuer(issuer)
.setSubject("sub")
.setExpiration(expiredDate)
.setIssuedAt(issuedAt)
.signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
.compact();
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
public static String getValidTokenResponse(String baseUrl, String nonce) {
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
Map<String,Object> additionalParameters = new HashMap<>();
additionalParameters.put("nonce", nonce);
String jws = Jwts.builder()
.setSubject(TEST_CLIENT_ID)
.setAudience(TEST_CLIENT_ID)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + 24*60*60*1000))
.setIssuer(baseUrl+"/")
.addClaims(additionalParameters)
.signWith(keyPair.getPrivate()).compact();
return "{" +
"\"access_token\":\"eyJraWQiOiJHYjl2VDBSS0xPWjYyYmN6WVFJckJtY0FBYkVUcDJaVTdudWVCVFlsUkdVIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULlY4UmdqQUhabWFXUzkxZEFORHpJNmFFdVVFeDNHYUpXTVdzXzExMlRPRjAiLCJpc3MiOiJodHRwczovL2xvaGlrYS11bS5va3RhcHJldmlldy5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiJhcGk6Ly9kZWZhdWx0IiwiaWF0IjoxNTQ1NDAwMDIxLCJleHAiOjE1NDU0ODY0MjEsImNpZCI6IjBvYWhuemhzZWd6WWpxRVRjMGg3IiwidWlkIjoiMDB1aHR3c3JyaUFDNXVpNDcwaDciLCJzY3AiOlsib3BlbmlkIiwicHJvZmlsZSJdLCJzdWIiOiJpbWFydHNla2hhQGxvaGlrYS5jb20ifQ.Bp-r0st5yyMFLKqoheh3mUTH_JhqubfBWXABWwApBoB_QqMB05EDskIBAhKfyc3KGMynoBK7fftP1KwNBhznYBQWUeueyXb5oHhKkPDYj8ds5Leu4758gLIDW2Ybj_eWspCR6aC1-eGWQZ-IbMz_rEpElmYC9TTXRPFngderPvqNW3dFU7VNJN-NFI18qEMRNf8-bIS8Qp9M1cU0WGKGi1wFDdgPM3761_R8beGMlWvulyA9B6mxZUs7M-ZxivJIdFbCKoFvxBo54ZBWXeMe-moEJA_tzXEuZf-Rq0mETwma-zBDCUWN3unZ51KRqEAtnZzGKDnt58on-olztbj1eA\"," +
"\"token_type\":\"Bearer\"," +
"\"expires_in\":86400," +
"\"scope\":\"openid profile\"," +
"\"id_token\":\""+jws+"\"" +
"}";
}
@Override
public void afterPropertiesSet() {
//Warning if the secret is still the default one
if ("s3cR3t4grAv1t3310AMS1g1ingDftK3y".equals(signingKeySecret)) {
LOGGER.warn("");
LOGGER.warn("##############################################################");
LOGGER.warn("# SECURITY WARNING #");
LOGGER.warn("##############################################################");
LOGGER.warn("");
LOGGER.warn("You still use the default jwt secret.");
LOGGER.warn("This known secret can be used to impersonate anyone.");
LOGGER.warn("Please change this value, or ask your administrator to do it !");
LOGGER.warn("");
LOGGER.warn("##############################################################");
LOGGER.warn("");
}
// init JWT signing key
key = Keys.hmacShaKeyFor(signingKeySecret.getBytes());
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@Test
public void testSerializeKeyPair() throws Exception {
KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
String privateKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPrivate());
String publicKey = AuthTokenUtils.encodeKeyBase64(keyPair.getPublic());
String token = AuthTokenUtils.createToken(AuthTokenUtils.decodePrivateKey(Decoders.BASE64.decode(privateKey), SignatureAlgorithm.RS256),
SUBJECT,
Optional.empty());
@SuppressWarnings("unchecked")
Jwt<?, Claims> jwt = Jwts.parser()
.setSigningKey(AuthTokenUtils.decodePublicKey(Decoders.BASE64.decode(publicKey), SignatureAlgorithm.RS256))
.parse(token);
assertNotNull(jwt);
assertNotNull(jwt.getBody());
assertEquals(jwt.getBody().getSubject(), SUBJECT);
}
@Test
public void testOne() throws NoSuchAlgorithmException, NoSuchProviderException {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String jws = Jwts.builder().setSubject("Joe").signWith(key).compact();
assertEquals(83, jws.length());
Matcher m = base64url_pattern.matcher(jws);
boolean good = m.find();
if (!good) {
System.out.println("Bad JWS:\n" + jws);
}
assertTrue(good);
String subject = Jwts.parser().setAllowedClockSkewSeconds(60).setSigningKey(key).parseClaimsJws(jws).getBody().getSubject();
assertEquals("Joe", subject);
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@Test
public void testOne() throws NoSuchAlgorithmException, NoSuchProviderException {
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String jws = Jwts.builder().setSubject("Joe").signWith(key).compact();
assertEquals(83, jws.length());
Matcher m = base64url_pattern.matcher(jws);
boolean good = m.find();
if (!good) {
System.out.println("Bad JWS:\n" + jws);
}
assertTrue(good);
String subject = Jwts.parser().setAllowedClockSkewSeconds(60).setSigningKey(key).parseClaimsJws(jws).getBody().getSubject();
assertEquals("Joe", subject);
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
private String generatorJWT(Long userId) {
Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes());
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, 2);
// 失效时间为2个月
return Jwts.builder().setSubject(ROLE)
.setId(String.valueOf(userId))
.setIssuedAt(new Date())
.setExpiration(calendar.getTime())
.signWith(key)
.compact();
}
/**
* 获取当前用户id
*/
public static Long currentUid(String jwt) {
Key key = Keys.hmacShaKeyFor(EncryConstant.SECRET.getBytes());
Long userId = null;
Date expireDate = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getExpiration();
if (expireDate.getTime() < new Date().getTime()) {
throw new LoginException(ErrorCodeEnum.AUTHENTICATION_EXPIRE);
}
try {
userId = Long.valueOf(Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody().getId());
} catch (JwtException e) {
throw new LoginException(ErrorCodeEnum.UNAUTHORIZED);
}
return userId;
}
@PostConstruct
public void init() {
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
String base64secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret();
byte[] keyBytes;
if (StringUtils.isEmpty(base64secret)) {
log.info("The JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
if (StringUtils.isEmpty(secret)) {
log.error("\n----------------------------------------------------------\n" +
"Your JWT secret key is not set up, you will not be able to log into the JHipster.\n"+
"Please read the documentation at https://www.jhipster.tech/jhipster-registry/\n" +
"----------------------------------------------------------");
throw new RuntimeException("No JWT secret key is configured, the application cannot start.");
}
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(base64secret);
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
@BeforeEach
public void setup() {
JHipsterProperties jHipsterProperties = new JHipsterProperties();
tokenProvider = new TokenProvider(jHipsterProperties);
ReflectionTestUtils.setField(tokenProvider, "key",
Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
jwtFilter = new JWTFilter(tokenProvider);
SecurityContextHolder.getContext().setAuthentication(null);
}
@BeforeEach
public void setup() {
tokenProvider = new TokenProvider( new JHipsterProperties());
key = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
ReflectionTestUtils.setField(tokenProvider, "key", key);
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
private String createTokenWithDifferentSignature() {
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
return Jwts.builder()
.setSubject("anonymous")
.signWith(otherKey, SignatureAlgorithm.HS512)
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
.compact();
}
@Override
public void afterPropertiesSet() {
byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
Key key = Keys.hmacShaKeyFor(keyBytes);
jwtParser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
jwtBuilder = Jwts.builder()
.signWith(key, SignatureAlgorithm.HS512);
}
@Before
public void setup() {
JHipsterProperties jHipsterProperties = new JHipsterProperties();
tokenProvider = new TokenProvider(jHipsterProperties);
ReflectionTestUtils.setField(tokenProvider, "key",
Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
jwtFilter = new JWTFilter(tokenProvider);
SecurityContextHolder.getContext().setAuthentication(null);
}
@Before
public void setup() {
jHipsterProperties = Mockito.mock(JHipsterProperties.class);
tokenProvider = new TokenProvider(jHipsterProperties);
key = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
ReflectionTestUtils.setField(tokenProvider, "key", key);
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
private String createTokenWithDifferentSignature() {
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
return Jwts.builder()
.setSubject("anonymous")
.signWith(otherKey, SignatureAlgorithm.HS512)
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
.compact();
}
private String generateToken(String issuer, Map<String, Object> claims) {
claims.merge(AuthConstant.REFRESH_COUNT, 0, (value, newValue) -> (Integer) value < 3 ? (Integer) value + 1 : value);
Integer refreshCount = (Integer) claims.get(AuthConstant.REFRESH_COUNT);
long expirationTimeLong = Long.parseLong(authProperties.getExpirationTime());
final Date createdDate = new Date();
final Date expirationDate = new Date(createdDate.getTime() + (refreshCount + 1) * expirationTimeLong * 1000);
return Jwts.builder()
.setIssuer(issuer)
.setClaims(claims)
.setIssuedAt(createdDate)
.setExpiration(expirationDate)
.signWith(Keys.hmacShaKeyFor(authProperties.getSecret().getBytes()))
.compact();
}
@PostConstruct
public void init() {
String secret = applicationProperties.getSecurity().getAuthentication().getJwt().getBase64Secret();
Assert.isTrue(StringUtil.isNotEmpty(secret), "jwt secret can not be empty");
byte[] keyBytes = Decoders.BASE64.decode(secret);
this.secretKey = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * applicationProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * applicationProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe();
}