oauth2 package - golang.org/x/oauth2 - Go Packages (original) (raw)
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.
func NewClient(ctx context.Context, src TokenSource) *http.Client
func RegisterBrokenAuthHeaderProvider(tokenURL string)deprecated
- 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) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)
- func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource
This section is empty.
HTTPClient is the context key to use with context.WithValueto associate a *http.Client value with a context.
NoContext is the default context you should supply if not using your own context.Context.
Deprecated: Use context.Background or context.TODO instead.
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. The resulting verifier should be passed to Config.AuthCodeURL or Config.DeviceAuthwith S256ChallengeOption, and to Config.Exchange or Config.DeviceAccessTokenwith VerifierOption.
NewClient creates an *http.Client from a context.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.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 RegisterBrokenAuthHeaderProvider(tokenURL string)
RegisterBrokenAuthHeaderProvider previously did something. It is now a no-op.
Deprecated: this function no longer does anything. Caller code that wants to avoid potential extra HTTP requests made during auto-probing of the provider's auth style should set Endpoint.AuthStyle.
S256ChallengeFromVerifier returns a PKCE code challenge derived from verifier with method S256.
Prefer to use S256ChallengeOption where possible.
type AuthCodeOption interface {
}
An AuthCodeOption is passed to Config.AuthCodeURL.
var (
AccessTypeOnline [AuthCodeOption](#AuthCodeOption) = [SetAuthURLParam](#SetAuthURLParam)("access_type", "online")
AccessTypeOffline [AuthCodeOption](#AuthCodeOption) = [SetAuthURLParam](#SetAuthURLParam)("access_type", "offline")
ApprovalForce [AuthCodeOption](#AuthCodeOption) = [SetAuthURLParam](#SetAuthURLParam)("prompt", "consent"))
func S256ChallengeOption(verifier string) AuthCodeOption
S256ChallengeOption derives a PKCE code challenge from the verifier with method S256. It should be passed to Config.AuthCodeURL or Config.DeviceAuthonly.
func SetAuthURLParam(key, value string) AuthCodeOption
SetAuthURLParam builds an AuthCodeOption which passes key/value parameters to a provider's authorization endpoint.
func VerifierOption(verifier string) AuthCodeOption
VerifierOption returns a PKCE code verifier AuthCodeOption. It should only be passed to Config.Exchange or Config.DeviceAccessToken.
AuthStyle represents how requests for tokens are authenticated to the server.
const (
AuthStyleAutoDetect [AuthStyle](#AuthStyle) = 0
AuthStyleInParams [AuthStyle](#AuthStyle) = 1
AuthStyleInHeader [AuthStyle](#AuthStyle) = 2)
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 thegolang.org/x/oauth2/clientcredentials package.
package main
import ( "context" "fmt" "log"
"golang.org/x/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("...")}
package main
import ( "context" "fmt" "log" "net/http" "time"
"golang.org/x/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}
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.
DeviceAccessToken polls the server to exchange a device code for a token.
DeviceAuth returns a device auth struct which contains a device code and authorization information provided for users to enter on another device.
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)
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 http.Request.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.
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.
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.
Endpoint represents an OAuth 2.0 provider's authorization and token endpoint URLs.
type Token struct {
AccessToken [string](/builtin#string) `json:"access_token"`
TokenType [string](/builtin#string) `json:"token_type,omitempty"`
RefreshToken [string](/builtin#string) `json:"refresh_token,omitempty"`
Expiry [time](/time).[Time](/time#Time) `json:"expiry,omitempty"`
ExpiresIn [int64](/builtin#int64) `json:"expires_in,omitempty"`}
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.
Extra returns an extra field. Extra fields are key-value pairs returned by the server as part of the token retrieval response.
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 returns t.TokenType if non-empty, else "Bearer".
Valid reports whether t is non-nil, has an AccessToken, and is not expired.
func (t *Token) WithExtra(extra any) *Token
WithExtra returns a new Token that's a clone of t, but using the provided raw extra map. This is only intended for use by packages implementing derivative OAuth2 flows.
type TokenSource interface {
Token() (*[Token](#Token), [error](/builtin#error))}
A TokenSource is anything that can return a token.
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 otherTokenSource without adverse effects.
ReuseTokenSourceWithExpiry returns a TokenSource that acts in the same manner as theTokenSource returned by ReuseTokenSource, except the expiry buffer is configurable. The expiration time of a token is calculated as t.Expiry.Add(-earlyExpiry).
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.
Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, wrapping a base http.RoundTripper and adding an Authorization header with a token from the supplied TokenSource.
Transport is a low-level mechanism. Most code will use the higher-level Config.Client method instead.
CancelRequest does nothing. It used to be a legacy cancellation mechanism but now only logs on first use to warn that it's deprecated.
Deprecated: use contexts for cancellation instead.
RoundTrip authorizes and authenticates the request with an access token from Transport's Source.