You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.1 KiB
37 lines
1.1 KiB
package org.tbasket.jwt
|
|
|
|
import pdi.jwt.*
|
|
import pdi.jwt.algorithms.JwtAsymmetricAlgorithm
|
|
import zio.*
|
|
import zio.http.{Request, Response}
|
|
import zio.json.*
|
|
import zio.json.ast.Json
|
|
|
|
import java.lang.System.currentTimeMillis
|
|
import java.nio.file.*
|
|
import java.security.{Key, PrivateKey}
|
|
import java.security.interfaces.RSAPrivateKey
|
|
import java.security.spec.PKCS8EncodedKeySpec
|
|
import java.util.concurrent.TimeUnit
|
|
import java.util.{Date, UUID}
|
|
import javax.crypto.SecretKey
|
|
import java.time.Duration
|
|
|
|
class JwtGenerator(tokenLifespan: Duration, key: PrivateKey, algorithm: JwtAsymmetricAlgorithm):
|
|
|
|
private def claims(content: String) = JwtClaim(
|
|
expiration = Some(currentTimeMillis() + tokenLifespan.toMillis),
|
|
issuedAt = Some(currentTimeMillis()),
|
|
jwtId = Some(UUID.randomUUID().toString),
|
|
content = content
|
|
)
|
|
|
|
|
|
def generateTokenResponse(request: Request): Task[Response] =
|
|
for
|
|
claims <- request.body.asString.map(claims)
|
|
jwt <- ZIO.attempt(JwtZIOJson.encode(claims, key, algorithm)).catchAll(e => {
|
|
ZIO.attempt(e.printStackTrace()).as("error")
|
|
})
|
|
yield Response.json(jwt)
|