token.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. // DecodeStrict will switch the codec used for decoding JWTs into strict mode.
  15. // In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5.
  16. // Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe.
  17. // To use strict decoding, set this boolean to `true` prior to using this package.
  18. var DecodeStrict bool
  19. // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
  20. // You can override it to use another time value. This is useful for testing or if your
  21. // server uses a different time zone than your tokens.
  22. var TimeFunc = time.Now
  23. // Keyfunc will be used by the Parse methods as a callback function to supply
  24. // the key for verification. The function receives the parsed,
  25. // but unverified Token. This allows you to use properties in the
  26. // Header of the token (such as `kid`) to identify which key to use.
  27. type Keyfunc func(*Token) (interface{}, error)
  28. // Token represents a JWT Token. Different fields will be used depending on whether you're
  29. // creating or parsing/verifying a token.
  30. type Token struct {
  31. Raw string // The raw token. Populated when you Parse a token
  32. Method SigningMethod // The signing method used or to be used
  33. Header map[string]interface{} // The first segment of the token
  34. Claims Claims // The second segment of the token
  35. Signature string // The third segment of the token. Populated when you Parse a token
  36. Valid bool // Is the token valid? Populated when you Parse/Verify a token
  37. }
  38. // New creates a new Token with the specified signing method and an empty map of claims.
  39. func New(method SigningMethod) *Token {
  40. return NewWithClaims(method, MapClaims{})
  41. }
  42. // NewWithClaims creates a new Token with the specified signing method and claims.
  43. func NewWithClaims(method SigningMethod, claims Claims) *Token {
  44. return &Token{
  45. Header: map[string]interface{}{
  46. "typ": "JWT",
  47. "alg": method.Alg(),
  48. },
  49. Claims: claims,
  50. Method: method,
  51. }
  52. }
  53. // SignedString creates and returns a complete, signed JWT.
  54. // The token is signed using the SigningMethod specified in the token.
  55. func (t *Token) SignedString(key interface{}) (string, error) {
  56. var sig, sstr string
  57. var err error
  58. if sstr, err = t.SigningString(); err != nil {
  59. return "", err
  60. }
  61. if sig, err = t.Method.Sign(sstr, key); err != nil {
  62. return "", err
  63. }
  64. return strings.Join([]string{sstr, sig}, "."), nil
  65. }
  66. // SigningString generates the signing string. This is the
  67. // most expensive part of the whole deal. Unless you
  68. // need this for something special, just go straight for
  69. // the SignedString.
  70. func (t *Token) SigningString() (string, error) {
  71. var err error
  72. var jsonValue []byte
  73. if jsonValue, err = json.Marshal(t.Header); err != nil {
  74. return "", err
  75. }
  76. header := EncodeSegment(jsonValue)
  77. if jsonValue, err = json.Marshal(t.Claims); err != nil {
  78. return "", err
  79. }
  80. claim := EncodeSegment(jsonValue)
  81. return strings.Join([]string{header, claim}, "."), 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. // ParseWithClaims is a shortcut for NewParser().ParseWithClaims().
  94. //
  95. // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
  96. // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
  97. // proper memory for it before passing in the overall claims, otherwise you might run into a panic.
  98. func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
  99. return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
  100. }
  101. // EncodeSegment encodes a JWT specific base64url encoding with padding stripped
  102. //
  103. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  104. // should only be used internally
  105. func EncodeSegment(seg []byte) string {
  106. return base64.RawURLEncoding.EncodeToString(seg)
  107. }
  108. // DecodeSegment decodes a JWT specific base64url encoding with padding stripped
  109. //
  110. // Deprecated: In a future release, we will demote this function to a non-exported function, since it
  111. // should only be used internally
  112. func DecodeSegment(seg string) ([]byte, error) {
  113. encoding := base64.RawURLEncoding
  114. if DecodePaddingAllowed {
  115. if l := len(seg) % 4; l > 0 {
  116. seg += strings.Repeat("=", 4-l)
  117. }
  118. encoding = base64.URLEncoding
  119. }
  120. if DecodeStrict {
  121. encoding = encoding.Strict()
  122. }
  123. return encoding.DecodeString(seg)
  124. }