jwt_claim_def.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package zllauth1
  2. import (
  3. "crypto/subtle"
  4. "fmt"
  5. "github.com/dgrijalva/jwt-go"
  6. "time"
  7. )
  8. type ZLLAuthJwtClaim struct {
  9. ExpiresAt int64 `json:"exp,omitempty"`
  10. Id string `json:"jti"`
  11. IssuedAt int64 `json:"iat,omitempty"`
  12. Issuer string `json:"iss,omitempty"`
  13. NotBefore int64 `json:"nbf,omitempty"`
  14. Subject string `json:"sub,omitempty"`
  15. ExtendInfo map[string]interface{} `json:"exi"`
  16. }
  17. func (c *ZLLAuthJwtClaim) Valid() error {
  18. now := jwt.TimeFunc().Unix()
  19. if c.VerifyExpiresAt(now, true) == false {
  20. delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
  21. return fmt.Errorf("token is expired by %v", delta)
  22. }
  23. if c.VerifyIssuedAt(now, true) == false {
  24. return fmt.Errorf("Token used before issued")
  25. }
  26. if c.VerifyNotBefore(now, true) == false {
  27. return fmt.Errorf("token is not valid yet")
  28. }
  29. return nil
  30. }
  31. func (c *ZLLAuthJwtClaim) VerifyExpiresAt(cmp int64, req bool) bool {
  32. if c.ExpiresAt == 0 {
  33. return !req
  34. }
  35. return cmp <= c.ExpiresAt
  36. }
  37. func (c *ZLLAuthJwtClaim) VerifyIssuedAt(cmp int64, req bool) bool {
  38. if c.IssuedAt == 0 {
  39. return !req
  40. }
  41. return cmp >= c.IssuedAt
  42. }
  43. func (c *ZLLAuthJwtClaim) VerifyIssuer(cmp string, req bool) bool {
  44. if c.Issuer == "" {
  45. return !req
  46. }
  47. if subtle.ConstantTimeCompare([]byte(c.Issuer), []byte(cmp)) != 0 {
  48. return true
  49. } else {
  50. return false
  51. }
  52. }
  53. func (c *ZLLAuthJwtClaim) VerifyNotBefore(cmp int64, req bool) bool {
  54. if c.NotBefore == 0 {
  55. return !req
  56. }
  57. return cmp >= c.NotBefore
  58. }
  59. func (c *ZLLAuthJwtClaim) VerifySubject(cmp string, req bool) bool {
  60. if c.Subject == "" {
  61. return !req
  62. }
  63. if subtle.ConstantTimeCompare([]byte(c.Subject), []byte(cmp)) != 0 {
  64. return true
  65. } else {
  66. return false
  67. }
  68. }