tokenparser_test.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package token
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "time"
  7. "github.com/dgrijalva/jwt-go"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/tal-tech/go-zero/core/timex"
  10. )
  11. func TestTokenParser(t *testing.T) {
  12. const (
  13. key = "14F17379-EB8F-411B-8F12-6929002DCA76"
  14. prevKey = "B63F477D-BBA3-4E52-96D3-C0034C27694A"
  15. )
  16. keys := []struct {
  17. key string
  18. prevKey string
  19. }{
  20. {
  21. key,
  22. prevKey,
  23. },
  24. {
  25. key,
  26. "",
  27. },
  28. }
  29. for _, pair := range keys {
  30. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  31. token, err := buildToken(key, map[string]interface{}{
  32. "key": "value",
  33. }, 3600)
  34. assert.Nil(t, err)
  35. req.Header.Set("Authorization", "Bearer "+token)
  36. parser := NewTokenParser(WithResetDuration(time.Minute))
  37. tok, err := parser.ParseToken(req, pair.key, pair.prevKey)
  38. assert.Nil(t, err)
  39. assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"])
  40. }
  41. }
  42. func TestTokenParser_Expired(t *testing.T) {
  43. const (
  44. key = "14F17379-EB8F-411B-8F12-6929002DCA76"
  45. prevKey = "B63F477D-BBA3-4E52-96D3-C0034C27694A"
  46. )
  47. req := httptest.NewRequest(http.MethodGet, "http://localhost", nil)
  48. token, err := buildToken(key, map[string]interface{}{
  49. "key": "value",
  50. }, 3600)
  51. assert.Nil(t, err)
  52. req.Header.Set("Authorization", "Bearer "+token)
  53. parser := NewTokenParser(WithResetDuration(time.Second))
  54. tok, err := parser.ParseToken(req, key, prevKey)
  55. assert.Nil(t, err)
  56. assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"])
  57. tok, err = parser.ParseToken(req, key, prevKey)
  58. assert.Nil(t, err)
  59. assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"])
  60. parser.resetTime = timex.Now() - time.Hour
  61. tok, err = parser.ParseToken(req, key, prevKey)
  62. assert.Nil(t, err)
  63. assert.Equal(t, "value", tok.Claims.(jwt.MapClaims)["key"])
  64. }
  65. func buildToken(secretKey string, payloads map[string]interface{}, seconds int64) (string, error) {
  66. now := time.Now().Unix()
  67. claims := make(jwt.MapClaims)
  68. claims["exp"] = now + seconds
  69. claims["iat"] = now
  70. for k, v := range payloads {
  71. claims[k] = v
  72. }
  73. token := jwt.New(jwt.SigningMethodHS256)
  74. token.Claims = claims
  75. return token.SignedString([]byte(secretKey))
  76. }