最新:https://github.com/golang-jwt/jwt

type SigningMethod

定义了验证的方法接口

  1. type SigningMethod interface {
  2. // Returns nil if signature is valid
  3. Verify(signingString, signature string, key interface{}) error
  4. // Returns encoded signature or error
  5. Sign(signingString string, key interface{}) (string, error)
  6. // returns the alg identifier for this method (example: 'HS256')
  7. Alg() string
  8. }

type SigningMethodECDSA

实现了SigningMethod接口

  1. type SigningMethodECDSA struct {
  2. Name string
  3. Hash crypto.Hash
  4. KeySize int
  5. CurveBits int
  6. }
  1. var (
  2. SigningMethodES256 *SigningMethodECDSA
  3. SigningMethodES384 *SigningMethodECDSA
  4. SigningMethodES512 *SigningMethodECDSA
  5. )

func (m SigningMethodECDSA) Alg() string
func (m
SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error)
func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error

type Keyfunc

  1. type Keyfunc func(*Token) (interface{}, error)

type MapClaims

  1. type MapClaims map[string]interface{}

type StandardClaims

  1. type StandardClaims struct {
  2. Audience string `json:"aud,omitempty"`
  3. ExpiresAt int64 `json:"exp,omitempty"`
  4. Id string `json:"jti,omitempty"`
  5. IssuedAt int64 `json:"iat,omitempty"`
  6. Issuer string `json:"iss,omitempty"`
  7. NotBefore int64 `json:"nbf,omitempty"`
  8. Subject string `json:"sub,omitempty"`
  9. }

func (c StandardClaims) Valid() error:验证standardclaims的合法性
func (c StandardClaims) VerifyAudience(cmp string, req bool) bool:验证standardclaims的合法性
func (c
StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool
func (c StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool
func (c
StandardClaims) VerifyIssuer(cmp string, req bool) bool
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool

type Token

  1. type Token struct {
  2. Raw string // The raw token. Populated when you Parse a token
  3. Method SigningMethod // The signing method used or to be used
  4. Header map[string]interface{} // The first segment of the token
  5. Claims Claims // The second segment of the token
  6. Signature string // The third segment of the token. Populated when you Parse a token
  7. Valid bool // Is the token valid? Populated when you Parse/Verify a token
  8. }

func (t *Token) SignedString(key interface{}) (string, error):生成已签名的令牌

无claims

func New(method SigningMethod) *Token:创建一个新的令牌

  1. func main() {
  2. calims :=make(jwt.MapClaims)
  3. calims["name"] = "zhangsan"
  4. calims["age"] = 20
  5. token := jwt.New(jwt.SigningMethodHS256)
  6. token.Claims = calims
  7. // Sign and get the complete encoded token as a string using the secret
  8. tokenString, err := token.SignedString([]byte("mysalt"))
  9. fmt.Println(tokenString, err)
  10. }
  11. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHBpcmVkIjoxNTY2NTU5MjE1LCJ0aW1lc3RyYXAiOjE1NjY1NTU2MTV9.7m83aVguSGcVJHnZ51_nm268HnRYWj-xaIzOXUp-ayU <nil>
  1. func CreateJWT() string{
  2. claims := jwt.StandardClaims{}
  3. claims.ExpiresAt = time.Now().Add(time.Second * 1).Unix()
  4. token := jwt.New(jwt.SigningMethodHS256)
  5. token.Claims = claims
  6. tokenString, err := token.SignedString(MySigningKey)
  7. fmt.Println(tokenString, err)
  8. }

func Parse(tokenString string, keyFunc Keyfunc) (*Token, error)

  1. func main() {
  2. tokenString :="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHBpcmVkIjoxNTY2NTU5MjE1LCJ0aW1lc3RyYXAiOjE1NjY1NTU2MTV9.7m83aVguSGcVJHnZ51_nm268HnRYWj-xaIzOXUp-ayU"
  3. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  4. return []byte("mysalt"), nil
  5. })
  6. if token.Valid { //有效
  7. fmt.Println("good work")
  8. } else if ve, ok := err.(*jwt.ValidationError); ok { //错误被捕捉
  9. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  10. //格式错误
  11. fmt.Println("That's not even a token")
  12. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  13. //过期或还没激活
  14. fmt.Println("Token is either expired or not active yet")
  15. } else {
  16. //signature is invalid
  17. fmt.Println("Couldn't handle this token:", err)
  18. }
  19. } else { //错误无法捕捉
  20. fmt.Println("Couldn't handle this token:", err)
  21. }
  22. }
  23. good work

有claims

func NewWithClaims(method SigningMethod, claims Claims) *Token

  1. mySigningKey := []byte("AllYourBase")
  2. type MyCustomClaims struct {
  3. Foo string `json:"foo"`
  4. jwt.StandardClaims
  5. }
  6. // Create the Claims
  7. claims := MyCustomClaims{
  8. "bar",
  9. jwt.StandardClaims{
  10. ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
  11. Issuer: "test",
  12. },
  13. }
  14. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  15. ss, err := token.SignedString(mySigningKey)
  16. fmt.Printf("%v %v", ss, err)
  17. --------------------------------------------------------------------------------
  18. mySigningKey := []byte("AllYourBase")
  19. // Create the Claims
  20. claims := &jwt.StandardClaims{
  21. ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
  22. Issuer: "test",
  23. }
  24. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  25. ss, err := token.SignedString(mySigningKey)
  26. fmt.Printf("%v %v", ss, err)

func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error)

  1. tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
  2. type MyCustomClaims struct {
  3. Foo string `json:"foo"`
  4. jwt.StandardClaims
  5. }
  6. token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  7. return []byte("AllYourBase"), nil
  8. })
  9. if err !=nil {
  10. if ve, ok := err.(*jwt.ValidationError); ok { //错误被捕捉
  11. if ve.Errors&jwt.ValidationErrorMalformed != 0 {
  12. //格式错误
  13. fmt.Println("That's not even a token")
  14. } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
  15. //过期或还没激活
  16. fmt.Println("Token is either expired or not active yet")
  17. } else {
  18. //signature is invalid
  19. fmt.Println("Couldn't handle this token:", err)
  20. }
  21. }
  22. //错误无法捕捉
  23. fmt.Println("Couldn't handle this token:", err)
  24. }
  25. if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
  26. fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
  27. }else { // 上面的错误可以不捕捉
  28. fmt.Println("Couldn't handle this token:", err)
  29. }

无claims创建,有claims解析

  1. func CreateJWT() string{
  2. claims := jwt.StandardClaims{}
  3. claims.ExpiresAt = time.Now().Add(time.Second * 1).Unix()
  4. token := jwt.New(jwt.SigningMethodHS256)
  5. token.Claims = claims
  6. tokenString, err := token.SignedString(MySigningKey)
  7. fmt.Println(tokenString, err)
  8. return tokenString
  9. }
  10. func main() {
  11. tokenString := CreateJWT()
  12. token,err := jwt.ParseWithClaims(tokenString,&jwt.StandardClaims{},func(token *jwt.Token) (interface{}, error) {
  13. return MySigningKey, nil
  14. })
  15. if claims, ok := token.Claims.(*jwt.StandardClaims); ok && token.Valid {
  16. fmt.Println(claims)
  17. }else { // 上面的错误可以不捕捉
  18. fmt.Println("Couldn't handle this token:", err)
  19. }
  20. }
  1. func CreateJWT() string {
  2. calims := make(jwt.MapClaims)
  3. calims["name"] = "zhangsan"
  4. calims["age"] = 20
  5. token := jwt.New(jwt.SigningMethodHS256)
  6. token.Claims = calims
  7. tokenString, err := token.SignedString([]byte("mysalt"))
  8. fmt.Println(tokenString, err)
  9. return tokenString
  10. }
  11. func main() {
  12. tokenString := CreateJWT()
  13. token, err := jwt.ParseWithClaims(tokenString, &jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
  14. return []byte("mysalt"), nil
  15. })
  16. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  17. fmt.Println(claims)
  18. } else { // 上面的错误可以不捕捉
  19. fmt.Println("Couldn't handle this token:", err)
  20. }
  21. }

常见的token报存用户信息

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/golang-jwt/jwt"
  5. "time"
  6. )
  7. var (
  8. MySigningKey = []byte("mysalt")
  9. )
  10. type MyCustomClaims struct {
  11. jwt.StandardClaims
  12. UserId string `json:"UserId"`
  13. }
  14. func CreatJWT() string{
  15. userId := "xaspln001"
  16. claims := MyCustomClaims{
  17. jwt.StandardClaims{
  18. ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
  19. Issuer: "jw",
  20. },
  21. userId,
  22. }
  23. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  24. tokenString, err := token.SignedString(MySigningKey)
  25. fmt.Println(tokenString, err)
  26. return tokenString
  27. }
  28. func main() {
  29. tokenString := CreatJWT()
  30. token,err := jwt.ParseWithClaims(tokenString,&MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
  31. return MySigningKey, nil
  32. })
  33. if err != nil {
  34. fmt.Println("请登入!")
  35. }
  36. if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
  37. fmt.Printf("%v %v", claims.UserId,claims.ExpiresAt)
  38. } else {
  39. fmt.Println("请登入!")
  40. }
  41. }
  42. eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzExOTQxOTUsImlzcyI6Imp3IiwiVXNlcklkIjoieGFzcGxuMDAxIn0.58KuTNAMPUebivq3mJLrZzjZ140sn9g-0YHCvJxzTlg <nil>
  43. xaspln001 1571194195