v1
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package com.hertz.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import javax.crypto.SecretKey;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class JwtService {
|
||||
private final SecretKey key;
|
||||
private final long expireSeconds;
|
||||
|
||||
public JwtService(
|
||||
@Value("${app.jwt.secret}") String secret,
|
||||
@Value("${app.jwt.expire-seconds}") long expireSeconds
|
||||
) {
|
||||
if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length < 32) {
|
||||
throw new IllegalArgumentException("app.jwt.secret 至少 32 字节");
|
||||
}
|
||||
this.key = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
|
||||
this.expireSeconds = expireSeconds;
|
||||
}
|
||||
|
||||
public String createToken(long userId, String username) {
|
||||
var now = Instant.now();
|
||||
return Jwts.builder()
|
||||
.subject(username)
|
||||
.claim("uid", userId)
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(now.plusSeconds(expireSeconds)))
|
||||
.signWith(key)
|
||||
.compact();
|
||||
}
|
||||
|
||||
public Claims parse(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(key)
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user