package
0.7.0
Repository: https://github.com/hashicorp/cap.git
Documentation: pkg.go.dev

# README

oidc

Go Reference

oidc is a package for writing clients that integrate with OIDC Providers using OIDC flows.

Primary types provided by the package:

  • Request: represents one OIDC authentication flow for a user. It contains the data needed to uniquely represent that one-time flow across the multiple interactions needed to complete the OIDC flow the user is attempting. All Requests contain an expiration for the user's OIDC flow.

  • Token: represents an OIDC id_token, as well as an Oauth2 access_token and refresh_token (including the the access_token expiry)

  • Config: provides the configuration for a typical 3-legged OIDC authorization code flow (for example: client ID/Secret, redirectURL, supported signing algorithms, additional scopes requested, etc)

  • Provider: provides integration with an OIDC provider. The provider provides capabilities like: generating an auth URL, exchanging codes for tokens, verifying tokens, making user info requests, etc.

  • Alg: represents asymmetric signing algorithms

  • Error: provides an error and provides the ability to specify an error code, operation that raised the error, the kind of error, and any wrapped error

oidc.callback

Go Reference

The callback package includes handlers (http.HandlerFunc) which can be used for the callback leg an OIDC flow. Callback handlers for both the authorization code flow (with optional PKCE) and the implicit flow are provided.


Examples:

  • CLI example which implements an OIDC user authentication CLI.

  • SPA example which implements an OIDC user authentication SPA (single page app).


Example of a provider using an authorization code flow:

// Create a new provider config
pc, err := oidc.NewConfig(
  "http://your-issuer.com/",
  "your_client_id",
  "your_client_secret",
  []oidc.Alg{oidc.RS256},
  []string{"http://your_redirect_url"},
)
if err != nil {
  // handle error
}

// Create a provider
p, err := oidc.NewProvider(pc)
if err != nil {
  // handle error
}
defer p.Done()

	
// Create a Request for a user's authentication attempt that will use the
// authorization code flow.  (See NewRequest(...) using the WithPKCE and
// WithImplicit options for creating a Request that uses those flows.)	
oidcRequest, err := oidc.NewRequest(2 * time.Minute, "http://your_redirect_url/callback")
if err != nil {
  // handle error
}

// Create an auth URL
authURL, err := p.AuthURL(context.Background(), oidcRequest)
if err != nil {
  // handle error
}
fmt.Println("open url to kick-off authentication: ", authURL)

Create a http.Handler for OIDC authentication response redirects.

func NewHandler(ctx context.Context, p *oidc.Provider, rw callback.RequestReader) (http.HandlerFunc, error)
  if p == nil { 
    // handle error
  }
  if rw == nil {
    // handle error
  }
  return func(w http.ResponseWriter, r *http.Request) {
    oidcRequest, err := rw.Read(ctx, req.FormValue("state"))
    if err != nil {
      // handle error
    }
    // Exchange(...) will verify the tokens before returning. 
    token, err := p.Exchange(ctx, oidcRequest, req.FormValue("state"), req.FormValue("code"))
    if err != nil {
      // handle error
    }
    var claims map[string]interface{}
    if err := t.IDToken().Claims(&claims); err != nil {
      // handle error
    }

    // Get the user's claims via the provider's UserInfo endpoint
    var infoClaims map[string]interface{}
    err = p.UserInfo(ctx, token.StaticTokenSource(), claims["sub"].(string), &infoClaims)
    if err != nil {
      // handle error
    }
    resp := struct {
	  IDTokenClaims  map[string]interface{}
	  UserInfoClaims map[string]interface{}
    }{claims, infoClaims}
    enc := json.NewEncoder(w)
    if err := enc.Encode(resp); err != nil {
	    // handle error
    }
  }
}

# Packages

callback is a package that provides callbacks (in the form of http.HandlerFunc) for handling OIDC provider responses to authorization code flow (with optional PKCE) and implicit flow authentication attempts.
No description provided by the author

# Functions

ApplyOpts takes a pointer to the options struct as a set of default options and applies the slice of opts as overrides.
CreateCodeChallenge creates a code challenge from the verifier.
EncodeCertificates will encode a number of x509 certificates to PEM.
NewCodeVerifier creates a new CodeVerifier (*S256Verifier).
NewConfig composes a new config for a provider.
NewID generates a ID with an optional prefix.
NewProvider creates and initializes a Provider.
NewRequest creates a new Request (*Req).
NewTestingLogger makes a new TestingLogger.
NewToken creates a new Token (*Tk).
StartTestProvider creates and starts a running TestProvider http server.
TestGenerateCA will generate a test x509 CA cert, along with it encoded in a PEM format.
TestGenerateKeys will generate a test ECDSA P-256 pub/priv key pair.
TestSignJWT will bundle the provided claims into a test signed JWT.
UnmarshalClaims will retrieve the claims from the provided raw JWT token.
WithACRValues optionally specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference.
WithAudiences provides an optional list of audiences.
WithClaims optionally requests that specific claims be returned using the claims parameter.
WithDisplay optionally specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.
WithImplicitFlow provides an option to use an OIDC implicit flow with form post.
WithMaxAge provides an optional maximum authentication age, which is the allowable elapsed time in seconds since the last time the user was actively authenticated by the provider.
WithNonce optionally specifies a value to use for the request's nonce.
WithNoTLS provides the option to not use TLS for the test provider.
WithNow provides an optional func for determining what the current time it is.
WithPKCE provides an option to use a CodeVerifier with the authorization code flow with PKCE.
WithPrefix provides an optional prefix for an new ID.
WithPrompts provides an optional list of values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent.
WithProviderCA provides optional CA certs (PEM encoded) for the provider's config.
WithProviderConfig provides an optional ProviderConfig which supports creating a provider that doesn't support OIDC discovery.
WithRoundTripper provides and optional RoundTripper for the provider's config.
WithScopes provides an optional list of scopes.
WithState optionally specifies a value to use for the request's state.
WithTestDefaults provides an option to provide a set of defaults to StartTestProvider(...) which make it much more composable.
WithTestHost provides an optional address for the test provider.
WithTestPort provides an optional port for the test provider.
WithUILocales optionally specifies End-User's preferred languages via language Tags, ordered by preference.

# Constants

No description provided by the author
DefaultIDLength is the default length for generated IDs, which are used for state and nonce parameters during OIDC flows.
No description provided by the author
ECDSA using P-256 and SHA-256.
ECDSA using P-384 and SHA-384.
ECDSA using P-521 and SHA-512.
No description provided by the author
Defined the Prompt values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent.
Defined the Display values that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.
No description provided by the author
RSASSA-PSS using SHA256 and MGF1-SHA256.
RSASSA-PSS using SHA384 and MGF1-SHA384.
RSASSA-PSS using SHA512 and MGF1-SHA512.
RedactedAccessToken is the redacted string or json for an oauth access_token.
RedactedClientSecret is the redacted string or json for an oauth client secret.
RedactedIDToken is the redacted string or json for an oidc id_token.
RedactedRefreshToken is the redacted string or json for an oauth refresh_token.
RequestExpirySkew defines a time skew when checking a Request's expiration.
RSASSA-PKCS-v1.5 using SHA-256.
RSASSA-PKCS-v1.5 using SHA-384.
RSASSA-PKCS-v1.5 using SHA-512.
SHA-256.
No description provided by the author
TokenExpirySkew defines a time skew when checking a Token's expiration.
No description provided by the author
No description provided by the author

# Variables

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

Config represents the configuration for an OIDC provider used by a relying party.
DiscoveryInfo is the Provider's configuration info which is published to a well-known discoverable location (based on the Issuer of the provider).
Provider provides integration with an OIDC provider.
ProviderConfig supports creating a provider that doesn't support OIDC discovery.
Req represents the oidc request used for oidc flows and implements the Request interface.
S256Verifier represents an OAuth PKCE code verifier that uses the S256 challenge method.
TestingLogger defines a logger that will implement the TestingT interface so it can be used with StartTestProvider(...) as its t TestingT parameter.
TestProvider is a local http server that supports test provider capabilities which makes writing tests much easier.
TestProviderDefaults define a type for composing all the defaults for StartTestProvider(...).
TestSigningKey defines a type for specifying a test signing key and algorithm when providing TestProviderDefaults.
TestSubject is a struct that contains various values for customizing per-user responses via SubjectInfo in TestProvider.
Tk satisfies the Token interface and represents an Oauth2 access_token and refresh_token (including the the access_token expiry), as well as an OIDC id_token.

# Interfaces

CleanupT defines an single function interface for a testing.Cleanup(func()).
CodeVerifier represents an OAuth PKCE code verifier.
HelperT defines a single function interface for a testing.Helper().
InfofT defines a single function interface for a Info(format string, args ...interface{}).
Request basically represents one OIDC authentication flow for a user.
StaticTokenSource is a single function interface that defines a method to create a oauth2.TokenSource that always returns the same token.
TestingT defines a very slim interface required by the TestProvider and any test functions it uses.
Token interface represents an OIDC id_token, as well as an Oauth2 access_token and refresh_token (including the the access_token expiry).

# Type aliases

AccessToken is an oauth access_token.
Alg represents asymmetric signing algorithms.
ChallengeMethod represents PKCE code challenge methods as defined by RFC 7636.
ClientSecret is an oauth client Secret.
Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.
IDToken is an oidc id_token.
Option defines a common functional options type which can be used in a variadic parameter pattern.
Prompt is a string values that specifies whether the Authorization Server prompts the End-User for reauthentication and consent.
RefreshToken is an oauth refresh_token.