jws.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Copyright 2014 The oauth2 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
  28. Iat int64 `json:"iat"` // the time the assertion was issued.
  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. exp time.Time
  39. iat time.Time
  40. }
  41. func (c *ClaimSet) encode() (string, error) {
  42. if c.exp.IsZero() || c.iat.IsZero() {
  43. // Reverting time back for machines whose time is not perfectly in sync.
  44. // If client machine's time is in the future according
  45. // to Google servers, an access token will not be issued.
  46. now := time.Now().Add(-10 * time.Second)
  47. c.iat = now
  48. c.exp = now.Add(time.Hour)
  49. }
  50. c.Exp = c.exp.Unix()
  51. c.Iat = c.iat.Unix()
  52. b, err := json.Marshal(c)
  53. if err != nil {
  54. return "", err
  55. }
  56. if len(c.PrivateClaims) == 0 {
  57. return base64Encode(b), nil
  58. }
  59. // Marshal private claim set and then append it to b.
  60. prv, err := json.Marshal(c.PrivateClaims)
  61. if err != nil {
  62. return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims)
  63. }
  64. // Concatenate public and private claim JSON objects.
  65. if !bytes.HasSuffix(b, []byte{'}'}) {
  66. return "", fmt.Errorf("jws: invalid JSON %s", b)
  67. }
  68. if !bytes.HasPrefix(prv, []byte{'{'}) {
  69. return "", fmt.Errorf("jws: invalid JSON %s", prv)
  70. }
  71. b[len(b)-1] = ',' // Replace closing curly brace with a comma.
  72. b = append(b, prv[1:]...) // Append private claims.
  73. return base64Encode(b), nil
  74. }
  75. // Header represents the header for the signed JWS payloads.
  76. type Header struct {
  77. // The algorithm used for signature.
  78. Algorithm string `json:"alg"`
  79. // Represents the token type.
  80. Typ string `json:"typ"`
  81. }
  82. func (h *Header) encode() (string, error) {
  83. b, err := json.Marshal(h)
  84. if err != nil {
  85. return "", err
  86. }
  87. return base64Encode(b), nil
  88. }
  89. // Decode decodes a claim set from a JWS payload.
  90. func Decode(payload string) (*ClaimSet, error) {
  91. // decode returned id token to get expiry
  92. s := strings.Split(payload, ".")
  93. if len(s) < 2 {
  94. // TODO(jbd): Provide more context about the error.
  95. return nil, errors.New("jws: invalid token received")
  96. }
  97. decoded, err := base64Decode(s[1])
  98. if err != nil {
  99. return nil, err
  100. }
  101. c := &ClaimSet{}
  102. err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c)
  103. return c, err
  104. }
  105. // Encode encodes a signed JWS with provided header and claim set.
  106. func Encode(header *Header, c *ClaimSet, signature *rsa.PrivateKey) (string, error) {
  107. head, err := header.encode()
  108. if err != nil {
  109. return "", err
  110. }
  111. cs, err := c.encode()
  112. if err != nil {
  113. return "", err
  114. }
  115. ss := fmt.Sprintf("%s.%s", head, cs)
  116. h := sha256.New()
  117. h.Write([]byte(ss))
  118. b, err := rsa.SignPKCS1v15(rand.Reader, signature, crypto.SHA256, h.Sum(nil))
  119. if err != nil {
  120. return "", err
  121. }
  122. sig := base64Encode(b)
  123. return fmt.Sprintf("%s.%s", ss, sig), nil
  124. }
  125. // base64Encode returns and Base64url encoded version of the input string with any
  126. // trailing "=" stripped.
  127. func base64Encode(b []byte) string {
  128. return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=")
  129. }
  130. // base64Decode decodes the Base64url encoded string
  131. func base64Decode(s string) ([]byte, error) {
  132. // add back missing padding
  133. switch len(s) % 4 {
  134. case 2:
  135. s += "=="
  136. case 3:
  137. s += "="
  138. }
  139. return base64.URLEncoding.DecodeString(s)
  140. }