JWT 做token的校验,非常的方便,具体作用可以google查一下,这里只记录怎么使用 1、引入jwt的依赖
/**
* java-jwt
*/
implementation("com.auth0:java-jwt:3.18.1")
2、编写JWT的工具类
@Component
@Slf4j
class JwtUtil(val jwtProperties: JwtProperties){
open fun validateToken(authToken: String?): Boolean {
val algorithm: Algorithm = Algorithm.HMAC512(jwtProperties.secret)
val verifier = JWT.require(algorithm).build()
try {
verifier.verify(authToken)
return true
} catch (e: JWTVerificationException) {
log.warn("Invalid signature/claims :: {}", e.message)
}
return false
}
open fun extractUserFromJwt(token: String): Map<String?, Claim?>? {
val token = if (token.startsWith("Bearer ")) token.substring(7) else token
val verificationSucceeded =
validateToken(token)
if (!verificationSucceeded) {
throw Exception("Token was unauthorized")
}
try {
val jwt = JWT.decode(token)
return jwt.claims
} catch (e: JWTDecodeException) {
log.error("Failed to decode token", e)
}
return null
}
}
@Component
@ConfigurationProperties(prefix="jwt")
data class JwtProperties (
var header: String?=null,
var tokenHead: String?=null,
var secret: String?=null,
var expirationInMs: Long?=null
)
jwt:
header: "Authorization"
tokenHead: "Bearer "
secret: XXXXXXXX
expirationInMs: 22133
3、JWT的使用
open class AliPayController (
val alipayTemplate: AlipayTemplate,
val platformOrderService:IPlatformOrderService,
val jwtUtil: JwtUtil
){
open fun payOrder(@RequestBody aliPayVo: AliPayVo,@RequestHeader("Authorization") token: String): String? {
val platformOrder = PlatformOrder()
platformOrder.tenantId = jwtUtil.extractUserFromJwt(token)!!["tenantId"]!!.asLong()
platformOrder.fromUserId = jwtUtil.extractUserFromJwt(token)!!["userId"]!!.asLong()
}
}
|