mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-23 14:40:49 +08:00
48 lines
1.3 KiB
Java
48 lines
1.3 KiB
Java
package com.openisle.service;
|
|
|
|
import io.jsonwebtoken.Claims;
|
|
import io.jsonwebtoken.Jwts;
|
|
import io.jsonwebtoken.SignatureAlgorithm;
|
|
import io.jsonwebtoken.io.Decoders;
|
|
import io.jsonwebtoken.io.Encoders;
|
|
import io.jsonwebtoken.security.Keys;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.security.Key;
|
|
import java.util.Date;
|
|
|
|
@Service
|
|
public class JwtService {
|
|
@Value("${app.jwt.secret}")
|
|
private String secret;
|
|
|
|
@Value("${app.jwt.expiration}")
|
|
private long expiration;
|
|
|
|
private Key getSigningKey() {
|
|
byte[] keyBytes = Encoders.BASE64.encode(secret.getBytes()).getBytes();
|
|
return Keys.hmacShaKeyFor(keyBytes);
|
|
}
|
|
|
|
public String generateToken(String subject) {
|
|
Date now = new Date();
|
|
Date expiryDate = new Date(now.getTime() + expiration);
|
|
return Jwts.builder()
|
|
.setSubject(subject)
|
|
.setIssuedAt(now)
|
|
.setExpiration(expiryDate)
|
|
.signWith(getSigningKey())
|
|
.compact();
|
|
}
|
|
|
|
public String validateAndGetSubject(String token) {
|
|
Claims claims = Jwts.parserBuilder()
|
|
.setSigningKey(getSigningKey())
|
|
.build()
|
|
.parseClaimsJws(token)
|
|
.getBody();
|
|
return claims.getSubject();
|
|
}
|
|
}
|