Adds JWT-based auth with refresh tokens
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
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.Date
|
||||
import javax.crypto.SecretKey
|
||||
|
||||
@Component
|
||||
class JwtUtil {
|
||||
@Value($$"${jwt.secret}")
|
||||
private val jwtSecret: String? = null
|
||||
|
||||
@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 = Jwts.SIG.HS256.key().build()
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user