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.
49 lines
1.5 KiB
49 lines
1.5 KiB
package org.tbasket.jwt
|
|
|
|
import org.apache.logging.log4j.LogManager
|
|
import org.slf4j.LoggerFactory
|
|
import org.tbasket.jwt.JwtGenerator.LOG
|
|
import pdi.jwt.*
|
|
import pdi.jwt.algorithms.JwtAsymmetricAlgorithm
|
|
import zio.*
|
|
import zio.http.model.HttpError
|
|
import zio.http.model.Status.InternalServerError
|
|
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.cert.CertificateFactory
|
|
import java.security.interfaces.RSAPrivateKey
|
|
import java.security.spec.PKCS8EncodedKeySpec
|
|
import java.security.{Key, PrivateKey}
|
|
import java.time.Duration
|
|
import java.util.concurrent.TimeUnit
|
|
import java.util.{Date, UUID}
|
|
import javax.crypto.SecretKey
|
|
|
|
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)
|
|
response <- ZIO.attempt(JwtZIOJson.encode(claims, key, algorithm))
|
|
.map(Response.text)
|
|
.catchAll(e => {
|
|
ZIO.attempt(e.printStackTrace()).as(Response.status(InternalServerError))
|
|
})
|
|
yield
|
|
LOG.info(s"Generated jwt:\n${claims.toJson}")
|
|
response
|
|
|
|
object JwtGenerator:
|
|
private val LOG = LogManager.getLogger("JWTEmitter")
|
|
|