jwt.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jwt
  15. import (
  16. "bytes"
  17. "crypto"
  18. "crypto/rand"
  19. "crypto/rsa"
  20. "crypto/sha256"
  21. "encoding/base64"
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "strings"
  26. "time"
  27. )
  28. const (
  29. // HeaderAlgRSA256 is the RS256 [Header.Algorithm].
  30. HeaderAlgRSA256 = "RS256"
  31. // HeaderAlgES256 is the ES256 [Header.Algorithm].
  32. HeaderAlgES256 = "ES256"
  33. // HeaderType is the standard [Header.Type].
  34. HeaderType = "JWT"
  35. )
  36. // Header represents a JWT header.
  37. type Header struct {
  38. Algorithm string `json:"alg"`
  39. Type string `json:"typ"`
  40. KeyID string `json:"kid"`
  41. }
  42. func (h *Header) encode() (string, error) {
  43. b, err := json.Marshal(h)
  44. if err != nil {
  45. return "", err
  46. }
  47. return base64.RawURLEncoding.EncodeToString(b), nil
  48. }
  49. // Claims represents the claims set of a JWT.
  50. type Claims struct {
  51. // Iss is the issuer JWT claim.
  52. Iss string `json:"iss"`
  53. // Scope is the scope JWT claim.
  54. Scope string `json:"scope,omitempty"`
  55. // Exp is the expiry JWT claim. If unset, default is in one hour from now.
  56. Exp int64 `json:"exp"`
  57. // Iat is the subject issued at claim. If unset, default is now.
  58. Iat int64 `json:"iat"`
  59. // Aud is the audience JWT claim. Optional.
  60. Aud string `json:"aud"`
  61. // Sub is the subject JWT claim. Optional.
  62. Sub string `json:"sub,omitempty"`
  63. // AdditionalClaims contains any additional non-standard JWT claims. Optional.
  64. AdditionalClaims map[string]interface{} `json:"-"`
  65. }
  66. func (c *Claims) encode() (string, error) {
  67. // Compensate for skew
  68. now := time.Now().Add(-10 * time.Second)
  69. if c.Iat == 0 {
  70. c.Iat = now.Unix()
  71. }
  72. if c.Exp == 0 {
  73. c.Exp = now.Add(time.Hour).Unix()
  74. }
  75. if c.Exp < c.Iat {
  76. return "", fmt.Errorf("jwt: invalid Exp = %d; must be later than Iat = %d", c.Exp, c.Iat)
  77. }
  78. b, err := json.Marshal(c)
  79. if err != nil {
  80. return "", err
  81. }
  82. if len(c.AdditionalClaims) == 0 {
  83. return base64.RawURLEncoding.EncodeToString(b), nil
  84. }
  85. // Marshal private claim set and then append it to b.
  86. prv, err := json.Marshal(c.AdditionalClaims)
  87. if err != nil {
  88. return "", fmt.Errorf("invalid map of additional claims %v: %w", c.AdditionalClaims, err)
  89. }
  90. // Concatenate public and private claim JSON objects.
  91. if !bytes.HasSuffix(b, []byte{'}'}) {
  92. return "", fmt.Errorf("invalid JSON %s", b)
  93. }
  94. if !bytes.HasPrefix(prv, []byte{'{'}) {
  95. return "", fmt.Errorf("invalid JSON %s", prv)
  96. }
  97. b[len(b)-1] = ',' // Replace closing curly brace with a comma.
  98. b = append(b, prv[1:]...) // Append private claims.
  99. return base64.RawURLEncoding.EncodeToString(b), nil
  100. }
  101. // EncodeJWS encodes the data using the provided key as a JSON web signature.
  102. func EncodeJWS(header *Header, c *Claims, key *rsa.PrivateKey) (string, error) {
  103. head, err := header.encode()
  104. if err != nil {
  105. return "", err
  106. }
  107. claims, err := c.encode()
  108. if err != nil {
  109. return "", err
  110. }
  111. ss := fmt.Sprintf("%s.%s", head, claims)
  112. h := sha256.New()
  113. h.Write([]byte(ss))
  114. sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
  115. if err != nil {
  116. return "", err
  117. }
  118. return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil
  119. }
  120. // DecodeJWS decodes a claim set from a JWS payload.
  121. func DecodeJWS(payload string) (*Claims, error) {
  122. // decode returned id token to get expiry
  123. s := strings.Split(payload, ".")
  124. if len(s) < 2 {
  125. return nil, errors.New("invalid token received")
  126. }
  127. decoded, err := base64.RawURLEncoding.DecodeString(s[1])
  128. if err != nil {
  129. return nil, err
  130. }
  131. c := &Claims{}
  132. if err := json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c); err != nil {
  133. return nil, err
  134. }
  135. if err := json.NewDecoder(bytes.NewBuffer(decoded)).Decode(&c.AdditionalClaims); err != nil {
  136. return nil, err
  137. }
  138. return c, err
  139. }
  140. // VerifyJWS tests whether the provided JWT token's signature was produced by
  141. // the private key associated with the provided public key.
  142. func VerifyJWS(token string, key *rsa.PublicKey) error {
  143. parts := strings.Split(token, ".")
  144. if len(parts) != 3 {
  145. return errors.New("jwt: invalid token received, token must have 3 parts")
  146. }
  147. signedContent := parts[0] + "." + parts[1]
  148. signatureString, err := base64.RawURLEncoding.DecodeString(parts[2])
  149. if err != nil {
  150. return err
  151. }
  152. h := sha256.New()
  153. h.Write([]byte(signedContent))
  154. return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), signatureString)
  155. }