Last active
May 25, 2021 15:47
-
-
Save otiai10/22ad21fbe48f37f14c6b2218e9d110a5 to your computer and use it in GitHub Desktop.
Golang JWT Example (2017/Oct/26)
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
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) | |
} |
how would you create a refresh token?
This is outside of the scope of the Gist but one idea is to simply include a stateless renewal hash as a claim.
You can checkout full implementation of JWT and Go at http://jwt.io there is 11 implementation of the API
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
how would you create a refresh token?