Created
March 5, 2016 07:53
-
-
Save arcseldon/ed5de4a71aa8d05da15e to your computer and use it in GitHub Desktop.
Provides a blueprint for how to create an Auth0 JSON Web Token (JWT)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// richard.seldon@auth0.com | |
// commons-codec-1.10.jar | |
// java-jwt-2.1.0.jar | |
// see docs here: https://auth0.com/docs/jwt | |
import java.security.SignatureException | |
import java.text.SimpleDateFormat | |
import com.auth0.jwt.{JWTVerifier, JWTSigner} | |
import org.apache.commons.codec.binary.Base64 | |
object SignerExample { | |
def main(args: Array[String]) = { | |
try { | |
val CLIENT_SECRET = "<YOUR_APP_CLIENT_SECRET" | |
val EXPIRATION = 36000 // 10 hours | |
// iss the issuer which corresponds to your instance of Auth0. | |
// sub the subject, is a string formed by the connection used to authenticate the user | |
// and the unique id of the logged in user in that identity provider. | |
// aud the audience, always set to your application Client ID in Auth0. | |
// exp the expiration, set to 10 hours. | |
// iat the issued at timestamp. | |
val iss: String = "https://<YOUR_ACCOUNT>.auth0.com/" | |
val sub: String = "auth0|<YOUR_USER>" | |
val aud: String = "<CLIENT_ID>" | |
val formatDateInt = (dateInt: Integer) => { | |
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(dateInt * 1000L)) | |
} | |
val dateNow = () => new java.util.Date().getTime() / 1000 | |
val createExpDateInt = () => { | |
dateNow().toInt + EXPIRATION | |
} | |
// automatically calculate | |
val exp: Integer = createExpDateInt() | |
val iat: Integer = dateNow().toInt | |
println("Expiry: " + formatDateInt(exp)) | |
//=> 2016-03-06 00:22:06 (10 hours from when generated) | |
val claims: java.util.Map[String, Object] = new java.util.HashMap[String, Object]() | |
claims.put("iss", iss) | |
claims.put("sub", sub) | |
claims.put("aud", aud) | |
claims.put("exp", exp) | |
claims.put("iat", iat) | |
// ok, generate the JWT | |
val secret: Array[Byte] = Base64.decodeBase64(CLIENT_SECRET) | |
val jwtSigner = new JWTSigner(secret) | |
val token = jwtSigner.sign(claims) | |
println("Token: " + token) | |
// just quick verification check - sanity check only | |
val jwtVerifier = new JWTVerifier(secret, aud) | |
val decodedPayload: java.util.Map[String, Object] = jwtVerifier.verify(token) | |
println("Issuer: " + decodedPayload.get("iss")); | |
//=> https://<YOUR_ACCOUNT>.auth0.com/ | |
} catch { | |
case se: SignatureException => println("Invalid signature!") | |
case ise: IllegalStateException => println("Invalid Token!") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment