Skip to content

Instantly share code, notes, and snippets.

@petehouston
Created March 13, 2020 17:28
Show Gist options
  • Save petehouston/f2dc3bda57f8f761b9e4c6e65869e16b to your computer and use it in GitHub Desktop.
Save petehouston/f2dc3bda57f8f761b9e4c6e65869e16b to your computer and use it in GitHub Desktop.
Generate signed JWT token string in Golang

Import the JWT package

import "github.com/dgrijalva/jwt-go"

Then generate with NewWithClaims.

Finally, get the signed JWT token string by calling SignedString().

package main
import (
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"log"
"time"
)
const (
ApiKey = "123123123"
ApiSecret = "secret"
)
func main() {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iat": time.Now().Unix(),
"sub": ApiKey,
})
if token == nil {
log.Fatal("error generating token")
return
}
tokenString, err := token.SignedString([]byte(ApiSecret))
if err != nil {
log.Fatal("error signing token")
return
}
fmt.Println("Generated JWT token string: " + tokenString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment