jwt.go 948 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/dgrijalva/jwt-go"
  5. "strconv"
  6. )
  7. type TokenClaims struct {
  8. ID float64 `json:"id"`
  9. jwt.StandardClaims
  10. }
  11. func main() {
  12. c, err := parseToken("eyJhbGciOiJIUzI1NiIsImlhdCI6MTUzNzg0Njc4MywiZXhwIjoxNTM5MDU2MzgzfQ.eyJpZCI6MzI0NTEzNH0.RqRoad8H5oAGY6L3qMLcxCUYE5Fl7-MXtpSyfSU4aqU")
  13. if nil != err {
  14. println(err)
  15. }
  16. fmt.Printf("%v\n", c)
  17. fmt.Printf("%v", strconv.FormatFloat(c.ID, 'f', 0, 64))
  18. }
  19. func parseToken(tokenString string) (*TokenClaims, error) {
  20. token, err := jwt.ParseWithClaims(tokenString, &TokenClaims{}, func(token *jwt.Token) (interface{}, error) {
  21. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  22. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  23. }
  24. return []byte("hard to guess string"), nil
  25. })
  26. if err != nil {
  27. return nil, err
  28. }
  29. if claims, ok := token.Claims.(*TokenClaims); ok && token.Valid {
  30. return claims, nil
  31. }
  32. return nil, nil
  33. }