Files
fullstack-starter/docs/工具箱端-授权对接指南/utils/JwtUtil.kt

51 lines
1.5 KiB
Kotlin
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
) {
// 生成签名 KeyHS256
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
}
}