面包店
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

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