2016-11-17 23:21:26 +00:00
|
|
|
// Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.
|
2016-07-25 20:00:28 +00:00
|
|
|
package oidc
|
|
|
|
|
|
|
|
import (
|
2017-03-08 18:33:36 +00:00
|
|
|
"context"
|
2016-07-25 20:00:28 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/oauth2"
|
2016-11-17 23:21:26 +00:00
|
|
|
jose "gopkg.in/square/go-jose.v2"
|
2016-07-25 20:00:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
// 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-08 18:33:36 +00:00
|
|
|
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-17 23:21:26 +00:00
|
|
|
}
|
2017-03-08 18:33:36 +00:00
|
|
|
return client.Do(req.WithContext(ctx))
|
2016-11-17 23:21:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Provider represents an OpenID Connect server's configuration.
|
2016-07-25 20:00:28 +00:00
|
|
|
type Provider struct {
|
2016-11-17 23:21:26 +00:00
|
|
|
issuer string
|
|
|
|
authURL string
|
|
|
|
tokenURL string
|
|
|
|
userInfoURL string
|
|
|
|
|
|
|
|
// Raw claims returned by the server.
|
|
|
|
rawClaims []byte
|
|
|
|
|
|
|
|
remoteKeySet *remoteKeySet
|
|
|
|
}
|
|
|
|
|
|
|
|
type cachedKeys struct {
|
|
|
|
keys []jose.JSONWebKey
|
|
|
|
expiry time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
type providerJSON struct {
|
2016-07-25 20:00:28 +00:00
|
|
|
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-17 23:21:26 +00:00
|
|
|
// 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-25 20:00:28 +00:00
|
|
|
func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
|
|
|
|
wellKnown := strings.TrimSuffix(issuer, "/") + "/.well-known/openid-configuration"
|
2017-03-08 18:33:36 +00:00
|
|
|
req, err := http.NewRequest("GET", wellKnown, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
resp, err := doRequest(ctx, req)
|
2016-07-25 20:00:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2016-11-17 23:21:26 +00:00
|
|
|
var p providerJSON
|
2016-07-25 20:00:28 +00:00
|
|
|
if err := json.Unmarshal(body, &p); err != nil {
|
|
|
|
return nil, fmt.Errorf("oidc: failed to decode provider discovery object: %v", err)
|
|
|
|
}
|
|
|
|
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-17 23:21:26 +00:00
|
|
|
return &Provider{
|
|
|
|
issuer: p.Issuer,
|
|
|
|
authURL: p.AuthURL,
|
|
|
|
tokenURL: p.TokenURL,
|
|
|
|
userInfoURL: p.UserInfoURL,
|
|
|
|
rawClaims: body,
|
|
|
|
remoteKeySet: newRemoteKeySet(ctx, p.JWKSURL, time.Now),
|
|
|
|
}, nil
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
func (p *Provider) Claims(v interface{}) error {
|
|
|
|
if p.rawClaims == nil {
|
|
|
|
return errors.New("oidc: claims not set")
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2016-08-08 18:45:51 +00:00
|
|
|
return json.Unmarshal(p.rawClaims, v)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Endpoint returns the OAuth2 auth and token endpoints for the given provider.
|
|
|
|
func (p *Provider) Endpoint() oauth2.Endpoint {
|
2016-11-17 23:21:26 +00:00
|
|
|
return oauth2.Endpoint{AuthURL: p.authURL, TokenURL: p.tokenURL}
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
claims []byte
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
2016-08-08 18:45:51 +00:00
|
|
|
// 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-25 20:00:28 +00:00
|
|
|
}
|
2016-08-08 18:45:51 +00:00
|
|
|
return json.Unmarshal(u.claims, v)
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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-17 23:21:26 +00:00
|
|
|
if p.userInfoURL == "" {
|
|
|
|
return nil, errors.New("oidc: user info endpoint is not supported by this provider")
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|
2016-12-01 21:16:14 +00:00
|
|
|
|
|
|
|
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-08 18:33:36 +00:00
|
|
|
resp, err := doRequest(ctx, req)
|
2016-07-25 20:00:28 +00:00
|
|
|
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-08 18:45:51 +00:00
|
|
|
userInfo.claims = body
|
2016-07-25 20:00:28 +00:00
|
|
|
return &userInfo, nil
|
|
|
|
}
|
|
|
|
|
2016-08-08 18:45:51 +00:00
|
|
|
// 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-08 18:33:36 +00:00
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
Issuer string
|
|
|
|
|
2017-03-08 18:33:36 +00:00
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
Audience []string
|
|
|
|
|
|
|
|
// A unique string which identifies the end user.
|
|
|
|
Subject string
|
|
|
|
|
2017-03-08 18:33:36 +00:00
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
IssuedAt time.Time
|
2017-03-08 18:33:36 +00:00
|
|
|
|
|
|
|
// Initial nonce provided during the authentication redirect.
|
|
|
|
//
|
|
|
|
// If present, this package ensures this is a valid nonce.
|
|
|
|
Nonce string
|
2016-08-08 18:45:51 +00:00
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
// Raw payload of the id_token.
|
2016-08-08 18:45:51 +00:00
|
|
|
claims []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
// Claims unmarshals the raw JSON payload of the ID Token into a provided struct.
|
2016-11-17 23:21:26 +00:00
|
|
|
//
|
|
|
|
// 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-08 18:45:51 +00:00
|
|
|
func (i *IDToken) Claims(v interface{}) error {
|
|
|
|
if i.claims == nil {
|
|
|
|
return errors.New("oidc: claims not set")
|
|
|
|
}
|
|
|
|
return json.Unmarshal(i.claims, v)
|
|
|
|
}
|
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
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"`
|
|
|
|
}
|
|
|
|
|
2016-08-08 18:45:51 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
func (a audience) MarshalJSON() ([]byte, error) {
|
|
|
|
if len(a) == 1 {
|
|
|
|
return json.Marshal(a[0])
|
|
|
|
}
|
|
|
|
return json.Marshal([]string(a))
|
|
|
|
}
|
|
|
|
|
2016-08-08 18:45:51 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-11-17 23:21:26 +00:00
|
|
|
func (j jsonTime) MarshalJSON() ([]byte, error) {
|
|
|
|
return json.Marshal(time.Time(j).Unix())
|
2016-07-25 20:00:28 +00:00
|
|
|
}
|