-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.sh
executable file
·74 lines (59 loc) · 1.74 KB
/
jwt.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env bash
# JWT Encoder Bash Script
#
# A lightly modified version of the original by Will Haley:
# https://willhaley.com/blog/generate-jwt-with-bash/
#
# With stdin handling from Filipe Fortes:
# https://fortes.com/2019/bash-script-args-and-stdin/
# Copy command-line arguments over to new array
ARGS=( $@ )
# Don't split on spaces
IFS='
'
# Read in from piped input, if present, and append to newly-created array
if [ ! -t 0 ]; then
readarray STDIN_ARGS < /dev/stdin
ARGS=( $@ ${STDIN_ARGS[@]} )
fi
# Takes two parameters: the shared secret, and the JSON string to encode
secret=${ARGS[0]}
# Take the payload from the arguments, or fall back to stdin
payload=${ARGS[1]}
# Show an error if neither are defined
if [ -z "$secret" ] || [ -z "$payload" ]; then
>&2 echo "Usage: $0 <secret> <json>"
exit 1
fi
# Static header fields.
header='{
"typ": "JWT",
"alg": "HS256"
}'
# Use jq to set the dynamic `iat` and `exp`
# fields on the payload using the current time.
# `iat` is set to now, and `exp` is now + 1 hour.
payload=$(
echo "${payload}" | jq --arg time_str "$(date +%s)" \
'
($time_str | tonumber) as $time_num
| .iat=$time_num
| .exp=($time_num + 3600)
| .iss="orrc/jwt-generator"
'
)
base64_encode() {
# Use `tr` to URL encode the output from base64.
base64 | tr -d '=' | tr '/+' '_-' | tr -d '\n'
}
json() {
jq -c . | tr -d '\n'
}
hmacsha256_sign() {
openssl dgst -binary -sha256 -hmac "${secret}"
}
header_base64=$(echo "${header}" | json | base64_encode)
payload_base64=$(echo "${payload}" | json | base64_encode)
header_payload=$(echo "${header_base64}.${payload_base64}")
signature=$(echo -n "${header_payload}" | hmacsha256_sign | base64_encode)
echo "${header_payload}.${signature}"