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/goincremental/web/Godeps/_workspace/src/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("")
fmt.Printf("Visit the URL for the auth dialog: %v", url)
// Use the exchange code that is handled by the redirect URL.
// NewTransportWithCode will do the handshake to retrieve
// an access token and iniate a Transport that is
// authorized and authenticated the retrieved token.
var exchangeCode string
if _, err = fmt.Scan(&exchangeCode); err != nil {
log.Fatal(err)
}
t, err := conf.NewTransportWithCode(exchangeCode)
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/goincremental/web/Godeps/_workspace/src/github.com/golang/oauth2"
)
func main() {
conf, err := oauth2.NewJWTConfig(&oauth2.JWTOptions{
Email: "xxx@developer.gserviceaccount.com",
// The path to the pem file. 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
PemFilename: "/path/to/pem/file.pem",
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 ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// 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.
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.
Example:
t, _ := c.NewTransport() t.SetToken(validToken)
func (*Config) NewTransportWithCode ¶
NewTransportWithCode exchanges the OAuth 2.0 exchange code with the provider to fetch a new access token (and refresh token). Once it succesffully retrieves a new token, creates a new transport authorized with it.
type JWTConfig ¶
type JWTConfig struct {
// 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 {
// ClientID is the OAuth client identifier used when communicating with
// the configured OAuth provider.
Email string `json:"email"`
// The path to the pem file. 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
// Pem file should contain your private key.
PemFilename string `json:"pemfilename"`
// 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"`
// Optional, identifies the level of access being requested.
Scopes []string `json:"scopes"`
// Optional, "online" (default) or "offline", no refresh token if "online"
AccessType string `json:"omit"`
// ApprovalPrompt 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.
ApprovalPrompt string `json:"omit"`
}
Options represents options to provide OAuth 2.0 client credentials and access level. A sample configuration:
opts := &oauth2.Options{
ClientID: "<clientID>",
ClientSecret: "ad4364309eff",
RedirectURL: "https://homepage/oauth2callback",
Scopes: []string{"scope1", "scope2"},
AccessType: "offline", // retrieves a refresh token
}
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 map[string]string `json:"extra,omitempty"`
// JWT related fields
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.
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 interface {
// Authenticates the request with the existing token. If token is
// expired, tries to refresh/fetch a new token.
// Makes the request by delegating it to the default transport.
RoundTrip(*http.Request) (*http.Response, error)
// Returns the token authenticates the transport.
// This operation is thread-safe.
Token() *Token
// Sets a new token to authenticate the transport.
// This operation is thread-safe.
SetToken(token *Token)
// Refreshes the token if refresh is possible (such as in the
// presense of a refresh token). Returns an error if refresh is
// not possible. Refresh is thread-safe.
RefreshToken() error
}
Transport represents an authorized transport. Provides currently in-use user token and allows to set a token to be used. If token expires, it tries to fetch a new token, if possible. Token fetching is thread-safe. If two or more concurrent requests are being made with the same expired token, one of the requests will wait for the other to refresh the existing token.
func NewAuthorizedTransport ¶
func NewAuthorizedTransport(origTransport http.RoundTripper, fetcher TokenFetcher, token *Token) Transport
NewAuthorizedTransport creates a transport that uses the provided token fetcher to retrieve new tokens if there is no access token provided or it is expired.
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. |