Documentation
¶
Overview ¶
Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests, as specified in RFC 6749. It can additionally grant authorization with Bearer JWT.
Copyright 2023 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
Index ¶
- Variables
- func GenerateVerifier() string
- func NewClient(ctx context.Context, src TokenSource) *http.Client
- func S256ChallengeFromVerifier(verifier string) string
- type AuthCodeOption
- type AuthStyle
- type BaseError
- type Config
- func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string
- func (c *Config) Client(ctx context.Context, t *Token) *http.Client
- func (c *Config) DeviceAccessToken(ctx context.Context, da *DeviceAuthResponse, opts ...AuthCodeOption) (*Token, error)
- func (c *Config) DeviceAuth(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuthResponse, error)
- func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error)
- func (c *Config) ParsedAuthCodeURL(state string, opts ...AuthCodeOption) (authURL *url.URL, err error)
- func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)
- func (c *Config) PushedAuth(ctx context.Context, state string, opts ...AuthCodeOption) (authURL *url.URL, par *PushedAuthResponse, err error)
- func (c *Config) RevokeToken(ctx context.Context, token *Token, opts ...RevocationOption) (err error)
- func (c *Config) Token(ctx context.Context, opts ...AuthCodeOption) (*Token, error)
- func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource
- type DeviceAuthResponse
- type Endpoint
- type Error
- type PKCE
- type PushedAuthResponse
- type RetrieveError
- type RevocationOption
- type RevokeError
- type Token
- type TokenSource
- type Transport
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var HTTPClient internal.ContextKey
HTTPClient is the context key to use with golang.org/x/net/context's WithValue function to associate an *http.Client value with a context.
Functions ¶
func GenerateVerifier ¶
func GenerateVerifier() string
GenerateVerifier generates a PKCE code verifier with 32 octets of randomness. This follows recommendations in RFC 7636.
A fresh verifier should be generated for each authorization. S256ChallengeOption(verifier) should then be passed to Config.AuthCodeURL (or Config.DeviceAccess) and VerifierOption(verifier) to Config.Exchange (or Config.DeviceAccessToken).
func NewClient ¶
func NewClient(ctx context.Context, src TokenSource) *http.Client
NewClient creates an *http.Client from a Context and TokenSource. The returned client is not valid beyond the lifetime of the context.
Note that if a custom *http.Client is provided via the Context it is used only for token acquisition and is not used to configure the *http.Client returned from NewClient.
As a special case, if src is nil, a non-OAuth2 client is returned using the provided context. This exists to support related OAuth2 packages.
func S256ChallengeFromVerifier ¶
S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256.
Prefer to use S256ChallengeOption where possible.
Types ¶
type AuthCodeOption ¶
type AuthCodeOption interface {
// contains filtered or unexported methods
}
An AuthCodeOption is passed to Config.AuthCodeURL.
var ( // AccessTypeOnline and AccessTypeOffline are options passed // to the Options.AuthCodeURL method. They modify the // "access_type" field that gets sent in the URL returned by // AuthCodeURL. // // Online is the default if neither is specified. If your // application needs to refresh access tokens when the user // is not present at the browser, then use offline. This will // result in your application obtaining a refresh token the // first time your application exchanges an authorization // code for a user. AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online") AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline") // ApprovalForce forces the users to view the consent dialog // and confirm the permissions request at the URL returned // from AuthCodeURL, even if they've already done so. ApprovalForce AuthCodeOption = SetAuthURLParam("prompt", "consent") )
func S256ChallengeOption ¶
func S256ChallengeOption(verifier string) AuthCodeOption
S256ChallengeOption derives a PKCE code challenge derived from verifier with method S256. It should be passed to Config.AuthCodeURL or Config.DeviceAccess only.
func SetAuthURLParam ¶
func SetAuthURLParam(key, value string) AuthCodeOption
SetAuthURLParam builds an AuthCodeOption which passes key/value parameters to a provider's authorization endpoint.
func VerifierOption ¶
func VerifierOption(verifier string) AuthCodeOption
VerifierOption returns a PKCE code verifier AuthCodeOption. It should be passed to Config.Exchange or Config.DeviceAccessToken only.
type AuthStyle ¶
type AuthStyle int
AuthStyle represents how requests for tokens are authenticated to the server.
const ( // AuthStyleAutoDetect means to auto-detect which authentication // style the provider wants by trying both ways and caching // the successful way for the future. AuthStyleAutoDetect AuthStyle = 0 // AuthStyleInParams sends the "client_id" and "client_secret" // in the POST body as application/x-www-form-urlencoded parameters. // This is also known as 'client_secret_post'. AuthStyleInParams AuthStyle = 1 // AuthStyleInHeader sends the client_id and client_password // using HTTP Basic Authorization. This is an optional style // described in the OAuth2 RFC 6749 section 2.3.1. // This is also known as 'client_secret_basic'. AuthStyleInHeader AuthStyle = 2 // ClientSecretBasic is an alias for AuthStyleInHeader. ClientSecretBasic = AuthStyleInHeader // ClientSecretPost is an alias for AuthStyleInParams. ClientSecretPost = AuthStyleInParams )
type BaseError ¶
type BaseError struct { Response *http.Response Body []byte // ErrorCode is RFC 6749's 'error' parameter. ErrorCode string // ErrorDescription is RFC 6749's 'error_description' parameter. ErrorDescription string // ErrorURI is RFC 6749's 'error_uri' parameter. ErrorURI string }
func (*BaseError) GetErrorCode ¶
func (*BaseError) GetErrorDescription ¶
func (*BaseError) GetErrorURI ¶
func (*BaseError) GetResponse ¶
type Config ¶
type Config struct { // ClientID is the application's ID. ClientID string // ClientSecret is the application's secret. ClientSecret string // Endpoint contains the resource server's token endpoint // URLs. These are constants specific to each server and are // often available via site-specific packages, such as // google.Endpoint or github.Endpoint. Endpoint Endpoint // RedirectURL is the URL to redirect users going through // the OAuth flow, after the resource owner's URLs. RedirectURL string // Scope specifies optional requested permissions. Scopes []string // contains filtered or unexported fields }
Config describes a typical 3-legged OAuth2 flow, with both the client application information and the server's endpoint URLs. For the client credentials 2-legged OAuth2 flow, see the clientcredentials package (https://authelia.com/client/oauth2/clientcredentials).
Example ¶
package main import ( "context" "fmt" "log" "authelia.com/client/oauth2" ) func main() { ctx := context.Background() conf := &oauth2.Config{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", Scopes: []string{"SCOPE1", "SCOPE2"}, Endpoint: oauth2.Endpoint{ AuthURL: "https://provider.com/o/oauth2/auth", TokenURL: "https://provider.com/o/oauth2/token", }, } // use PKCE to protect against CSRF attacks // https://www.ietf.org/archive/id/draft-ietf-oauth-security-topics-22.html#name-countermeasures-6 verifier := oauth2.GenerateVerifier() // Redirect user to consent page to ask for permission // for the scopes specified above. url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier)) fmt.Printf("Visit the URL for the auth dialog: %v", url) // Use the authorization code that is pushed to the redirect // URL. Exchange will do the handshake to retrieve the // initial access token. The HTTP Client returned by // conf.Client will refresh the token as necessary. var code string if _, err := fmt.Scan(&code); err != nil { log.Fatal(err) } tok, err := conf.Exchange(ctx, code, oauth2.VerifierOption(verifier)) if err != nil { log.Fatal(err) } client := conf.Client(ctx, tok) client.Get("...") }
Output:
Example (CustomHTTP) ¶
package main import ( "context" "fmt" "log" "net/http" "time" "authelia.com/client/oauth2" ) func main() { ctx := context.Background() conf := &oauth2.Config{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", Scopes: []string{"SCOPE1", "SCOPE2"}, Endpoint: oauth2.Endpoint{ TokenURL: "https://provider.com/o/oauth2/token", AuthURL: "https://provider.com/o/oauth2/auth", }, } // Redirect user to consent page to ask for permission // for the scopes specified above. url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) fmt.Printf("Visit the URL for the auth dialog: %v", url) // Use the authorization code that is pushed to the redirect // URL. Exchange will do the handshake to retrieve the // initial access token. The HTTP Client returned by // conf.Client will refresh the token as necessary. var code string if _, err := fmt.Scan(&code); err != nil { log.Fatal(err) } // Use the custom HTTP client when requesting a token. httpClient := &http.Client{Timeout: 2 * time.Second} ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) tok, err := conf.Exchange(ctx, code) if err != nil { log.Fatal(err) } client := conf.Client(ctx, tok) _ = client }
Output:
func (*Config) AuthCodeURL ¶
func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string
AuthCodeURL returns a URL to OAuth 2.0 provider's consent page that asks for permissions for the required scopes explicitly.
State is an opaque value used by the client to maintain state between the request and callback. The authorization server includes this value when redirecting the user agent back to the client.
Opts may include AccessTypeOnline or AccessTypeOffline, as well as ApprovalForce.
To protect against CSRF attacks, opts should include a PKCE challenge (S256ChallengeOption). Not all servers support PKCE. An alternative is to generate a random state parameter and verify it after exchange. See https://datatracker.ietf.org/doc/html/rfc6749#section-10.12 (predating PKCE), https://www.oauth.com/oauth2-servers/pkce/ and https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-09.html#name-cross-site-request-forgery (describing both approaches)
func (*Config) Client ¶
Client returns an HTTP client using the provided token. The token will auto-refresh as necessary. The underlying HTTP transport will be obtained using the provided context. The returned client and its Transport should not be modified.
func (*Config) DeviceAccessToken ¶
func (c *Config) DeviceAccessToken(ctx context.Context, da *DeviceAuthResponse, opts ...AuthCodeOption) (*Token, error)
DeviceAccessToken polls the server to exchange a device code for a token.
func (*Config) DeviceAuth ¶
func (c *Config) DeviceAuth(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuthResponse, error)
DeviceAuth returns a device auth struct which contains a device code and authorization information provided for users to enter on another device.
Example ¶
var config Config ctx := context.Background() response, err := config.DeviceAuth(ctx) if err != nil { panic(err) } fmt.Printf("please enter code %s at %s\n", response.UserCode, response.VerificationURI) token, err := config.DeviceAccessToken(ctx, response) if err != nil { panic(err) } fmt.Println(token)
Output:
func (*Config) Exchange ¶
Exchange converts an authorization code into a token.
It is used after a resource provider redirects the user back to the Redirect URI (the URL obtained from AuthCodeURL).
The provided context optionally controls which HTTP client is used. See the HTTPClient variable.
The code will be in the *http.Request.FormValue("code"). Before calling Exchange, be sure to validate FormValue("state") if you are using it to protect against CSRF attacks.
If using PKCE to protect against CSRF attacks, opts should include a VerifierOption.
func (*Config) ParsedAuthCodeURL ¶
func (c *Config) ParsedAuthCodeURL(state string, opts ...AuthCodeOption) (authURL *url.URL, err error)
ParsedAuthCodeURL is the same as AuthCodeURL just it wraps the result in url.Parse.
func (*Config) PasswordCredentialsToken ¶
func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)
PasswordCredentialsToken converts a resource owner username and password pair into a token.
Per the RFC, this grant type should only be used "when there is a high degree of trust between the resource owner and the client (e.g., the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available." See https://tools.ietf.org/html/rfc6749#section-4.3 for more info.
The provided context optionally controls which HTTP client is used. See the HTTPClient variable.
func (*Config) PushedAuth ¶
func (c *Config) PushedAuth(ctx context.Context, state string, opts ...AuthCodeOption) (authURL *url.URL, par *PushedAuthResponse, err error)
PushedAuth returns a pushed auth struct which contains a request uri and expires in information after making a HTTP POST request to the configured Pushed Auth URL. In addition, it returns the *url.URL of the properly formatted AuthURL for the PAR session provided the AuthURL Endpoint is configured.
func (*Config) RevokeToken ¶
func (c *Config) RevokeToken(ctx context.Context, token *Token, opts ...RevocationOption) (err error)
RevokeToken allows for simple token revocation.
func (*Config) Token ¶
Token is similar to Exchange except the grant type and code is not configured. This allows for manually performing flows other than the Authorization Code Flow.
func (*Config) TokenSource ¶
func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource
TokenSource returns a TokenSource that returns t until t expires, automatically refreshing it as necessary using the provided context.
Most users will use Config.Client instead.
type DeviceAuthResponse ¶
type DeviceAuthResponse struct { // DeviceCode DeviceCode string `json:"device_code"` // UserCode is the code the user should enter at the verification uri UserCode string `json:"user_code"` // VerificationURI is where user should enter the user code VerificationURI string `json:"verification_uri"` // VerificationURIComplete (if populated) includes the user code in the verification URI. This is typically shown to the user in non-textual form, such as a QR code. VerificationURIComplete string `json:"verification_uri_complete,omitempty"` // Expiry is when the device code and user code expire Expiry time.Time `json:"expires_in,omitempty"` // Interval is the duration in seconds that Poll should wait between requests Interval int64 `json:"interval,omitempty"` }
DeviceAuthResponse describes a successful RFC 8628 Device Authorization Response https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
func (DeviceAuthResponse) MarshalJSON ¶
func (d DeviceAuthResponse) MarshalJSON() ([]byte, error)
func (*DeviceAuthResponse) UnmarshalJSON ¶
func (d *DeviceAuthResponse) UnmarshalJSON(data []byte) (err error)
type Endpoint ¶
type Endpoint struct { AuthURL string DeviceAuthURL string PushedAuthURL string TokenURL string IntrospectionURL string RevocationURL string UserinfoURL string JWKSURL string // AuthStyle optionally specifies how the endpoint wants the // client ID & client secret sent. The zero value means to // auto-detect. AuthStyle AuthStyle }
Endpoint represents an OAuth 2.0 provider's authorization and token endpoint URLs.
type Error ¶
type Error interface { Error() string GetErrorCode() string GetErrorDescription() string GetErrorURI() string GetResponse() *http.Response GetBody() []byte }
Error interface for most error types, particularly new ones.
type PKCE ¶
type PKCE struct {
// contains filtered or unexported fields
}
func NewPKCEWithValues ¶
func (*PKCE) AuthCodeOptionChallenge ¶
func (pkce *PKCE) AuthCodeOptionChallenge() AuthCodeOption
AuthCodeOptionChallenge returns the option used for the challenge phase of PKCE i.e. the Config.PushedAuth or Config.AuthCodeURL functions.
func (*PKCE) AuthCodeOptionVerifier ¶
func (pkce *PKCE) AuthCodeOptionVerifier() AuthCodeOption
AuthCodeOptionVerifier returns the option used for the verifier phase of PKCE i.e. the Config.Exchange function.
func (*PKCE) ChallengeMethod ¶
ChallengeMethod returns a string representation of the current challenge method.
type PushedAuthResponse ¶
type PushedAuthResponse struct { // RequestURI is the request URI corresponding to the authorization request posted. This URI is a single-use // reference to the respective request data in the subsequent authorization request. The way the authorization // process obtains the authorization request data is at the discretion of the authorization server and is out of // scope of this specification. There is no need to make the authorization request data available to other parties // via this URI. RequestURI string `json:"request_uri"` // Interval is a JSON number that represents the lifetime of the request URI in seconds as a positive integer. The // request URI lifetime is at the discretion of the authorization server but will typically be relatively short // (e.g., between 5 and 600 seconds). ExpiresIn int64 `json:"expires_in"` }
PushedAuthResponse describes a successful RFC 8628 Device Authorization Response https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
type RetrieveError ¶
type RetrieveError struct {
*BaseError
}
RetrieveError is the error returned when the token endpoint returns a non-2XX HTTP status code or populates RFC 6749's 'error' parameter. https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
type RevocationOption ¶
type RevocationOption interface {
// contains filtered or unexported methods
}
func AddRevocationTokenTypes ¶
func AddRevocationTokenTypes(values ...string) RevocationOption
AddRevocationTokenTypes builds a RevocationOption which explicitly adds a token type hint to the revocation process. By default the oauth2.RevokeToken method will perform the access token revocation. If the authorization server requires the refresh token is revoked manually then use this option like oauth.AddRevocationTokenTypes("access_token", "refresh_token").
func SetRevocationURLParam ¶
func SetRevocationURLParam(key, value string) RevocationOption
SetRevocationURLParam builds a RevocationOption which passes key/value parameters to a provider's revocation endpoint.
type RevokeError ¶
type RevokeError struct {
*BaseError
}
type Token ¶
type Token struct { // AccessToken is the token that authorizes and authenticates // the requests. AccessToken string `json:"access_token"` // TokenType is the type of token. // The Type method returns either this or "Bearer", the default. TokenType string `json:"token_type,omitempty"` // RefreshToken is a token that's used by the application // (as opposed to the user) to refresh the access token // if it expires. RefreshToken string `json:"refresh_token,omitempty"` // Expiry is the optional expiration time of the access token. // // If zero, TokenSource implementations will reuse the same // token forever and RefreshToken or equivalent // mechanisms for that TokenSource will not be used. Expiry time.Time `json:"expiry,omitempty"` // contains filtered or unexported fields }
Token represents the credentials used to authorize the requests to access protected resources on the OAuth 2.0 provider's backend.
Most users of this package should not access fields of Token directly. They're exported mostly for use by related packages implementing derivative OAuth2 flows.
func (*Token) Extra ¶
Extra returns an extra field. Extra fields are key-value pairs returned by the server as a part of the token retrieval response.
func (*Token) SetAuthHeader ¶
SetAuthHeader sets the Authorization header to r using the access token in t.
This method is unnecessary when using Transport or an HTTP Client returned by this package.
type TokenSource ¶
type TokenSource interface { // Token returns a token or an error. // Token must be safe for concurrent use by multiple goroutines. // The returned Token must not be modified. Token() (*Token, error) }
A TokenSource is anything that can return a token.
func ReuseTokenSource ¶
func ReuseTokenSource(t *Token, src TokenSource) TokenSource
ReuseTokenSource returns a TokenSource which repeatedly returns the same token as long as it's valid, starting with t. When its cached token is invalid, a new token is obtained from src.
ReuseTokenSource is typically used to reuse tokens from a cache (such as a file on disk) between runs of a program, rather than obtaining new tokens unnecessarily.
The initial token t may be nil, in which case the TokenSource is wrapped in a caching version if it isn't one already. This also means it's always safe to wrap ReuseTokenSource around any other TokenSource without adverse effects.
func ReuseTokenSourceWithExpiry ¶
func ReuseTokenSourceWithExpiry(t *Token, src TokenSource, earlyExpiry time.Duration) TokenSource
ReuseTokenSource returns a TokenSource that acts in the same manner as the TokenSource returned by ReuseTokenSource, except the expiry buffer is configurable. The expiration time of a token is calculated as t.Expiry.Add(-earlyExpiry).
func StaticTokenSource ¶
func StaticTokenSource(t *Token) TokenSource
StaticTokenSource returns a TokenSource that always returns the same token. Because the provided token t is never refreshed, StaticTokenSource is only useful for tokens that never expire.
type Transport ¶
type Transport struct { // Source supplies the token to add to outgoing requests' // Authorization headers. Source TokenSource // Base is the base RoundTripper used to make HTTP requests. // If nil, http.DefaultTransport is used. Base http.RoundTripper }
Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, wrapping a base RoundTripper and adding an Authorization header with a token from the supplied Sources.
Transport is a low-level mechanism. Most code will use the higher-level Config.Client method instead.
func (*Transport) CancelRequest
deprecated
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
Package authhandler implements a TokenSource to support "three-legged OAuth 2.0" via a custom AuthorizationHandler.
|
Package authhandler implements a TokenSource to support "three-legged OAuth 2.0" via a custom AuthorizationHandler. |
Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0".
|
Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". |
Package endpoints provides constants for using OAuth2 to access various services.
|
Package endpoints provides constants for using OAuth2 to access various services. |
Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs.
|
Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. |
downscope
Package downscope implements the ability to downscope, or restrict, the Identity and Access Management permissions that a short-lived Token can use.
|
Package downscope implements the ability to downscope, or restrict, the Identity and Access Management permissions that a short-lived Token can use. |
Package hipchat provides constants for using OAuth2 to access HipChat.
|
Package hipchat provides constants for using OAuth2 to access HipChat. |
Package internal contains support packages for oauth2 package.
|
Package internal contains support packages for oauth2 package. |
jws
Package jws provides a partial implementation of JSON Web Signature encoding and decoding.
|
Package jws provides a partial implementation of JSON Web Signature encoding and decoding. |
jwt
Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0".
|
Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". |
Package jira provides claims and JWT signing for OAuth2 to access JIRA/Confluence.
|
Package jira provides claims and JWT signing for OAuth2 to access JIRA/Confluence. |