jws.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package jws provides a partial implementation
  5. // of JSON Web Signature encoding and decoding.
  6. // It exists to support the golang.org/x/oauth2 package.
  7. //
  8. // See RFC 7515.
  9. //
  10. // Deprecated: this package is not intended for public use and might be
  11. // removed in the future. It exists for internal use only.
  12. // Please switch to another JWS package or copy this package into your own
  13. // source tree.
  14. package jws // import "golang.org/x/oauth2/jws"
  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. // ClaimSet contains information about the JWT signature including the
  29. // permissions being requested (scopes), the target of the token, the issuer,
  30. // the time the token was issued, and the lifetime of the token.
  31. type ClaimSet struct {
  32. Iss string `json:"iss"` // email address of the client_id of the application making the access token request
  33. Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
  34. Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
  35. Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch)
  36. Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch)
  37. Typ string `json:"typ,omitempty"` // token type (Optional).
  38. // Email for which the application is requesting delegated access (Optional).
  39. Sub string `json:"sub,omitempty"`
  40. // The old name of Sub. Client keeps setting Prn to be
  41. // complaint with legacy OAuth 2.0 providers. (Optional)
  42. Prn string `json:"prn,omitempty"`
  43. // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
  44. // This array is marshalled using custom code (see (c *ClaimSet) encode()).
  45. PrivateClaims map[string]interface{} `json:"-"`
  46. }
  47. func (c *ClaimSet) encode() (string, error) {
  48. // Reverting time back for machines whose time is not perfectly in sync.
  49. // If client machine's time is in the future according
  50. // to Google servers, an access token will not be issued.
  51. now := time.Now().Add(-10 * time.Second)
  52. if c.Iat == 0 {
  53. c.Iat = now.Unix()
  54. }
  55. if c.Exp == 0 {
  56. c.Exp = now.Add(time.Hour).Unix()
  57. }
  58. if c.Exp < c.Iat {
  59. return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat)
  60. }
  61. b, err := json.Marshal(c)
  62. if err != nil {
  63. return "", err
  64. }
  65. if len(c.PrivateClaims) == 0 {
  66. return base64.RawURLEncoding.EncodeToString(b), nil
  67. }
  68. // Marshal private claim set and then append it to b.
  69. prv, err := json.Marshal(c.PrivateClaims)
  70. if err != nil {
  71. return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
  72. }
  73. // Concatenate public and private claim JSON objects.
  74. if !bytes.HasSuffix(b, []byte{'}'}) {
  75. return "", fmt.Errorf("jws: invalid JSON %s", b)
  76. }
  77. if !bytes.HasPrefix(prv, []byte{'{'}) {
  78. return "", fmt.Errorf("jws: invalid JSON %s", prv)
  79. }
  80. b[len(b)-1] = ',' // Replace closing curly brace with a comma.
  81. b = append(b, prv[1:]...) // Append private claims.
  82. return base64.RawURLEncoding.EncodeToString(b), nil
  83. }
  84. // Header represents the header for the signed JWS payloads.
  85. type Header struct {
  86. // The algorithm used for signature.
  87. Algorithm string `json:"alg"`
  88. // Represents the token type.
  89. Typ string `json:"typ"`
  90. // The optional hint of which key is being used.
  91. KeyID string `json:"kid,omitempty"`
  92. }
  93. func (h *Header) encode() (string, error) {
  94. b, err := json.Marshal(h)
  95. if err != nil {
  96. return "", err
  97. }
  98. return base64.RawURLEncoding.EncodeToString(b), nil
  99. }
  100. // Decode decodes a claim set from a JWS payload.
  101. func Decode(payload string) (*ClaimSet, error) {
  102. // decode returned id token to get expiry
  103. s := strings.Split(payload, ".")
  104. if len(s) < 2 {
  105. // TODO(jbd): Provide more context about the error.
  106. return nil, errors.New("jws: invalid token received")
  107. }
  108. decoded, err := base64.RawURLEncoding.DecodeString(s[1])
  109. if err != nil {
  110. return nil, err
  111. }
  112. c := &ClaimSet{}
  113. err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
  114. return c, err
  115. }
  116. // Signer returns a signature for the given data.
  117. type Signer func(data []byte) (sig []byte, err error)
  118. // EncodeWithSigner encodes a header and claim set with the provided signer.
  119. func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) {
  120. head, err := header.encode()
  121. if err != nil {
  122. return "", err
  123. }
  124. cs, err := c.encode()
  125. if err != nil {
  126. return "", err
  127. }
  128. ss := fmt.Sprintf("%s.%s", head, cs)
  129. sig, err := sg([]byte(ss))
  130. if err != nil {
  131. return "", err
  132. }
  133. return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(sig)), nil
  134. }
  135. // Encode encodes a signed JWS with provided header and claim set.
  136. // This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key.
  137. func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) {
  138. sg := func(data []byte) (sig []byte, err error) {
  139. h := sha256.New()
  140. h.Write(data)
  141. return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
  142. }
  143. return EncodeWithSigner(header, c, sg)
  144. }
  145. // Verify tests whether the provided JWT token's signature was produced by the private key
  146. // associated with the supplied public key.
  147. func Verify(token string, key *rsa.PublicKey) error {
  148. parts := strings.Split(token, ".")
  149. if len(parts) != 3 {
  150. return errors.New("jws: invalid token received, token must have 3 parts")
  151. }
  152. signedContent := parts[0] + "." + parts[1]
  153. signatureString, err := base64.RawURLEncoding.DecodeString(parts[2])
  154. if err != nil {
  155. return err
  156. }
  157. h := sha256.New()
  158. h.Write([]byte(signedContent))
  159. return rsa.VerifyPKCS1v15(key, crypto.SHA256, h.Sum(nil), signatureString)
  160. }