How to create a Json Web Token (JWT) using OpenSSL shell commands?

前端 未结 1 1162
情书的邮戳
情书的邮戳 2020-12-31 14:37

I\'m trying to create a JSON Web Token (JWT) using command line utilities on MacOS and hitting a snag with the signing portion.

I was greatly inspired by this gist:

相关标签:
1条回答
  • 2020-12-31 15:19

    I was able to recreate the JWT from https://jwt.io/

    In your example, there was a hidden newline on the user secret. So in the below, I also add on that newline, purely to recreate the desired output. Also the email address in your payload was not consistent, so for below I have used jordan@example.com.

    I took a slightly different approach to the hmac step. I converted the user secret to hex bytes and used that as the key (using the hexkey option for the HMAC).

    # Construct the header
    jwt_header=$(echo -n '{"alg":"HS256","typ":"JWT"}' | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
    
    # ans: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
    
    # Construct the payload
    payload=$(echo -n '{"email":"jordan@example.com"}' | base64 | sed s/\+/-/g |sed 's/\//_/g' |  sed -E s/=+$//)
    
    # ans: eyJlbWFpbCI6ImpvcmRhbkBleGFtcGxlLmNvbSJ9
    
    # Store the raw user secret (with example of newline at end)
    secret=$'bigsecretisveryhardtoguessbysneakypeopleright\n'
    
    # Note, because the secret may have newline, need to reference using form $"" 
    echo -n "$secret"
    
    # Convert secret to hex (not base64)
    hexsecret=$(echo -n "$secret" | xxd -p | paste -sd "")
    
    # ans: 62696773656372657469737665727968617264746f67756573736279736e65616b7970656f706c6572696768740a
    
    # For debug, also display secret in base64 (for input into https://jwt.io/)
    echo -n "$secret" | base64
    
    # ans: Ymlnc2VjcmV0aXN2ZXJ5aGFyZHRvZ3Vlc3NieXNuZWFreXBlb3BsZXJpZ2h0Cg==
    
    # Calculate hmac signature -- note option to pass in the key as hex bytes
    hmac_signature=$(echo -n "${jwt_header}.${payload}" |  openssl dgst -sha256 -mac HMAC -macopt hexkey:$hexsecret -binary | base64  | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)
    
    # Create the full token
    jwt="${jwt_header}.${payload}.${hmac_signature}"
    
    # ans: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpvcmRhbkBleGFtcGxlLmNvbSJ9.C3MVjfmnul8dLNIgiv6Dt3jSefD07Y0QtDrOZ5oYSXo
    
    0 讨论(0)
提交回复
热议问题