oidc.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
  2. package oidc
  3. import (
  4. "context"
  5. "crypto/sha256"
  6. "crypto/sha512"
  7. "encoding/base64"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "hash"
  12. "io/ioutil"
  13. "mime"
  14. "net/http"
  15. "strings"
  16. "time"
  17. "golang.org/x/oauth2"
  18. jose "gopkg.in/square/go-jose.v2"
  19. )
  20. const (
  21. // ScopeOpenID is the mandatory scope for all OpenID Connect OAuth2 requests.
  22. ScopeOpenID = "openid"
  23. // ScopeOfflineAccess is an optional scope defined by OpenID Connect for requesting
  24. // OAuth2 refresh tokens.
  25. //
  26. // Support for this scope differs between OpenID Connect providers. For instance
  27. // Google rejects it, favoring appending "access_type=offline" as part of the
  28. // authorization request instead.
  29. //
  30. // See: https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
  31. ScopeOfflineAccess = "offline_access"
  32. )
  33. var (
  34. errNoAtHash = errors.New("id token did not have an access token hash")
  35. errInvalidAtHash = errors.New("access token hash does not match value in ID token")
  36. )
  37. // ClientContext returns a new Context that carries the provided HTTP client.
  38. //
  39. // This method sets the same context key used by the golang.org/x/oauth2 package,
  40. // so the returned context works for that package too.
  41. //
  42. // myClient := &http.Client{}
  43. // ctx := oidc.ClientContext(parentContext, myClient)
  44. //
  45. // // This will use the custom client
  46. // provider, err := oidc.NewProvider(ctx, "https://accounts.example.com")
  47. //
  48. func ClientContext(ctx context.Context, client *http.Client) context.Context {
  49. return context.WithValue(ctx, oauth2.HTTPClient, client)
  50. }
  51. func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
  52. client := http.DefaultClient
  53. if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
  54. client = c
  55. }
  56. return client.Do(req.WithContext(ctx))
  57. }
  58. // Provider represents an OpenID Connect server's configuration.
  59. type Provider struct {
  60. issuer string
  61. authURL string
  62. tokenURL string
  63. userInfoURL string
  64. // Raw claims returned by the server.
  65. rawClaims []byte
  66. remoteKeySet KeySet
  67. }
  68. type cachedKeys struct {
  69. keys []jose.JSONWebKey
  70. expiry time.Time
  71. }
  72. type providerJSON struct {
  73. Issuer string `json:"issuer"`
  74. AuthURL string `json:"authorization_endpoint"`
  75. TokenURL string `json:"token_endpoint"`
  76. JWKSURL string `json:"jwks_uri"`
  77. UserInfoURL string `json:"userinfo_endpoint"`
  78. }
  79. // NewProvider uses the OpenID Connect discovery mechanism to construct a Provider.
  80. //
  81. // The issuer is the URL identifier for the service. For example: "https://accounts.google.com"
  82. // or "https://login.salesforce.com".
  83. func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
  84. wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
  85. req, err := http.NewRequest("GET", wellKnown, nil)
  86. if err != nil {
  87. return nil, err
  88. }
  89. resp, err := doRequest(ctx, req)
  90. if err != nil {
  91. return nil, err
  92. }
  93. defer resp.Body.Close()
  94. body, err := ioutil.ReadAll(resp.Body)
  95. if err != nil {
  96. return nil, fmt.Errorf("unable to read response body: %v", err)
  97. }
  98. if resp.StatusCode != http.StatusOK {
  99. return nil, fmt.Errorf("%s: %s", resp.Status, body)
  100. }
  101. var p providerJSON
  102. err = unmarshalResp(resp, body, &p)
  103. if err != nil {
  104. return nil, fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
  105. }
  106. if p.Issuer != issuer {
  107. return nil, fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", issuer, p.Issuer)
  108. }
  109. return &Provider{
  110. issuer: p.Issuer,
  111. authURL: p.AuthURL,
  112. tokenURL: p.TokenURL,
  113. userInfoURL: p.UserInfoURL,
  114. rawClaims: body,
  115. remoteKeySet: NewRemoteKeySet(ctx, p.JWKSURL),
  116. }, nil
  117. }
  118. // Claims unmarshals raw fields returned by the server during discovery.
  119. //
  120. // var claims struct {
  121. // ScopesSupported []string `json:"scopes_supported"`
  122. // ClaimsSupported []string `json:"claims_supported"`
  123. // }
  124. //
  125. // if err := provider.Claims(&claims); err != nil {
  126. // // handle unmarshaling error
  127. // }
  128. //
  129. // For a list of fields defined by the OpenID Connect spec see:
  130. // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
  131. func (p *Provider) Claims(v interface{}) error {
  132. if p.rawClaims == nil {
  133. return errors.New("oidc: claims not set")
  134. }
  135. return json.Unmarshal(p.rawClaims, v)
  136. }
  137. // Endpoint returns the OAuth2 auth and token endpoints for the given provider.
  138. func (p *Provider) Endpoint() oauth2.Endpoint {
  139. return oauth2.Endpoint{AuthURL: p.authURL, TokenURL: p.tokenURL}
  140. }
  141. // UserInfo represents the OpenID Connect userinfo claims.
  142. type UserInfo struct {
  143. Subject string `json:"sub"`
  144. Profile string `json:"profile"`
  145. Email string `json:"email"`
  146. EmailVerified bool `json:"email_verified"`
  147. claims []byte
  148. }
  149. // Claims unmarshals the raw JSON object claims into the provided object.
  150. func (u *UserInfo) Claims(v interface{}) error {
  151. if u.claims == nil {
  152. return errors.New("oidc: claims not set")
  153. }
  154. return json.Unmarshal(u.claims, v)
  155. }
  156. // UserInfo uses the token source to query the provider's user info endpoint.
  157. func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
  158. if p.userInfoURL == "" {
  159. return nil, errors.New("oidc: user info endpoint is not supported by this provider")
  160. }
  161. req, err := http.NewRequest("GET", p.userInfoURL, nil)
  162. if err != nil {
  163. return nil, fmt.Errorf("oidc: create GET request: %v", err)
  164. }
  165. token, err := tokenSource.Token()
  166. if err != nil {
  167. return nil, fmt.Errorf("oidc: get access token: %v", err)
  168. }
  169. token.SetAuthHeader(req)
  170. resp, err := doRequest(ctx, req)
  171. if err != nil {
  172. return nil, err
  173. }
  174. defer resp.Body.Close()
  175. body, err := ioutil.ReadAll(resp.Body)
  176. if err != nil {
  177. return nil, err
  178. }
  179. if resp.StatusCode != http.StatusOK {
  180. return nil, fmt.Errorf("%s: %s", resp.Status, body)
  181. }
  182. var userInfo UserInfo
  183. if err := json.Unmarshal(body, &userInfo); err != nil {
  184. return nil, fmt.Errorf("oidc: failed to decode userinfo: %v", err)
  185. }
  186. userInfo.claims = body
  187. return &userInfo, nil
  188. }
  189. // IDToken is an OpenID Connect extension that provides a predictable representation
  190. // of an authorization event.
  191. //
  192. // The ID Token only holds fields OpenID Connect requires. To access additional
  193. // claims returned by the server, use the Claims method.
  194. type IDToken struct {
  195. // The URL of the server which issued this token. OpenID Connect
  196. // requires this value always be identical to the URL used for
  197. // initial discovery.
  198. //
  199. // Note: Because of a known issue with Google Accounts' implementation
  200. // this value may differ when using Google.
  201. //
  202. // See: https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo
  203. Issuer string
  204. // The client ID, or set of client IDs, that this token is issued for. For
  205. // common uses, this is the client that initialized the auth flow.
  206. //
  207. // This package ensures the audience contains an expected value.
  208. Audience []string
  209. // A unique string which identifies the end user.
  210. Subject string
  211. // Expiry of the token. Ths package will not process tokens that have
  212. // expired unless that validation is explicitly turned off.
  213. Expiry time.Time
  214. // When the token was issued by the provider.
  215. IssuedAt time.Time
  216. // Initial nonce provided during the authentication redirect.
  217. //
  218. // This package does NOT provided verification on the value of this field
  219. // and it's the user's responsibility to ensure it contains a valid value.
  220. Nonce string
  221. // at_hash claim, if set in the ID token. Callers can verify an access token
  222. // that corresponds to the ID token using the VerifyAccessToken method.
  223. AccessTokenHash string
  224. // signature algorithm used for ID token, needed to compute a verification hash of an
  225. // access token
  226. sigAlgorithm string
  227. // Raw payload of the id_token.
  228. claims []byte
  229. }
  230. // Claims unmarshals the raw JSON payload of the ID Token into a provided struct.
  231. //
  232. // idToken, err := idTokenVerifier.Verify(rawIDToken)
  233. // if err != nil {
  234. // // handle error
  235. // }
  236. // var claims struct {
  237. // Email string `json:"email"`
  238. // EmailVerified bool `json:"email_verified"`
  239. // }
  240. // if err := idToken.Claims(&claims); err != nil {
  241. // // handle error
  242. // }
  243. //
  244. func (i *IDToken) Claims(v interface{}) error {
  245. if i.claims == nil {
  246. return errors.New("oidc: claims not set")
  247. }
  248. return json.Unmarshal(i.claims, v)
  249. }
  250. // VerifyAccessToken verifies that the hash of the access token that corresponds to the iD token
  251. // matches the hash in the id token. It returns an error if the hashes don't match.
  252. // It is the caller's responsibility to ensure that the optional access token hash is present for the ID token
  253. // before calling this method. See https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  254. func (i *IDToken) VerifyAccessToken(accessToken string) error {
  255. if i.AccessTokenHash == "" {
  256. return errNoAtHash
  257. }
  258. var h hash.Hash
  259. switch i.sigAlgorithm {
  260. case RS256, ES256, PS256:
  261. h = sha256.New()
  262. case RS384, ES384, PS384:
  263. h = sha512.New384()
  264. case RS512, ES512, PS512:
  265. h = sha512.New()
  266. default:
  267. return fmt.Errorf("oidc: unsupported signing algorithm %q", i.sigAlgorithm)
  268. }
  269. h.Write([]byte(accessToken)) // hash documents that Write will never return an error
  270. sum := h.Sum(nil)[:h.Size()/2]
  271. actual := base64.RawURLEncoding.EncodeToString(sum)
  272. if actual != i.AccessTokenHash {
  273. return errInvalidAtHash
  274. }
  275. return nil
  276. }
  277. type idToken struct {
  278. Issuer string `json:"iss"`
  279. Subject string `json:"sub"`
  280. Audience audience `json:"aud"`
  281. Expiry jsonTime `json:"exp"`
  282. IssuedAt jsonTime `json:"iat"`
  283. Nonce string `json:"nonce"`
  284. AtHash string `json:"at_hash"`
  285. }
  286. type audience []string
  287. func (a *audience) UnmarshalJSON(b []byte) error {
  288. var s string
  289. if json.Unmarshal(b, &s) == nil {
  290. *a = audience{s}
  291. return nil
  292. }
  293. var auds []string
  294. if err := json.Unmarshal(b, &auds); err != nil {
  295. return err
  296. }
  297. *a = audience(auds)
  298. return nil
  299. }
  300. type jsonTime time.Time
  301. func (j *jsonTime) UnmarshalJSON(b []byte) error {
  302. var n json.Number
  303. if err := json.Unmarshal(b, &n); err != nil {
  304. return err
  305. }
  306. var unix int64
  307. if t, err := n.Int64(); err == nil {
  308. unix = t
  309. } else {
  310. f, err := n.Float64()
  311. if err != nil {
  312. return err
  313. }
  314. unix = int64(f)
  315. }
  316. *j = jsonTime(time.Unix(unix, 0))
  317. return nil
  318. }
  319. func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
  320. err := json.Unmarshal(body, &v)
  321. if err == nil {
  322. return nil
  323. }
  324. ct := r.Header.Get("Content-Type")
  325. mediaType, _, parseErr := mime.ParseMediaType(ct)
  326. if parseErr == nil && mediaType == "application/json" {
  327. return fmt.Errorf("got Content-Type = application/json, but could not unmarshal as JSON: %v", err)
  328. }
  329. return fmt.Errorf("expected Content-Type = application/json, got %q: %v", ct, err)
  330. }