oidc.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. algorithms []string
  65. // Raw claims returned by the server.
  66. rawClaims []byte
  67. remoteKeySet KeySet
  68. }
  69. type cachedKeys struct {
  70. keys []jose.JSONWebKey
  71. expiry time.Time
  72. }
  73. type providerJSON struct {
  74. Issuer string `json:"issuer"`
  75. AuthURL string `json:"authorization_endpoint"`
  76. TokenURL string `json:"token_endpoint"`
  77. JWKSURL string `json:"jwks_uri"`
  78. UserInfoURL string `json:"userinfo_endpoint"`
  79. Algorithms []string `json:"id_token_signing_alg_values_supported"`
  80. }
  81. // supportedAlgorithms is a list of algorithms explicitly supported by this
  82. // package. If a provider supports other algorithms, such as HS256 or none,
  83. // those values won't be passed to the IDTokenVerifier.
  84. var supportedAlgorithms = map[string]bool{
  85. RS256: true,
  86. RS384: true,
  87. RS512: true,
  88. ES256: true,
  89. ES384: true,
  90. ES512: true,
  91. PS256: true,
  92. PS384: true,
  93. PS512: true,
  94. }
  95. // NewProvider uses the OpenID Connect discovery mechanism to construct a Provider.
  96. //
  97. // The issuer is the URL identifier for the service. For example: "https://accounts.google.com"
  98. // or "https://login.salesforce.com".
  99. func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
  100. wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
  101. req, err := http.NewRequest("GET", wellKnown, nil)
  102. if err != nil {
  103. return nil, err
  104. }
  105. resp, err := doRequest(ctx, req)
  106. if err != nil {
  107. return nil, err
  108. }
  109. defer resp.Body.Close()
  110. body, err := ioutil.ReadAll(resp.Body)
  111. if err != nil {
  112. return nil, fmt.Errorf("unable to read response body: %v", err)
  113. }
  114. if resp.StatusCode != http.StatusOK {
  115. return nil, fmt.Errorf("%s: %s", resp.Status, body)
  116. }
  117. var p providerJSON
  118. err = unmarshalResp(resp, body, &p)
  119. if err != nil {
  120. return nil, fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
  121. }
  122. if p.Issuer != issuer {
  123. return nil, fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", issuer, p.Issuer)
  124. }
  125. var algs []string
  126. for _, a := range p.Algorithms {
  127. if supportedAlgorithms[a] {
  128. algs = append(algs, a)
  129. }
  130. }
  131. return &Provider{
  132. issuer: p.Issuer,
  133. authURL: p.AuthURL,
  134. tokenURL: p.TokenURL,
  135. userInfoURL: p.UserInfoURL,
  136. algorithms: algs,
  137. rawClaims: body,
  138. remoteKeySet: NewRemoteKeySet(ctx, p.JWKSURL),
  139. }, nil
  140. }
  141. // Claims unmarshals raw fields returned by the server during discovery.
  142. //
  143. // var claims struct {
  144. // ScopesSupported []string `json:"scopes_supported"`
  145. // ClaimsSupported []string `json:"claims_supported"`
  146. // }
  147. //
  148. // if err := provider.Claims(&claims); err != nil {
  149. // // handle unmarshaling error
  150. // }
  151. //
  152. // For a list of fields defined by the OpenID Connect spec see:
  153. // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
  154. func (p *Provider) Claims(v interface{}) error {
  155. if p.rawClaims == nil {
  156. return errors.New("oidc: claims not set")
  157. }
  158. return json.Unmarshal(p.rawClaims, v)
  159. }
  160. // Endpoint returns the OAuth2 auth and token endpoints for the given provider.
  161. func (p *Provider) Endpoint() oauth2.Endpoint {
  162. return oauth2.Endpoint{AuthURL: p.authURL, TokenURL: p.tokenURL}
  163. }
  164. // UserInfo represents the OpenID Connect userinfo claims.
  165. type UserInfo struct {
  166. Subject string `json:"sub"`
  167. Profile string `json:"profile"`
  168. Email string `json:"email"`
  169. EmailVerified bool `json:"email_verified"`
  170. claims []byte
  171. }
  172. // Claims unmarshals the raw JSON object claims into the provided object.
  173. func (u *UserInfo) Claims(v interface{}) error {
  174. if u.claims == nil {
  175. return errors.New("oidc: claims not set")
  176. }
  177. return json.Unmarshal(u.claims, v)
  178. }
  179. // UserInfo uses the token source to query the provider's user info endpoint.
  180. func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
  181. if p.userInfoURL == "" {
  182. return nil, errors.New("oidc: user info endpoint is not supported by this provider")
  183. }
  184. req, err := http.NewRequest("GET", p.userInfoURL, nil)
  185. if err != nil {
  186. return nil, fmt.Errorf("oidc: create GET request: %v", err)
  187. }
  188. token, err := tokenSource.Token()
  189. if err != nil {
  190. return nil, fmt.Errorf("oidc: get access token: %v", err)
  191. }
  192. token.SetAuthHeader(req)
  193. resp, err := doRequest(ctx, req)
  194. if err != nil {
  195. return nil, err
  196. }
  197. defer resp.Body.Close()
  198. body, err := ioutil.ReadAll(resp.Body)
  199. if err != nil {
  200. return nil, err
  201. }
  202. if resp.StatusCode != http.StatusOK {
  203. return nil, fmt.Errorf("%s: %s", resp.Status, body)
  204. }
  205. var userInfo UserInfo
  206. if err := json.Unmarshal(body, &userInfo); err != nil {
  207. return nil, fmt.Errorf("oidc: failed to decode userinfo: %v", err)
  208. }
  209. userInfo.claims = body
  210. return &userInfo, nil
  211. }
  212. // IDToken is an OpenID Connect extension that provides a predictable representation
  213. // of an authorization event.
  214. //
  215. // The ID Token only holds fields OpenID Connect requires. To access additional
  216. // claims returned by the server, use the Claims method.
  217. type IDToken struct {
  218. // The URL of the server which issued this token. OpenID Connect
  219. // requires this value always be identical to the URL used for
  220. // initial discovery.
  221. //
  222. // Note: Because of a known issue with Google Accounts' implementation
  223. // this value may differ when using Google.
  224. //
  225. // See: https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo
  226. Issuer string
  227. // The client ID, or set of client IDs, that this token is issued for. For
  228. // common uses, this is the client that initialized the auth flow.
  229. //
  230. // This package ensures the audience contains an expected value.
  231. Audience []string
  232. // A unique string which identifies the end user.
  233. Subject string
  234. // Expiry of the token. Ths package will not process tokens that have
  235. // expired unless that validation is explicitly turned off.
  236. Expiry time.Time
  237. // When the token was issued by the provider.
  238. IssuedAt time.Time
  239. // Initial nonce provided during the authentication redirect.
  240. //
  241. // This package does NOT provided verification on the value of this field
  242. // and it's the user's responsibility to ensure it contains a valid value.
  243. Nonce string
  244. // at_hash claim, if set in the ID token. Callers can verify an access token
  245. // that corresponds to the ID token using the VerifyAccessToken method.
  246. AccessTokenHash string
  247. // signature algorithm used for ID token, needed to compute a verification hash of an
  248. // access token
  249. sigAlgorithm string
  250. // Raw payload of the id_token.
  251. claims []byte
  252. // Map of distributed claim names to claim sources
  253. distributedClaims map[string]claimSource
  254. }
  255. // Claims unmarshals the raw JSON payload of the ID Token into a provided struct.
  256. //
  257. // idToken, err := idTokenVerifier.Verify(rawIDToken)
  258. // if err != nil {
  259. // // handle error
  260. // }
  261. // var claims struct {
  262. // Email string `json:"email"`
  263. // EmailVerified bool `json:"email_verified"`
  264. // }
  265. // if err := idToken.Claims(&claims); err != nil {
  266. // // handle error
  267. // }
  268. //
  269. func (i *IDToken) Claims(v interface{}) error {
  270. if i.claims == nil {
  271. return errors.New("oidc: claims not set")
  272. }
  273. return json.Unmarshal(i.claims, v)
  274. }
  275. // VerifyAccessToken verifies that the hash of the access token that corresponds to the iD token
  276. // matches the hash in the id token. It returns an error if the hashes don't match.
  277. // It is the caller's responsibility to ensure that the optional access token hash is present for the ID token
  278. // before calling this method. See https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
  279. func (i *IDToken) VerifyAccessToken(accessToken string) error {
  280. if i.AccessTokenHash == "" {
  281. return errNoAtHash
  282. }
  283. var h hash.Hash
  284. switch i.sigAlgorithm {
  285. case RS256, ES256, PS256:
  286. h = sha256.New()
  287. case RS384, ES384, PS384:
  288. h = sha512.New384()
  289. case RS512, ES512, PS512:
  290. h = sha512.New()
  291. default:
  292. return fmt.Errorf("oidc: unsupported signing algorithm %q", i.sigAlgorithm)
  293. }
  294. h.Write([]byte(accessToken)) // hash documents that Write will never return an error
  295. sum := h.Sum(nil)[:h.Size()/2]
  296. actual := base64.RawURLEncoding.EncodeToString(sum)
  297. if actual != i.AccessTokenHash {
  298. return errInvalidAtHash
  299. }
  300. return nil
  301. }
  302. type idToken struct {
  303. Issuer string `json:"iss"`
  304. Subject string `json:"sub"`
  305. Audience audience `json:"aud"`
  306. Expiry jsonTime `json:"exp"`
  307. IssuedAt jsonTime `json:"iat"`
  308. NotBefore *jsonTime `json:"nbf"`
  309. Nonce string `json:"nonce"`
  310. AtHash string `json:"at_hash"`
  311. ClaimNames map[string]string `json:"_claim_names"`
  312. ClaimSources map[string]claimSource `json:"_claim_sources"`
  313. }
  314. type claimSource struct {
  315. Endpoint string `json:"endpoint"`
  316. AccessToken string `json:"access_token"`
  317. }
  318. type audience []string
  319. func (a *audience) UnmarshalJSON(b []byte) error {
  320. var s string
  321. if json.Unmarshal(b, &s) == nil {
  322. *a = audience{s}
  323. return nil
  324. }
  325. var auds []string
  326. if err := json.Unmarshal(b, &auds); err != nil {
  327. return err
  328. }
  329. *a = audience(auds)
  330. return nil
  331. }
  332. type jsonTime time.Time
  333. func (j *jsonTime) UnmarshalJSON(b []byte) error {
  334. var n json.Number
  335. if err := json.Unmarshal(b, &n); err != nil {
  336. return err
  337. }
  338. var unix int64
  339. if t, err := n.Int64(); err == nil {
  340. unix = t
  341. } else {
  342. f, err := n.Float64()
  343. if err != nil {
  344. return err
  345. }
  346. unix = int64(f)
  347. }
  348. *j = jsonTime(time.Unix(unix, 0))
  349. return nil
  350. }
  351. func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
  352. err := json.Unmarshal(body, &v)
  353. if err == nil {
  354. return nil
  355. }
  356. ct := r.Header.Get("Content-Type")
  357. mediaType, _, parseErr := mime.ParseMediaType(ct)
  358. if parseErr == nil && mediaType == "application/json" {
  359. return fmt.Errorf("got Content-Type = application/json, but could not unmarshal as JSON: %v", err)
  360. }
  361. return fmt.Errorf("expected Content-Type = application/json, got %q: %v", ct, err)
  362. }