Last active
September 18, 2024 14:32
-
-
Save Valve/575a1b1f5127d4f6108125205e36e07b to your computer and use it in GitHub Desktop.
Generate JWT token in Go without using 3rd party libraries
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
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