互动
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.

66 lines
1.6 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package jwt
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/dgrijalva/jwt-go"
  7. "github.com/ouxuanserver/osmanthuswine/src/helper"
  8. )
  9. type Claims struct {
  10. AccountType string
  11. AccountId int64
  12. CustomerId int64
  13. CustomerPid int64
  14. ActivityId int64
  15. AreaId int64
  16. jwt.StandardClaims
  17. }
  18. func GenJwtToken(accountType string, accountId, customerId, customerPid, areaId, activityId int64) (string, error) {
  19. claims := Claims{
  20. accountType,
  21. accountId,
  22. customerId,
  23. customerPid,
  24. activityId,
  25. areaId,
  26. jwt.StandardClaims{
  27. ExpiresAt: time.Now().Add(time.Duration(24) * time.Hour).Unix(),
  28. Id: helper.CreateUUID(),
  29. Issuer: Issuer,
  30. Subject: Subject,
  31. Audience: Audience,
  32. },
  33. }
  34. t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  35. return t.SignedString([]byte(Secret))
  36. }
  37. //const Secret = "十步杀一人,千里不留行。"
  38. const Secret = "osmanthuswine-very-secret"
  39. const Issuer = "osmanthuswine-issuer-ox"
  40. const Subject = "osmanthuswine-subject-ox"
  41. const Audience = "osmanthuswine-audience-ox"
  42. func ParseAccessToken(accessToken string) (*Claims, error) {
  43. var claims = &Claims{}
  44. token, err := jwt.ParseWithClaims(accessToken, claims, func(token *jwt.Token) (i interface{}, e error) {
  45. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  46. return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
  47. }
  48. return []byte(Secret), nil
  49. })
  50. if token == nil {
  51. return claims, errors.New("token invalid")
  52. }
  53. if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
  54. return nil, errors.New("token expired")
  55. }
  56. return claims, err
  57. }