token.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. var jsonValue []byte
  68. if jsonValue, err = json.Marshal(t.Header); err != nil {
  69. return "", err
  70. }
  71. header := EncodeSegment(jsonValue)
  72. if jsonValue, err = json.Marshal(t.Claims); err != nil {
  73. return "", err
  74. }
  75. claim := EncodeSegment(jsonValue)
  76. return strings.Join([]string{header, claim}, "."), nil
  77. }
  78. // Parse parses, validates, verifies the signature and returns the parsed token.
  79. // keyFunc will receive the parsed token and should return the cryptographic key
  80. // for verifying the signature.
  81. // The caller is strongly encouraged to set the WithValidMethods option to
  82. // validate the 'alg' claim in the token matches the expected algorithm.
  83. // For more details about the importance of validating the 'alg' claim,
  84. // see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/
  85. func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
  86. return NewParser(options...).Parse(tokenString, keyFunc)
  87. }
  88. func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
  89. return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
  90. }
  91. // EncodeSegment encodes a JWT specific base64url encoding with padding stripped
  92. //
  93. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  94. // should only be used internally
  95. func EncodeSegment(seg []byte) string {
  96. return base64.RawURLEncoding.EncodeToString(seg)
  97. }
  98. // DecodeSegment decodes a JWT specific base64url encoding with padding stripped
  99. //
  100. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  101. // should only be used internally
  102. func DecodeSegment(seg string) ([]byte, error) {
  103. if DecodePaddingAllowed {
  104. if l := len(seg) % 4; l > 0 {
  105. seg += strings.Repeat("=", 4-l)
  106. }
  107. return base64.URLEncoding.DecodeString(seg)
  108. }
  109. return base64.RawURLEncoding.DecodeString(seg)
  110. }