Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created June 22, 2016 18:46
Show Gist options
  • Save bdkosher/cb9bcac57ed3d77e0daee393a64c4694 to your computer and use it in GitHub Desktop.
Save bdkosher/cb9bcac57ed3d77e0daee393a64c4694 to your computer and use it in GitHub Desktop.
Script for generating a JWT token.
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
@Grab(group='commons-codec', module='commons-codec', version='1.10')
import org.apache.commons.codec.binary.Base64
def jwtTokenHeader = '''{
"typ": "JWT",
"alg": "HS256"
}'''
def jwtTokenClaims = """{
"exp": ${Long.MAX_VALUE},
"userName": "test",
"otherInfo": 12
}"""
try {
String secret = 'secret'
String message = Base64.encodeBase64String(jwtTokenHeader.bytes) + '.' + Base64.encodeBase64String(jwtTokenClaims.bytes)
Mac sha256_HMAC = Mac.getInstance('HmacSHA256')
SecretKeySpec key = new SecretKeySpec(secret.bytes, 'HmacSHA256')
sha256_HMAC.init(key)
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.bytes))
println "${message}.${hash}"
}
catch (e) {
e.printStackTrace()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment