diff --git a/src/main/kotlin/ltd/hlaeja/service/JwtService.kt b/src/main/kotlin/ltd/hlaeja/service/JwtService.kt new file mode 100644 index 0000000..b09a952 --- /dev/null +++ b/src/main/kotlin/ltd/hlaeja/service/JwtService.kt @@ -0,0 +1,25 @@ +package ltd.hlaeja.service + +import io.jsonwebtoken.Jwts +import java.security.interfaces.RSAPrivateKey +import java.util.UUID +import ltd.hlaeja.property.JwtProperty +import ltd.hlaeja.util.PrivateKeyProvider +import org.springframework.stereotype.Service + +@Service +class JwtService( + jwtProperty: JwtProperty, +) { + + private var privateKey: RSAPrivateKey = PrivateKeyProvider.load(jwtProperty.privateKey) + + suspend fun makeIdentity(device: UUID): String { + return Jwts.builder() + .claims() + .add("device", device) + .and() + .signWith(privateKey) + .compact() + } +} diff --git a/src/test/kotlin/ltd/hlaeja/service/JwtServiceTest.kt b/src/test/kotlin/ltd/hlaeja/service/JwtServiceTest.kt new file mode 100644 index 0000000..0ac96ad --- /dev/null +++ b/src/test/kotlin/ltd/hlaeja/service/JwtServiceTest.kt @@ -0,0 +1,31 @@ +package ltd.hlaeja.service + +import java.util.UUID +import kotlinx.coroutines.test.runTest +import ltd.hlaeja.property.JwtProperty +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class JwtServiceTest { + + val property: JwtProperty = JwtProperty("keys/valid-private-key.pem") + lateinit var service: JwtService + + @BeforeEach + fun setUp() { + service = JwtService(property) + } + + @Test + fun `should generate a JWT successfully with a valid private key`() = runTest { + // given + val deviceId = UUID.fromString("00000000-0000-0000-0000-000000000000") + + // when + val jwt = service.makeIdentity(deviceId) + + // then + assertThat(jwt).contains("eyJkZXZpY2UiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAifQ") + } +}