Created
May 22, 2017 02:07
-
-
Save aalvesjr/63cfc8dddf022e7d4f5b2c3796efb5de to your computer and use it in GitHub Desktop.
Try JWT with golang
This file contains hidden or 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 ( | |
"fmt" | |
"time" | |
"github.com/dgrijalva/jwt-go" | |
) | |
const secret = "big-secret" | |
func main() { | |
type DefaultClaims struct { | |
jwt.StandardClaims | |
UserID uint `json:"user_id"` | |
RoleType string `json:"role_type"` | |
} | |
attrs := map[string]interface{}{ | |
"user_id": 31, | |
"role_type": "BOSS", | |
"exp": time.Now().Unix(), | |
} | |
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(attrs)) | |
sToken, err := token.SignedString([]byte(secret)) | |
check(err) | |
fmt.Println("String Token:", sToken) | |
t, err := jwt.ParseWithClaims(sToken, &DefaultClaims{}, func(token *jwt.Token) (interface{}, error) { | |
return []byte(secret), nil | |
}) | |
check(err) | |
if claims, ok := t.Claims.(*DefaultClaims); ok { | |
fmt.Printf("User ID: %v is %s, token valid until %v\n", claims.UserID, claims.RoleType, claims.StandardClaims.ExpiresAt) | |
} | |
} | |
func check(e error) { | |
if e != nil { | |
fmt.Println("err >", e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment