token.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. package jwt
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "strings"
  6. "time"
  7. )
  8. // DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515
  9. // states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations
  10. // of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global
  11. // variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe.
  12. // To use the non-recommended decoding, set this boolean to `true` prior to using this package.
  13. var DecodePaddingAllowed bool
  14. // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
  15. // You can override it to use another time value. This is useful for testing or if your
  16. // server uses a different time zone than your tokens.
  17. var TimeFunc = time.Now
  18. // Keyfunc will be used by the Parse methods as a callback function to supply
  19. // the key for verification. The function receives the parsed,
  20. // but unverified Token. This allows you to use properties in the
  21. // Header of the token (such as `kid`) to identify which key to use.
  22. type Keyfunc func(*Token) (interface{}, error)
  23. // Token represents a JWT Token. Different fields will be used depending on whether you're
  24. // creating or parsing/verifying a token.
  25. type Token struct {
  26. Raw string // The raw token. Populated when you Parse a token
  27. Method SigningMethod // The signing method used or to be used
  28. Header map[string]interface{} // The first segment of the token
  29. Claims Claims // The second segment of the token
  30. Signature string // The third segment of the token. Populated when you Parse a token
  31. Valid bool // Is the token valid? Populated when you Parse/Verify a token
  32. }
  33. // New creates a new Token with the specified signing method and an empty map of claims.
  34. func New(method SigningMethod) *Token {
  35. return NewWithClaims(method, MapClaims{})
  36. }
  37. // NewWithClaims creates a new Token with the specified signing method and claims.
  38. func NewWithClaims(method SigningMethod, claims Claims) *Token {
  39. return &Token{
  40. Header: map[string]interface{}{
  41. "typ": "JWT",
  42. "alg": method.Alg(),
  43. },
  44. Claims: claims,
  45. Method: method,
  46. }
  47. }
  48. // SignedString creates and returns a complete, signed JWT.
  49. // The token is signed using the SigningMethod specified in the token.
  50. func (t *Token) SignedString(key interface{}) (string, error) {
  51. var sig, sstr string
  52. var err error
  53. if sstr, err = t.SigningString(); err != nil {
  54. return "", err
  55. }
  56. if sig, err = t.Method.Sign(sstr, key); err != nil {
  57. return "", err
  58. }
  59. return strings.Join([]string{sstr, sig}, "."), nil
  60. }
  61. // SigningString generates the signing string. This is the
  62. // most expensive part of the whole deal. Unless you
  63. // need this for something special, just go straight for
  64. // the SignedString.
  65. func (t *Token) SigningString() (string, error) {
  66. var err error
  67. parts := make([]string, 2)
  68. for i := range parts {
  69. var jsonValue []byte
  70. if i == 0 {
  71. if jsonValue, err = json.Marshal(t.Header); err != nil {
  72. return "", err
  73. }
  74. } else {
  75. if jsonValue, err = json.Marshal(t.Claims); err != nil {
  76. return "", err
  77. }
  78. }
  79. parts[i] = EncodeSegment(jsonValue)
  80. }
  81. return strings.Join(parts, "."), nil
  82. }
  83. // Parse parses, validates, verifies the signature and returns the parsed token.
  84. // keyFunc will receive the parsed token and should return the cryptographic key
  85. // for verifying the signature.
  86. // The caller is strongly encouraged to set the WithValidMethods option to
  87. // validate the 'alg' claim in the token matches the expected algorithm.
  88. // For more details about the importance of validating the 'alg' claim,
  89. // see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
  90. func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
  91. return NewParser(options...).Parse(tokenString, keyFunc)
  92. }
  93. func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
  94. return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
  95. }
  96. // EncodeSegment encodes a JWT specific base64url encoding with padding stripped
  97. //
  98. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  99. // should only be used internally
  100. func EncodeSegment(seg []byte) string {
  101. return base64.RawURLEncoding.EncodeToString(seg)
  102. }
  103. // DecodeSegment decodes a JWT specific base64url encoding with padding stripped
  104. //
  105. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  106. // should only be used internally
  107. func DecodeSegment(seg string) ([]byte, error) {
  108. if DecodePaddingAllowed {
  109. if l := len(seg) % 4; l > 0 {
  110. seg += strings.Repeat("=", 4-l)
  111. }
  112. return base64.URLEncoding.DecodeString(seg)
  113. }
  114. return base64.RawURLEncoding.DecodeString(seg)
  115. }