Involved Source Files
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.
token.gotransport.go
Code Examples
package main
import (
"context"
"fmt"
"golang.org/x/oauth2"
"log"
)
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",
},
}
// 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)
}
tok, err := conf.Exchange(ctx, code)
if err != nil {
log.Fatal(err)
}
client := conf.Client(ctx, tok)
client.Get("...")
}
package main
import (
"context"
"fmt"
"golang.org/x/oauth2"
"log"
"net/http"
"time"
)
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
}
Package-Level Type Names (total 12, in which 8 are exported)
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://golang.org/x/oauth2/clientcredentials).
ClientID is the application's ID.
ClientSecret is the application's secret.
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.
RedirectURL is the URL to redirect users going through
the OAuth flow, after the resource owner's URLs.
Scope specifies optional requested permissions.
AuthCodeURL returns a URL to OAuth 2.0 provider's consent page
that asks for permissions for the required scopes explicitly.
State is a token to protect the user from CSRF attacks. You must
always provide a non-empty string and validate that it matches the
the state query parameter on your redirect callback.
See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
Opts may include AccessTypeOnline or AccessTypeOffline, as well
as ApprovalForce.
It can also be used to pass the PKCE challenge.
See https://www.oauth.com/oauth2-servers/pkce/ for more info.
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.
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").
Opts may include the PKCE verifier code if previously used in AuthCodeURL.
See https://www.oauth.com/oauth2-servers/pkce/ for more info.
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.
func golang.org/x/oauth2/google.ConfigFromJSON(jsonKey []byte, scope ...string) (*Config, error)
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error)
Endpoint represents an OAuth 2.0 provider's authorization and token
endpoint URLs.
AuthStyle optionally specifies how the endpoint wants the
client ID & client secret sent. The zero value means to
auto-detect.
AuthURLstringTokenURLstring
var golang.org/x/oauth2/google.Endpoint
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.
AccessToken is the token that authorizes and authenticates
the requests.
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.
RefreshToken is a token that's used by the application
(as opposed to the user) to refresh the access token
if it expires.
TokenType is the type of token.
The Type method returns either this or "Bearer", the default.
raw optionally contains extra metadata from the server
when updating a token.
Extra returns an extra field.
Extra fields are key-value pairs returned by the server as a
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.
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.
expired reports whether the token is expired.
t must be non-nil.
func (*Config).Exchange(ctx context.Context, code string, opts ...AuthCodeOption) (*Token, error)
func (*Config).PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)
func (*Token).WithExtra(extra interface{}) *Token
func TokenSource.Token() (*Token, error)
func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error)
func tokenFromInternal(t *internal.Token) *Token
func ReuseTokenSource(t *Token, src TokenSource) TokenSource
func StaticTokenSource(t *Token) TokenSource
func (*Config).Client(ctx context.Context, t *Token) *http.Client
func (*Config).TokenSource(ctx context.Context, t *Token) TokenSource
func google.golang.org/grpc/credentials/oauth.NewOauthAccess(token *Token) credentials.PerRPCCredentials
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.
Base is the base RoundTripper used to make HTTP requests.
If nil, http.DefaultTransport is used.
Source supplies the token to add to outgoing requests'
Authorization headers.
CancelRequest does nothing. It used to be a legacy cancellation mechanism
but now only it 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.
(*T) base() http.RoundTripper
*T : net/http.RoundTripper
reuseTokenSource is a TokenSource that holds a single token in memory
and validates its expiry before each call to retrieve it with
Token. If it's expired, it will be auto-refreshed using the
new TokenSource.
// guards t
// called when t is expired.
t*Token
Token returns the current token if it's still valid, else will
refresh the current token (using r.Context for HTTP client
information) and return the new one.
*T : TokenSource
tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token"
HTTP requests to renew a token using a RefreshToken.
conf*Config
// used to get HTTP requests
refreshTokenstring
WARNING: Token is not safe for concurrent access, as it
updates the tokenRefresher's refreshToken field.
Within this package, it is used by reuseTokenSource which
synchronizes calls to this method with its own mutex.
*T : TokenSource
Package-Level Functions (total 8, in which 5 are exported)
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.
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.
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.
SetAuthURLParam builds an AuthCodeOption which passes key/value parameters
to a provider's authorization endpoint.
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.
cloneRequest returns a clone of the provided *http.Request.
The clone is a shallow copy of the struct and its Header map.
retrieveToken takes a *Config and uses that to retrieve an *internal.Token.
This token is then mapped from *internal.Token into an *oauth2.Token which is returned along
with an error..
tokenFromInternal maps an *internal.Token struct into
a *Token struct.
Package-Level Variables (total 7, in which 5 are exported)
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.
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.
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.
NoContext is the default context you should supply if not using
your own context.Context (see https://golang.org/x/net/context).
Deprecated: Use context.Background() or context.TODO() instead.
timeNow is time.Now but pulled out as a variable for tests.
Package-Level Constants (total 4, in which 3 are exported)
AuthStyleAutoDetect means to auto-detect which authentication
style the provider wants by trying both ways and caching
the successful way for the future.
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.
AuthStyleInParams sends the "client_id" and "client_secret"
in the POST body as application/x-www-form-urlencoded parameters.
expiryDelta determines how earlier a token should be considered
expired than its actual expiration time. It is used to avoid late
expirations due to client-server time mismatches.
The pages are generated with Goldsv0.3.2-preview. (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.