oidc

package module
v0.0.0-...-9e11711 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 28, 2016 License: Apache-2.0 Imports: 15 Imported by: 0

README

go-oidc

GoDoc Build Status

OpenID Connect support for Go

This package enables OpenID Connect support for the golang.org/x/oauth2 package.

provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
if err != nil {
    // handle error
}

// Configure an OpenID Connect aware OAuth2 client.
oauth2Config := oauth2.Config{
    ClientID:     clientID,
    ClientSecret: clientSecret,
    RedirectURL:  redirectURL,

    // Discovery returns the OAuth2 endpoints.
    Endpoint: provider.Endpoint(),

    // "openid" is a required scope for OpenID Connect flows.
    Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}

OAuth2 redirects are unchanged.

func handleRedirect(w http.ResponseWriter, r *http.Request) {
    http.Redirect(w, r, oauth2Config.AuthCodeURL(state), http.StatusFound)
}

The on responses, the provider can be used to verify ID Tokens.

var verifier = provider.Verifier()

func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
    // Verify state and errors.

    oauth2Token, err := oauth2Config.Exchange(ctx, r.URL.Query().Get("code"))
    if err != nil {
        // handle error
    }

    // Extract the ID Token from OAuth2 token.
    rawIDToken, ok := oauth2Token.Extra("id_token").(string)
    if !ok {
        // handle missing token
    }

    // Parse and verify ID Token payload.
    idToken, err := verifier.Verify(ctx, rawIDToken)
    if err != nil {
        // handle error
    }

    // Extract custom claims
    var claims struct {
        Email    string `json:"email"`
        Verified bool   `json:"email_verified"`
    }
    if err := idToken.Claims(&claims); err != nil {
        // handle error
    }
}

Documentation

Overview

Package oidc implements OpenID Connect client logic for the golang.org/x/oauth2 package.

Index

Constants

View Source
const (
	// JOSE asymmetric signing algorithm values as defined by RFC 7518
	//
	// see: https://tools.ietf.org/html/rfc7518#section-3.1
	RS256 = "RS256" // RSASSA-PKCS-v1.5 using SHA-256
	RS384 = "RS384" // RSASSA-PKCS-v1.5 using SHA-384
	RS512 = "RS512" // RSASSA-PKCS-v1.5 using SHA-512
	ES256 = "ES256" // ECDSA using P-256 and SHA-256
	ES384 = "ES384" // ECDSA using P-384 and SHA-384
	ES512 = "ES512" // ECDSA using P-521 and SHA-512
	PS256 = "PS256" // RSASSA-PSS using SHA256 and MGF1-SHA256
	PS384 = "PS384" // RSASSA-PSS using SHA384 and MGF1-SHA384
	PS512 = "PS512" // RSASSA-PSS using SHA512 and MGF1-SHA512
)
View Source
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"
)

Variables

This section is empty.

Functions

func ClientContext

func ClientContext(ctx context.Context, client *http.Client) context.Context

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 Nonce

func Nonce(nonce string) oauth2.AuthCodeOption

Nonce returns an auth code option which requires the ID Token created by the OpenID Connect provider to contain the specified nonce.

Types

type IDToken

type IDToken struct {
	// The URL of the server which issued this token. This will always be the same
	// as the URL used for initial discovery.
	Issuer string

	// The client, or set of clients, that this token is issued for.
	Audience []string

	// A unique string which identifies the end user.
	Subject string

	IssuedAt time.Time
	Expiry   time.Time
	Nonce    string
	// contains filtered or unexported fields
}

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.

func (*IDToken) Claims

func (i *IDToken) Claims(v interface{}) error

Claims unmarshals the raw JSON payload of the ID Token into a provided struct.

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
}

type IDTokenVerifier

type IDTokenVerifier struct {
	// contains filtered or unexported fields
}

IDTokenVerifier provides verification for ID Tokens.

func (*IDTokenVerifier) Verify

func (v *IDTokenVerifier) Verify(ctx context.Context, rawIDToken string) (*IDToken, error)

Verify parses a raw ID Token, verifies it's been signed by the provider, preforms any additional checks passed as VerifictionOptions, and returns the payload.

See: https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation

oauth2Token, err := oauth2Config.Exchange(ctx, r.URL.Query().Get("code"))
if err != nil {
    // handle error
}

// Extract the ID Token from oauth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
    // handle error
}

token, err := verifier.Verify(ctx, rawIDToken)

type NonceSource

type NonceSource interface {
	ClaimNonce(nonce string) error
}

NonceSource represents a source which can verify a nonce is valid and has not been claimed before.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider represents an OpenID Connect server's configuration.

func NewProvider

func NewProvider(ctx context.Context, issuer string) (*Provider, error)

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".

func (*Provider) Claims

func (p *Provider) Claims(v interface{}) error

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

func (*Provider) Endpoint

func (p *Provider) Endpoint() oauth2.Endpoint

Endpoint returns the OAuth2 auth and token endpoints for the given provider.

func (*Provider) UserInfo

func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error)

UserInfo uses the token source to query the provider's user info endpoint.

func (*Provider) Verifier

func (p *Provider) Verifier(options ...VerificationOption) *IDTokenVerifier

Verifier returns an IDTokenVerifier that uses the provider's key set to verify JWTs.

The returned IDTokenVerifier is tied to the Provider's context and its behavior is undefined once the Provider's context is canceled.

type UserInfo

type UserInfo struct {
	Subject       string `json:"sub"`
	Profile       string `json:"profile"`
	Email         string `json:"email"`
	EmailVerified bool   `json:"email_verified"`
	// contains filtered or unexported fields
}

UserInfo represents the OpenID Connect userinfo claims.

func (*UserInfo) Claims

func (u *UserInfo) Claims(v interface{}) error

Claims unmarshals the raw JSON object claims into the provided object.

type VerificationOption

type VerificationOption interface {
	// contains filtered or unexported methods
}

VerificationOption provides additional checks on ID Tokens.

func VerifyAudience

func VerifyAudience(clientID string) VerificationOption

VerifyAudience ensures that an ID Token was issued for the specific client.

Note that a verified token may be valid for other clients, as OpenID Connect allows a token to have multiple audiences.

func VerifyExpiry

func VerifyExpiry() VerificationOption

VerifyExpiry ensures that an ID Token has not expired.

func VerifyNonce

func VerifyNonce(source NonceSource) VerificationOption

VerifyNonce ensures that the ID Token contains a nonce which can be claimed by the nonce source.

func VerifySigningAlg

func VerifySigningAlg(allowedAlgs ...string) VerificationOption

VerifySigningAlg enforces that an ID Token is signed by a specific signing algorithm.

Because so many providers only support RS256, if this verifiction option isn't used, the IDTokenVerifier defaults to only allowing RS256.

Directories

Path Synopsis
example
idtoken
This is an example application to demonstrate parsing an ID Token.
This is an example application to demonstrate parsing an ID Token.
nonce
This is an example application to demonstrate verifying an ID Token with a nonce.
This is an example application to demonstrate verifying an ID Token with a nonce.
userinfo
This is an example application to demonstrate querying the user info endpoint.
This is an example application to demonstrate querying the user info endpoint.
Package http is DEPRECATED.
Package http is DEPRECATED.
Package jose is DEPRECATED.
Package jose is DEPRECATED.
Package key is DEPRECATED.
Package key is DEPRECATED.
Package oauth2 is DEPRECATED.
Package oauth2 is DEPRECATED.
Package oidc is DEPRECATED.
Package oidc is DEPRECATED.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL