Skip to content

Instantly share code, notes, and snippets.

@otiai10
Last active May 25, 2021 15:47
Show Gist options
  • Save otiai10/22ad21fbe48f37f14c6b2218e9d110a5 to your computer and use it in GitHub Desktop.
Save otiai10/22ad21fbe48f37f14c6b2218e9d110a5 to your computer and use it in GitHub Desktop.
Golang JWT Example (2017/Oct/26)
package main
import (
"log"
jwt "github.com/dgrijalva/jwt-go"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
jwt.StandardClaims
}
func createTokenString() string {
// Embed User information to `token`
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), &User{
Name: "otiai10",
Age: 30,
})
// token -> string. Only server knows this secret (foobar).
tokenstring, err := token.SignedString([]byte("foobar"))
if err != nil {
log.Fatalln(err)
}
return tokenstring
}
func main() {
// for example, server receive token string in request header.
tokenstring := createTokenString()
// This is that token string.
log.Println(tokenstring)
// Let's parse this by the secrete, which only server knows.
token, err := jwt.Parse(tokenstring, func(token *jwt.Token) (interface{}, error) {
return []byte("foobar"), nil
})
// When using `Parse`, the result `Claims` would be a map.
log.Println(token.Claims, err)
// In another way, you can decode token to your struct, which needs to satisfy `jwt.StandardClaims`
user := User{}
token, err = jwt.ParseWithClaims(tokenstring, &user, func(token *jwt.Token) (interface{}, error) {
return []byte("foobar"), nil
})
log.Println(token.Valid, user, err)
}
@rcauchon
Copy link

You can checkout full implementation of JWT and Go at http://jwt.io there is 11 implementation of the API

@orez-fu
Copy link

orez-fu commented May 4, 2019

How do the sever know alg use while encode?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment