面包店
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

auth.go 1.1 KiB

8 kuukautta sitten
123456789101112131415161718192021222324252627282930313233343536373839
  1. package auth
  2. import (
  3. "errors"
  4. "github.com/dgrijalva/jwt-go"
  5. "time"
  6. )
  7. // GenToken 生成JWT
  8. func GenToken(account, password string) (string, error) {
  9. // 创建一个我们自己的声明
  10. c := JWTUser{
  11. Account: account,
  12. Password: password,
  13. StandardClaims: jwt.StandardClaims{
  14. ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间
  15. Issuer: "bakery", // 签发人
  16. },
  17. }
  18. // 使用指定的签名方法创建签名对象
  19. token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
  20. // 使用指定的secret签名并获得完整的编码后的字符串token
  21. return token.SignedString(Secret)
  22. }
  23. // ParseToken 解析JWT
  24. func ParseToken(tokenString string) (*JWTUser, error) {
  25. // 解析token
  26. token, err := jwt.ParseWithClaims(tokenString, &JWTUser{}, func(token *jwt.Token) (i interface{}, err error) {
  27. return Secret, nil
  28. })
  29. if err != nil {
  30. return nil, err
  31. }
  32. if claims, ok := token.Claims.(*JWTUser); ok && token.Valid { // 校验token
  33. return claims, nil
  34. }
  35. return nil, errors.New("invalid token")
  36. }