Skip to content

Instantly share code, notes, and snippets.

@lregnier
Created June 15, 2018 17:47
Show Gist options
  • Save lregnier/d1db6d30ad6372834d88f4756547c226 to your computer and use it in GitHub Desktop.
Save lregnier/d1db6d30ad6372834d88f4756547c226 to your computer and use it in GitHub Desktop.
import java.util.Date
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.interfaces.DecodedJWT
import com.auth0.jwt.{JWT => Auth0JWT}
import com.typesafe.config.Config
import scala.util.Try
object JWT {
private def algorithm(implicit settings: JWTSettings): Algorithm = Algorithm.HMAC256(secret)
private def secret(implicit settings: JWTSettings): String = settings.secret
private def issuer(implicit settings: JWTSettings): String = settings.issuer
private def expiresAt(issuedAt: Date)(implicit settings: JWTSettings): Date = new Date(issuedAt.getTime + settings.expiresAfter.toMillis)
def create(subject: String)(implicit settings: JWTSettings): Try[String] = Try {
val issuedAt = new Date()
val token =
Auth0JWT
.create()
.withIssuer(issuer)
.withSubject(subject)
.withIssuedAt(issuedAt)
.withExpiresAt(expiresAt(issuedAt))
.sign(algorithm)
token
}
def verify(token: String)(implicit settings: JWTSettings): Try[DecodedJWT] = Try {
val verifier =
Auth0JWT
.require(algorithm)
.withIssuer(issuer)
.build()
verifier.verify(token)
}
}
class JWTSettings(config: Config) {
import utils.DurationExtensions._
private val jwtConfig = config.getConfig("jwt")
val secret = jwtConfig.getString("secret")
val issuer = jwtConfig.getString("issuer")
val expiresAfter = jwtConfig.getDuration("expires-after").toScala
}
object JWTSettings {
def apply(config: Config): JWTSettings = new JWTSettings(config)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment