jws.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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 encoding and decoding utilities for
  5. // signed JWS messages.
  6. package jws // import "golang.org/x/oauth2/jws"
  7. import (
  8. "bytes"
  9. "crypto"
  10. "crypto/rand"
  11. "crypto/rsa"
  12. "crypto/sha256"
  13. "encoding/base64"
  14. "encoding/json"
  15. "errors"
  16. "fmt"
  17. "strings"
  18. "time"
  19. )
  20. // ClaimSet contains information about the JWT signature including the
  21. // permissions being requested (scopes), the target of the token, the issuer,
  22. // the time the token was issued, and the lifetime of the token.
  23. type ClaimSet struct {
  24. Iss string `json:"iss"` // email address of the client_id of the application making the access token request
  25. Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
  26. Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
  27. Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch)
  28. Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch)
  29. Typ string `json:"typ,omitempty"` // token type (Optional).
  30. // Email for which the application is requesting delegated access (Optional).
  31. Sub string `json:"sub,omitempty"`
  32. // The old name of Sub. Client keeps setting Prn to be
  33. // complaint with legacy OAuth 2.0 providers. (Optional)
  34. Prn string `json:"prn,omitempty"`
  35. // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
  36. // This array is marshalled using custom code (see (c *ClaimSet) encode()).
  37. PrivateClaims map[string]interface{} `json:"-"`
  38. }
  39. func (c *ClaimSet) encode() (string, error) {
  40. // Reverting time back for machines whose time is not perfectly in sync.
  41. // If client machine's time is in the future according
  42. // to Google servers, an access token will not be issued.
  43. now := time.Now().Add(-10 * time.Second)
  44. if c.Iat == 0 {
  45. c.Iat = now.Unix()
  46. }
  47. if c.Exp == 0 {
  48. c.Exp = now.Add(time.Hour).Unix()
  49. }
  50. if c.Exp < c.Iat {
  51. return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat)
  52. }
  53. b, err := json.Marshal(c)
  54. if err != nil {
  55. return "", err
  56. }
  57. if len(c.PrivateClaims) == 0 {
  58. return base64Encode(b), nil
  59. }
  60. // Marshal private claim set and then append it to b.
  61. prv, err := json.Marshal(c.PrivateClaims)
  62. if err != nil {
  63. return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
  64. }
  65. // Concatenate public and private claim JSON objects.
  66. if !bytes.HasSuffix(b, []byte{'}'}) {
  67. return "", fmt.Errorf("jws: invalid JSON %s", b)
  68. }
  69. if !bytes.HasPrefix(prv, []byte{'{'}) {
  70. return "", fmt.Errorf("jws: invalid JSON %s", prv)
  71. }
  72. b[len(b)-1] = ',' // Replace closing curly brace with a comma.
  73. b = append(b, prv[1:]...) // Append private claims.
  74. return base64Encode(b), nil
  75. }
  76. // Header represents the header for the signed JWS payloads.
  77. type Header struct {
  78. // The algorithm used for signature.
  79. Algorithm string `json:"alg"`
  80. // Represents the token type.
  81. Typ string `json:"typ"`
  82. }
  83. func (h *Header) encode() (string, error) {
  84. b, err := json.Marshal(h)
  85. if err != nil {
  86. return "", err
  87. }
  88. return base64Encode(b), nil
  89. }
  90. // Decode decodes a claim set from a JWS payload.
  91. func Decode(payload string) (*ClaimSet, error) {
  92. // decode returned id token to get expiry
  93. s := strings.Split(payload, ".")
  94. if len(s) < 2 {
  95. // TODO(jbd): Provide more context about the error.
  96. return nil, errors.New("jws: invalid token received")
  97. }
  98. decoded, err := base64Decode(s[1])
  99. if err != nil {
  100. return nil, err
  101. }
  102. c := &ClaimSet{}
  103. err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
  104. return c, err
  105. }
  106. // Signer returns a signature for the given data.
  107. type Signer func(data []byte) (sig []byte, err error)
  108. // EncodeWithSigner encodes a header and claim set with the provided signer.
  109. func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) {
  110. head, err := header.encode()
  111. if err != nil {
  112. return "", err
  113. }
  114. cs, err := c.encode()
  115. if err != nil {
  116. return "", err
  117. }
  118. ss := fmt.Sprintf("%s.%s", head, cs)
  119. sig, err := sg([]byte(ss))
  120. if err != nil {
  121. return "", err
  122. }
  123. return fmt.Sprintf("%s.%s", ss, base64Encode(sig)), nil
  124. }
  125. // Encode encodes a signed JWS with provided header and claim set.
  126. // This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key.
  127. func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) {
  128. sg := func(data []byte) (sig []byte, err error) {
  129. h := sha256.New()
  130. h.Write([]byte(data))
  131. return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil))
  132. }
  133. return EncodeWithSigner(header, c, sg)
  134. }
  135. // base64Encode returns and Base64url encoded version of the input string with any
  136. // trailing "=" stripped.
  137. func base64Encode(b []byte) string {
  138. return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
  139. }
  140. // base64Decode decodes the Base64url encoded string
  141. func base64Decode(s string) ([]byte, error) {
  142. // add back missing padding
  143. switch len(s) % 4 {
  144. case 1:
  145. s += "==="
  146. case 2:
  147. s += "=="
  148. case 3:
  149. s += "="
  150. }
  151. return base64.URLEncoding.DecodeString(s)
  152. }