Documentation ¶
Overview ¶
Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. It can additionally grant authorization with Bearer JWT.
Example (Config) ¶
package main import ( "fmt" "log" "net/http" "github.com/golang/oauth2" ) func main() { conf, err := oauth2.NewConfig(&oauth2.Options{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", RedirectURL: "YOUR_REDIRECT_URL", Scopes: []string{"SCOPE1", "SCOPE2"}, }, "https://provider.com/o/oauth2/auth", "https://provider.com/o/oauth2/token") if err != nil { log.Fatal(err) } // Redirect user to consent page to ask for permission // for the scopes specified above. url := conf.AuthCodeURL("state", "online", "auto") fmt.Printf("Visit the URL for the auth dialog: %v", url) // Use the authorization code that is pushed to the redirect URL. // NewTransportWithCode will do the handshake to retrieve // an access token and initiate a Transport that is // authorized and authenticated by the retrieved token. var authorizationCode string if _, err = fmt.Scan(&authorizationCode); err != nil { log.Fatal(err) } t, err := conf.NewTransportWithCode(authorizationCode) if err != nil { log.Fatal(err) } // You can use t to initiate a new http.Client and // start making authenticated requests. client := http.Client{Transport: t} client.Get("...") }
Output:
Example (JWTConfig) ¶
package main import ( "log" "net/http" "github.com/golang/oauth2" ) func main() { conf, err := oauth2.NewJWTConfig(&oauth2.JWTOptions{ Email: "xxx@developer.gserviceaccount.com", // The contents of your RSA private key or your PEM file // that contains a private key. // If you have a p12 file instead, you // can use `openssl` to export the private key into a pem file. // // $ openssl pkcs12 -in key.p12 -out key.pem -nodes // // It only supports PEM containers with no passphrase. PrivateKey: []byte("PRIVATE KEY CONTENTS"), Scopes: []string{"SCOPE1", "SCOPE2"}, }, "https://provider.com/o/oauth2/token") if err != nil { log.Fatal(err) } // Initiate an http.Client, the following GET request will be // authorized and authenticated on the behalf of // xxx@developer.gserviceaccount.com. client := http.Client{Transport: conf.NewTransport()} client.Get("...") // If you would like to impersonate a user, you can // create a transport with a subject. The following GET // request will be made on the behalf of user@example.com. client = http.Client{Transport: conf.NewTransportWithUser("user@example.com")} client.Get("...") }
Output:
Index ¶
- type Config
- func (c *Config) AuthCodeURL(state, accessType, prompt string) (authURL string)
- func (c *Config) Exchange(code string) (*Token, error)
- func (c *Config) FetchToken(existing *Token) (*Token, error)
- func (c *Config) NewTransport() *Transport
- func (c *Config) NewTransportWithCode(code string) (*Transport, error)
- type JWTConfig
- type JWTOptions
- type Options
- type Token
- type TokenFetcher
- type Transport
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct { // Client is the HTTP client to be used to retrieve // tokens from the OAuth 2.0 provider. Client *http.Client // Transport is the http.RoundTripper to be used // to construct new oauth2.Transport instances from // this configuration. Transport http.RoundTripper // contains filtered or unexported fields }
Config represents the configuration of an OAuth 2.0 consumer client.
func NewConfig ¶
NewConfig creates a generic OAuth 2.0 configuration that talks to an OAuth 2.0 provider specified with authURL and tokenURL.
func (*Config) AuthCodeURL ¶
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-zero 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.
Access type is an OAuth extension that gets sent as the "access_type" field in the URL from AuthCodeURL. It may be "online" (default) or "offline". 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.
Approval prompt indicates whether the user should be re-prompted for consent. If set to "auto" (default) the user will be prompted only if they haven't previously granted consent and the code can only be exchanged for an access token. If set to "force" the user will always be prompted, and the code can be exchanged for a refresh token.
func (*Config) Exchange ¶
Exchange exchanges the authorization code with the OAuth 2.0 provider to retrieve a new access token.
func (*Config) FetchToken ¶
FetchToken retrieves a new access token and updates the existing token with the newly fetched credentials. If existing token doesn't contain a refresh token, it returns an error.
func (*Config) NewTransport ¶
NewTransport creates a new authorizable transport. It doesn't initialize the new transport with a token, so after creation, you need to set a valid token (or an expired token with a valid refresh token) in order to be able to do authorized requests.
func (*Config) NewTransportWithCode ¶
NewTransportWithCode exchanges the OAuth 2.0 authorization code with the provider to fetch a new access token (and refresh token). Once it successfully retrieves a new token, creates a new transport authorized with it.
type JWTConfig ¶
type JWTConfig struct { // Client is the HTTP client to be used to retrieve // tokens from the OAuth 2.0 provider. Client *http.Client // Transport is the http.RoundTripper to be used // to construct new oauth2.Transport instances from // this configuration. Transport http.RoundTripper // contains filtered or unexported fields }
JWTConfig represents an OAuth 2.0 provider and client options to provide authorized transports with a Bearer JWT token.
func NewJWTConfig ¶
func NewJWTConfig(opts *JWTOptions, aud string) (*JWTConfig, error)
NewJWTConfig creates a new configuration with the specified options and OAuth2 provider endpoint.
func (*JWTConfig) FetchToken ¶
fetchToken retrieves a new access token and updates the existing token with the newly fetched credentials.
func (*JWTConfig) NewTransport ¶
NewTransport creates a transport that is authorize with the parent JWT configuration.
func (*JWTConfig) NewTransportWithUser ¶
NewTransportWithUser creates a transport that is authorized by the client and impersonates the specified user.
type JWTOptions ¶
type JWTOptions struct { // Email is the OAuth client identifier used when communicating with // the configured OAuth provider. Email string `json:"email"` // PrivateKey contains the contents of an RSA private key or the // contents of a PEM file that contains a private key. The provided // private key is used to sign JWT payloads. // PEM containers with a passphrase are not supported. // Use the following command to convert a PKCS 12 file into a PEM. // // $ openssl pkcs12 -in key.p12 -out key.pem -nodes // PrivateKey []byte `json:"-"` // Scopes identify the level of access being requested. Scopes []string `json:"scopes"` }
JWTOptions represents a OAuth2 client's crendentials to retrieve a Bearer JWT token.
type Options ¶
type Options struct { // ClientID is the OAuth client identifier used when communicating with // the configured OAuth provider. ClientID string `json:"client_id"` // ClientSecret is the OAuth client secret used when communicating with // the configured OAuth provider. ClientSecret string `json:"client_secret"` // RedirectURL is the URL to which the user will be returned after // granting (or denying) access. RedirectURL string `json:"redirect_url"` // Scopes optionally specifies a list of requested permission scopes. Scopes []string `json:"scopes,omitempty"` }
Options represents options to provide OAuth 2.0 client credentials and access level. A sample configuration:
type Token ¶
type Token struct { // A token that authorizes and authenticates the requests. AccessToken string `json:"access_token"` // Identifies the type of token returned. TokenType string `json:"token_type,omitempty"` // A token that may be used to obtain a new access token. RefreshToken string `json:"refresh_token,omitempty"` // The remaining lifetime of the access token. Expiry time.Time `json:"expiry,omitempty"` // Extra optionally contains extra metadata from the server // when updating a token. The only current key that may be // populated is "id_token". It may be nil and will be // initialized as needed. Extra map[string]string `json:"extra,omitempty"` // Subject is the user to impersonate. Subject string `json:"subject,omitempty"` }
Token represents the crendentials used to authorize the requests to access protected resources on the OAuth 2.0 provider's backend.
type TokenFetcher ¶
type TokenFetcher interface { // FetchToken retrieves a new access token for the provider. // If the implementation doesn't know how to retrieve a new token, // it returns an error. The existing token may be nil. FetchToken(existing *Token) (*Token, error) }
TokenFetcher refreshes or fetches a new access token from the provider. It should return an error if it's not capable of retrieving a token.
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests.
func NewTransport ¶
func NewTransport(origTransport http.RoundTripper, fetcher TokenFetcher, token *Token) *Transport
NewTransport creates a new Transport that uses the provided token fetcher as token retrieving strategy. It authenticates the requests and delegates origTransport to make the actual requests.
func (*Transport) RefreshToken ¶
RefreshToken retrieves a new token, if a refreshing/fetching method is known and required credentials are presented (such as a refresh token).
func (*Transport) RoundTrip ¶
RoundTrip authorizes and authenticates the request with an access token. If no token exists or token is expired, tries to refresh/fetch a new token.
Directories ¶
Path | Synopsis |
---|---|
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. |
Package jws provides encoding and decoding utilities for signed JWS messages.
|
Package jws provides encoding and decoding utilities for signed JWS messages. |