Skip to content

Instantly share code, notes, and snippets.

@zed-wong
Created September 20, 2023 01:29
Show Gist options
  • Save zed-wong/4ec7b72c927a2985a23b487f06c142e4 to your computer and use it in GitHub Desktop.
Save zed-wong/4ec7b72c927a2985a23b487f06c142e4 to your computer and use it in GitHub Desktop.
mixin-sign-auth.go
package main
import (
"crypto/sha256"
"encoding/hex"
"github.com/dgrijalva/jwt-go"
"golang.org/x/crypto/ed25519"
"github.com/google/uuid"
"encoding/base64"
"fmt"
"time"
)
// UuidNewV4 generates a new UUID version 4.
func UuidNewV4() uuid.UUID {
return uuid.New()
}
func SignAuthenticationToken(uid, sid, privateKey, method, uri, body string) (string, error) {
expire := time.Now().UTC().Add(time.Hour * 24 * 30 * 3)
sum := sha256.Sum256([]byte(method + uri + body))
claims := jwt.MapClaims{
"uid": uid,
"sid": sid,
"iat": time.Now().UTC().Unix(),
"exp": expire.Unix(),
"jti": UuidNewV4().String(),
"sig": hex.EncodeToString(sum[:]),
"scp": "FULL",
}
priv, err := base64.RawURLEncoding.DecodeString(privateKey)
if err != nil {
return "", err
}
// more validate the private key
if len(priv) != 64 {
return "", fmt.Errorf("Bad ed25519 private key %s", priv)
}
token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
return token.SignedString(ed25519.PrivateKey(priv))
}
func main() {
// Example usage
uid := "user123"
sid := "session456"
privateKey := "your_private_key_here"
method := "GET"
uri := "/api/resource"
body := "request_body_here"
token, err := SignAuthenticationToken(uid, sid, privateKey, method, uri, body)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Authentication token:", token)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment