63 lines
1.9 KiB
Kotlin
63 lines
1.9 KiB
Kotlin
package net.halfbinary.scavengerhuntapi.config
|
|
|
|
import io.jsonwebtoken.JwtException
|
|
import io.jsonwebtoken.Jwts
|
|
import jakarta.annotation.PostConstruct
|
|
import org.springframework.beans.factory.annotation.Value
|
|
import org.springframework.stereotype.Component
|
|
import java.util.*
|
|
import javax.crypto.SecretKey
|
|
import javax.crypto.spec.SecretKeySpec
|
|
|
|
@Component
|
|
class JwtUtil {
|
|
@Value($$"${jwt.secret}")
|
|
private val jwtSecret: String = ""
|
|
|
|
@Value($$"${jwt.expiration}")
|
|
private val jwtExpirationMs = 0
|
|
|
|
private var key: SecretKey? = null
|
|
|
|
// Initializes the key after the class is instantiated and the jwtSecret is injected,
|
|
// preventing the repeated creation of the key and enhancing performance
|
|
@PostConstruct
|
|
fun init() {
|
|
this.key = SecretKeySpec(jwtSecret.toByteArray(Charsets.UTF_8), "HmacSHA256")
|
|
}
|
|
|
|
// Generate JWT token
|
|
fun generateToken(email: String): String {
|
|
return Jwts.builder()
|
|
.subject(email)
|
|
.issuedAt(Date())
|
|
.expiration(Date(System.currentTimeMillis() + jwtExpirationMs))
|
|
.signWith(key)
|
|
.compact()
|
|
}
|
|
|
|
// Get username from JWT token
|
|
fun getUsernameFromToken(token: String): String {
|
|
return Jwts.parser()
|
|
.verifyWith(key)
|
|
.build()
|
|
.parseSignedClaims(token)
|
|
.payload
|
|
.subject
|
|
}
|
|
|
|
// Validate JWT token
|
|
fun validateJwtToken(token: String?): Boolean {
|
|
try {
|
|
Jwts.parser().verifyWith(key).build().parseSignedClaims(token)
|
|
return true
|
|
} catch (e: SecurityException) {
|
|
println("Invalid JWT signature: " + e.message)
|
|
} catch (e: JwtException) {
|
|
println("Invalid JWT token: " + e.message)
|
|
} catch (e: IllegalArgumentException) {
|
|
println("JWT claims string is empty: " + e.message)
|
|
}
|
|
return false
|
|
}
|
|
} |