51 lines
1.5 KiB
Kotlin
51 lines
1.5 KiB
Kotlin
package top.tangyh.lamp.filing.utils
|
||
|
||
import io.jsonwebtoken.Jwts
|
||
import io.jsonwebtoken.SignatureAlgorithm
|
||
import io.jsonwebtoken.security.Keys
|
||
import org.springframework.beans.factory.annotation.Value
|
||
import org.springframework.stereotype.Component
|
||
import java.time.LocalDateTime
|
||
import java.time.ZoneId
|
||
import java.util.*
|
||
import javax.crypto.SecretKey
|
||
|
||
@Component
|
||
class JwtUtil(
|
||
@Value("\${jwt.secret}")
|
||
private val secretKey: String
|
||
) {
|
||
|
||
|
||
// 生成签名 Key(HS256)
|
||
private val signingKey: SecretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(secretKey))
|
||
|
||
/**
|
||
* 生成 Token
|
||
* */
|
||
fun generateToken(subject: String, claims: Map<String, Any> = emptyMap(), expireDays: Long = 7): String {
|
||
val now = LocalDateTime.now()
|
||
val expiration = now.plusDays(expireDays)
|
||
|
||
return Jwts.builder()
|
||
.setSubject(subject)
|
||
.setClaims(claims)
|
||
.setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant()))
|
||
.setExpiration(Date.from(expiration.atZone(ZoneId.systemDefault()).toInstant()))
|
||
.signWith(signingKey, SignatureAlgorithm.HS256)
|
||
.compact()
|
||
}
|
||
|
||
|
||
/**
|
||
* 解析 Token 获取 Claims
|
||
*/
|
||
fun parseToken(token: String): Map<String, Any> {
|
||
return Jwts.parserBuilder()
|
||
.setSigningKey(signingKey)
|
||
.build()
|
||
.parseClaimsJws(token)
|
||
.body
|
||
}
|
||
}
|