add PrivateJwtService

This commit is contained in:
2025-01-01 01:39:02 +01:00
parent f6dc766910
commit 90abefce22
3 changed files with 90 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
package ltd.hlaeja.jwt.service
import io.jsonwebtoken.Jwts
import java.security.interfaces.RSAPrivateKey
import ltd.hlaeja.jwt.util.PrivateKeyProvider
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Service
@Service
@ConditionalOnProperty(prefix = "jwt", name = ["private-key"])
class PrivateJwtService(
@Value("\${jwt.private-key}") jwtPrivateKey: String,
) {
private var privateKey: RSAPrivateKey = PrivateKeyProvider.load(jwtPrivateKey)
fun sign(
vararg claim: Pair<String, Any>,
): String = Jwts.builder()
.claims()
.also { claims -> claim.forEach { claims.add(it.first, it.second) } }
.and()
.signWith(privateKey)
.compact()
}

View File

@@ -0,0 +1,54 @@
package ltd.hlaeja.jwt.service
import java.util.Base64
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class PrivateJwtServiceTest {
private lateinit var service: PrivateJwtService
@BeforeEach
fun setup() {
service = PrivateJwtService("cert/valid-private-key.pem")
}
@Test
fun `make token with claims`() {
// given
val claim1 = "claim1" to "value1"
val claim2 = "claim2" to 123
// when
val token = service.sign(claim1, claim2)
// then
assertThat(token).isNotEmpty()
val parts = token.split("\\.".toRegex())
assertThat(parts).hasSize(3)
val header = String(Base64.getDecoder().decode(parts[0]))
val payload = String(Base64.getDecoder().decode(parts[1]))
assertThat(header).contains("RS256")
assertThat(payload).contains("\"claim1\":\"value1\"", "\"claim2\":123")
}
@Test
fun `make token with no claims`() {
// when
val token = service.sign()
// then
assertThat(token).isNotEmpty()
val parts = token.split("\\.".toRegex())
assertThat(parts).hasSize(3)
val header = String(Base64.getDecoder().decode(parts[0]))
val payload = String(Base64.getDecoder().decode(parts[1]))
assertThat(header).contains("RS256")
assertThat(payload).isEmpty()
}
}