Skip to content

Instantly share code, notes, and snippets.

@Carlos-Augusto
Created October 12, 2020 08:56
Show Gist options
  • Save Carlos-Augusto/c2007066af4a2f2b97d4293778f8af5d to your computer and use it in GitHub Desktop.
Save Carlos-Augusto/c2007066af4a2f2b97d4293778f8af5d to your computer and use it in GitHub Desktop.
import java.time.Clock
import java.util.UUID
import com.ubirch.crypto.GeneratorKeyFactory
import com.ubirch.crypto.utils.Curve
import org.json4s._
import org.json4s.jackson.Serialization
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
implicit lazy val formats: Formats = Serialization.formats(NoTypeHints) ++
org.json4s.ext.JavaTypesSerializers.all
implicit val clock: Clock = Clock.systemUTC
case class OtherClaims(role: Symbol)
val jwtID = UUID.fromString("2881e5f8-3d4b-4a1d-be78-b67837a383fa")
val tenantId = UUID.fromString("7d6018c0-f10b-4330-99fb-cd29f52ae9fa")
val deviceId = UUID.fromString("bb505d32-b5ec-4f8d-816d-761ce82f3657")
val otherClaims = OtherClaims('verifier)
val expiresInSecs = 60 * 60 * 60
//We generate a keypair
val privKey = GeneratorKeyFactory.getPrivKey(Curve.PRIME256V1)
val privateKey = privKey.getPrivateKey
val publicKey = privKey.getPublicKey
//We create the token
val token = Jwt.encode(
JwtClaim()
.withContent(jackson.compactJson(Extraction.decompose(otherClaims).snakizeKeys))
.by(tenantId.toString)
.to(deviceId.toString)
.withId(jwtID.toString)
.issuedNow
.expiresIn(expiresInSecs),
privateKey,
JwtAlgorithm.ES256
)
//eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJpc3MiOiI3ZDYwMThjMC1mMTBiLTQzMzAtOTlmYi1jZDI5ZjUyYWU5ZmEiLCJhdWQiOiJiYjUwNWQzMi1iNWVjLTRmOGQtODE2ZC03NjFjZTgyZjM2NTciLCJleHAiOjE2MDI3MDg5MTksImlhdCI6MTYwMjQ5MjkxOSwianRpIjoiMjg4MWU1ZjgtM2Q0Yi00YTFkLWJlNzgtYjY3ODM3YTM4M2ZhIiwicm9sZSI6InZlcmlmaWVyIn0.MGRDTFwaI5lVD442bgwPyFKszX06pbXSUcY_cftARPJW7dgbDfB0lTPqrQKeYVeP-Cqgkh24djsh7DfOCYmXhg
//We decode the token
Jwt.decodeRawAll(token, publicKey, Seq(JwtAlgorithm.ES256))
//res0: scala.util.Try[(String, String, String)] = Success(({"typ":"JWT","alg":"ES256"},{"iss":"7d6018c0-f10b-4330-99fb-cd29f52ae9fa","aud":"bb505d32-b5ec-4f8d-816d-761ce82f3657","exp":1602708919,"iat":1602492919,"jti":"2881e5f8-3d4b-4a1d-be78-b67837a383fa","role":"verifier"},MGRDTFwaI5lVD442bgwPyFKszX06pbXSUcY_cftARPJW7dgbDfB0lTPqrQKeYVeP-Cqgkh24djsh7DfOCYmXhg))
@Carlos-Augusto
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment