dex/vendor/github.com/coreos/go-oidc/oidc.go

375 lines
11 KiB
Go
Raw Normal View History

2016-11-18 04:51:26 +05:30
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
2016-07-26 01:30:28 +05:30
package oidc
import (
2017-03-09 00:03:36 +05:30
"context"
2019-06-20 21:57:47 +05:30
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
2016-07-26 01:30:28 +05:30
"encoding/json"
"errors"
"fmt"
2019-06-20 21:57:47 +05:30
"hash"
2016-07-26 01:30:28 +05:30
"io/ioutil"
2019-06-20 21:57:47 +05:30
"mime"
2016-07-26 01:30:28 +05:30
"net/http"
"strings"
"time"
"golang.org/x/oauth2"
2016-11-18 04:51:26 +05:30
jose "gopkg.in/square/go-jose.v2"
2016-07-26 01:30:28 +05:30
)
const (
// ScopeOpenID is the mandatory scope for all OpenID Connect OAuth2 requests.
ScopeOpenID = "openid"
// ScopeOfflineAccess is an optional scope defined by OpenID Connect for requesting
// OAuth2 refresh tokens.
//
// Support for this scope differs between OpenID Connect providers. For instance
// Google rejects it, favoring appending "access_type=offline" as part of the
// authorization request instead.
//
// See: https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess
ScopeOfflineAccess = "offline_access"
)
2019-06-20 21:57:47 +05:30
var (
errNoAtHash = errors.New("id token did not have an access token hash")
errInvalidAtHash = errors.New("access token hash does not match value in ID token")
)
2016-11-18 04:51:26 +05:30
// ClientContext returns a new Context that carries the provided HTTP client.
//
// This method sets the same context key used by the golang.org/x/oauth2 package,
// so the returned context works for that package too.
//
// myClient := &http.Client{}
// ctx := oidc.ClientContext(parentContext, myClient)
//
// // This will use the custom client
// provider, err := oidc.NewProvider(ctx, "https://accounts.example.com")
//
func ClientContext(ctx context.Context, client *http.Client) context.Context {
return context.WithValue(ctx, oauth2.HTTPClient, client)
}
2017-03-09 00:03:36 +05:30
func doRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
client := http.DefaultClient
if c, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok {
client = c
2016-11-18 04:51:26 +05:30
}
2017-03-09 00:03:36 +05:30
return client.Do(req.WithContext(ctx))
2016-11-18 04:51:26 +05:30
}
// Provider represents an OpenID Connect server's configuration.
2016-07-26 01:30:28 +05:30
type Provider struct {
2016-11-18 04:51:26 +05:30
issuer string
authURL string
tokenURL string
userInfoURL string
// Raw claims returned by the server.
rawClaims []byte
2019-06-20 21:57:47 +05:30
remoteKeySet KeySet
2016-11-18 04:51:26 +05:30
}
type cachedKeys struct {
keys []jose.JSONWebKey
expiry time.Time
}
type providerJSON struct {
2016-07-26 01:30:28 +05:30
Issuer string `json:"issuer"`
AuthURL string `json:"authorization_endpoint"`
TokenURL string `json:"token_endpoint"`
JWKSURL string `json:"jwks_uri"`
UserInfoURL string `json:"userinfo_endpoint"`
}
2016-11-18 04:51:26 +05:30
// NewProvider uses the OpenID Connect discovery mechanism to construct a Provider.
//
// The issuer is the URL identifier for the service. For example: "https://accounts.google.com"
// or "https://login.salesforce.com".
2016-07-26 01:30:28 +05:30
func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
2017-03-09 00:03:36 +05:30
req, err := http.NewRequest("GET", wellKnown, nil)
if err != nil {
return nil, err
}
resp, err := doRequest(ctx, req)
2016-07-26 01:30:28 +05:30
if err != nil {
return nil, err
}
2019-06-20 21:57:47 +05:30
defer resp.Body.Close()
2016-07-26 01:30:28 +05:30
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
2019-06-20 21:57:47 +05:30
return nil, fmt.Errorf("unable to read response body: %v", err)
2016-07-26 01:30:28 +05:30
}
2019-06-20 21:57:47 +05:30
2016-07-26 01:30:28 +05:30
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
2019-06-20 21:57:47 +05:30
2016-11-18 04:51:26 +05:30
var p providerJSON
2019-06-20 21:57:47 +05:30
err = unmarshalResp(resp, body, &p)
if err != nil {
2016-07-26 01:30:28 +05:30
return nil, fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
}
2019-06-20 21:57:47 +05:30
2016-07-26 01:30:28 +05:30
if p.Issuer != issuer {
return nil, fmt.Errorf("oidc: issuer did not match the issuer returned by provider, expected %q got %q", issuer, p.Issuer)
}
2016-11-18 04:51:26 +05:30
return &Provider{
issuer: p.Issuer,
authURL: p.AuthURL,
tokenURL: p.TokenURL,
userInfoURL: p.UserInfoURL,
rawClaims: body,
2019-06-20 21:57:47 +05:30
remoteKeySet: NewRemoteKeySet(ctx, p.JWKSURL),
2016-11-18 04:51:26 +05:30
}, nil
2016-07-26 01:30:28 +05:30
}
2016-11-18 04:51:26 +05:30
// Claims unmarshals raw fields returned by the server during discovery.
//
// var claims struct {
// ScopesSupported []string `json:"scopes_supported"`
// ClaimsSupported []string `json:"claims_supported"`
// }
//
// if err := provider.Claims(&claims); err != nil {
// // handle unmarshaling error
// }
//
// For a list of fields defined by the OpenID Connect spec see:
// https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
2016-08-09 00:15:51 +05:30
func (p *Provider) Claims(v interface{}) error {
if p.rawClaims == nil {
return errors.New("oidc: claims not set")
2016-07-26 01:30:28 +05:30
}
2016-08-09 00:15:51 +05:30
return json.Unmarshal(p.rawClaims, v)
2016-07-26 01:30:28 +05:30
}
// Endpoint returns the OAuth2 auth and token endpoints for the given provider.
func (p *Provider) Endpoint() oauth2.Endpoint {
2016-11-18 04:51:26 +05:30
return oauth2.Endpoint{AuthURL: p.authURL, TokenURL: p.tokenURL}
2016-07-26 01:30:28 +05:30
}
// UserInfo represents the OpenID Connect userinfo claims.
type UserInfo struct {
Subject string `json:"sub"`
Profile string `json:"profile"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
2016-08-09 00:15:51 +05:30
claims []byte
2016-07-26 01:30:28 +05:30
}
2016-08-09 00:15:51 +05:30
// Claims unmarshals the raw JSON object claims into the provided object.
func (u *UserInfo) Claims(v interface{}) error {
if u.claims == nil {
return errors.New("oidc: claims not set")
2016-07-26 01:30:28 +05:30
}
2016-08-09 00:15:51 +05:30
return json.Unmarshal(u.claims, v)
2016-07-26 01:30:28 +05:30
}
// UserInfo uses the token source to query the provider's user info endpoint.
func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
2016-11-18 04:51:26 +05:30
if p.userInfoURL == "" {
return nil, errors.New("oidc: user info endpoint is not supported by this provider")
2016-07-26 01:30:28 +05:30
}
2016-12-02 02:46:14 +05:30
req, err := http.NewRequest("GET", p.userInfoURL, nil)
if err != nil {
return nil, fmt.Errorf("oidc: create GET request: %v", err)
}
token, err := tokenSource.Token()
if err != nil {
return nil, fmt.Errorf("oidc: get access token: %v", err)
}
token.SetAuthHeader(req)
2017-03-09 00:03:36 +05:30
resp, err := doRequest(ctx, req)
2016-07-26 01:30:28 +05:30
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %s", resp.Status, body)
}
var userInfo UserInfo
if err := json.Unmarshal(body, &userInfo); err != nil {
return nil, fmt.Errorf("oidc: failed to decode userinfo: %v", err)
}
2016-08-09 00:15:51 +05:30
userInfo.claims = body
2016-07-26 01:30:28 +05:30
return &userInfo, nil
}
2016-08-09 00:15:51 +05:30
// IDToken is an OpenID Connect extension that provides a predictable representation
// of an authorization event.
//
// The ID Token only holds fields OpenID Connect requires. To access additional
// claims returned by the server, use the Claims method.
type IDToken struct {
2017-03-09 00:03:36 +05:30
// The URL of the server which issued this token. OpenID Connect
// requires this value always be identical to the URL used for
// initial discovery.
//
// Note: Because of a known issue with Google Accounts' implementation
// this value may differ when using Google.
//
// See: https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo
2016-08-09 00:15:51 +05:30
Issuer string
2017-03-09 00:03:36 +05:30
// The client ID, or set of client IDs, that this token is issued for. For
// common uses, this is the client that initialized the auth flow.
//
// This package ensures the audience contains an expected value.
2016-08-09 00:15:51 +05:30
Audience []string
// A unique string which identifies the end user.
Subject string
2017-03-09 00:03:36 +05:30
// Expiry of the token. Ths package will not process tokens that have
// expired unless that validation is explicitly turned off.
Expiry time.Time
// When the token was issued by the provider.
2016-08-09 00:15:51 +05:30
IssuedAt time.Time
2017-03-09 00:03:36 +05:30
// Initial nonce provided during the authentication redirect.
//
2019-06-20 21:57:47 +05:30
// This package does NOT provided verification on the value of this field
// and it's the user's responsibility to ensure it contains a valid value.
2017-03-09 00:03:36 +05:30
Nonce string
2016-08-09 00:15:51 +05:30
2019-06-20 21:57:47 +05:30
// at_hash claim, if set in the ID token. Callers can verify an access token
// that corresponds to the ID token using the VerifyAccessToken method.
AccessTokenHash string
// signature algorithm used for ID token, needed to compute a verification hash of an
// access token
sigAlgorithm string
2016-11-18 04:51:26 +05:30
// Raw payload of the id_token.
2016-08-09 00:15:51 +05:30
claims []byte
}
// Claims unmarshals the raw JSON payload of the ID Token into a provided struct.
2016-11-18 04:51:26 +05:30
//
// idToken, err := idTokenVerifier.Verify(rawIDToken)
// if err != nil {
// // handle error
// }
// var claims struct {
// Email string `json:"email"`
// EmailVerified bool `json:"email_verified"`
// }
// if err := idToken.Claims(&claims); err != nil {
// // handle error
// }
//
2016-08-09 00:15:51 +05:30
func (i *IDToken) Claims(v interface{}) error {
if i.claims == nil {
return errors.New("oidc: claims not set")
}
return json.Unmarshal(i.claims, v)
}
2019-06-20 21:57:47 +05:30
// VerifyAccessToken verifies that the hash of the access token that corresponds to the iD token
// matches the hash in the id token. It returns an error if the hashes don't match.
// It is the caller's responsibility to ensure that the optional access token hash is present for the ID token
// before calling this method. See https://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
func (i *IDToken) VerifyAccessToken(accessToken string) error {
if i.AccessTokenHash == "" {
return errNoAtHash
}
var h hash.Hash
switch i.sigAlgorithm {
case RS256, ES256, PS256:
h = sha256.New()
case RS384, ES384, PS384:
h = sha512.New384()
case RS512, ES512, PS512:
h = sha512.New()
default:
return fmt.Errorf("oidc: unsupported signing algorithm %q", i.sigAlgorithm)
}
h.Write([]byte(accessToken)) // hash documents that Write will never return an error
sum := h.Sum(nil)[:h.Size()/2]
actual := base64.RawURLEncoding.EncodeToString(sum)
if actual != i.AccessTokenHash {
return errInvalidAtHash
}
return nil
}
2016-11-18 04:51:26 +05:30
type idToken struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience audience `json:"aud"`
Expiry jsonTime `json:"exp"`
IssuedAt jsonTime `json:"iat"`
Nonce string `json:"nonce"`
2019-06-20 21:57:47 +05:30
AtHash string `json:"at_hash"`
2016-11-18 04:51:26 +05:30
}
2016-08-09 00:15:51 +05:30
type audience []string
func (a *audience) UnmarshalJSON(b []byte) error {
var s string
if json.Unmarshal(b, &s) == nil {
*a = audience{s}
return nil
}
var auds []string
if err := json.Unmarshal(b, &auds); err != nil {
return err
}
*a = audience(auds)
return nil
}
type jsonTime time.Time
func (j *jsonTime) UnmarshalJSON(b []byte) error {
var n json.Number
if err := json.Unmarshal(b, &n); err != nil {
return err
}
var unix int64
if t, err := n.Int64(); err == nil {
unix = t
} else {
f, err := n.Float64()
if err != nil {
return err
}
unix = int64(f)
}
*j = jsonTime(time.Unix(unix, 0))
return nil
}
2019-06-20 21:57:47 +05:30
func unmarshalResp(r *http.Response, body []byte, v interface{}) error {
err := json.Unmarshal(body, &v)
if err == nil {
return nil
}
ct := r.Header.Get("Content-Type")
mediaType, _, parseErr := mime.ParseMediaType(ct)
if parseErr == nil && mediaType == "application/json" {
return fmt.Errorf("got Content-Type = application/json, but could not unmarshal as JSON: %v", err)
}
return fmt.Errorf("expected Content-Type = application/json, got %q: %v", ct, err)
2016-07-26 01:30:28 +05:30
}