Skip to content

Instantly share code, notes, and snippets.

@Valve
Last active May 5, 2020 18:25
Show Gist options
  • Save Valve/575a1b1f5127d4f6108125205e36e07b to your computer and use it in GitHub Desktop.
Save Valve/575a1b1f5127d4f6108125205e36e07b to your computer and use it in GitHub Desktop.
Generate JWT token in Go without using 3rd party libraries
header := encodeSegment([]byte(`{"alg":"HS256","typ":"JWT"}`))
// token is valid for 60 seconds
payloadJSON := fmt.Sprintf(`{"userId":"2718281828459","iat":%d}`, time.Now().Add(60*time.Second).Unix())
payload := encodeSegment([]byte(payloadJSON))
key := "secret"
hmac := hmac.New(sha256.New, []byte(key))
hmac.Write([]byte(header + "." + payload))
signature := encodeSegment(hmac.Sum(nil))
token := header + "." + payload + "." + signature
// Encode JWT specific base64url encoding with padding stripped
func encodeSegment(seg []byte) string {
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment