docs: 添加管理平台标准加密算法 Kotlin 参考实现
This commit is contained in:
50
docs/工具箱端-授权对接指南/utils/JwtUtil.kt
Normal file
50
docs/工具箱端-授权对接指南/utils/JwtUtil.kt
Normal file
@@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user