oauth2

package module
v0.0.0-...-1679411 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2014 License: BSD-3-Clause Imports: 16 Imported by: 3

README

OAuth2 for Go

Build Status

oauth2 package contains a client implementation for OAuth 2.0 spec.

Installation

go get golang.org/x/oauth2

See godoc for further documentation and examples.

Contributing

Fork the repo, make changes, run the tests and open a pull request.

Before we can accept any pull requests we have to jump through a couple of legal hurdles, primarily a Contributor License Agreement (CLA):

  • If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an individual CLA.
  • If you work for a company that wants to allow you to contribute your work, then you'll need to sign a corporate CLA.

You can sign these electronically (just scroll to the bottom). After that, we'll be able to accept your pull requests.

Documentation

Overview

Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. It can additionally grant authorization with Bearer JWT.

Index

Examples

Constants

This section is empty.

Variables

View Source
var HTTPClient 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

This section is empty.

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 (the default if neither is specified) is the default.
	// 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 = setParam{"access_type", "online"}
	AccessTypeOffline AuthCodeOption = setParam{"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 = setParam{"approval_prompt", "force"}
)

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 supplied by the server and are often
	// available via site-specific packages (for example,
	// 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
}

Config describes a typical 3-legged OAuth2 flow, with both the client application information and the server's URLs.

Example
package main

import (
	"fmt"
	"log"

	"golang.org/x/oauth2"
)

func main() {
	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.
	// NewTransportWithCode will do the handshake to retrieve
	// an access token and initiate a Transport that is
	// authorized and authenticated by the retrieved token.
	var code string
	if _, err := fmt.Scan(&code); err != nil {
		log.Fatal(err)
	}
	tok, err := conf.Exchange(oauth2.NoContext, code)
	if err != nil {
		log.Fatal(err)
	}

	client := conf.Client(oauth2.NoContext, tok)
	client.Get("...")
}
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 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.

Opts may include AccessTypeOnline or AccessTypeOffline, as well as ApprovalForce.

func (*Config) Client

func (c *Config) Client(ctx Context, t *Token) *http.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) Exchange

func (c *Config) Exchange(ctx Context, code string) (*Token, error)

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 HTTP client to use is derived from the context. If nil, http.DefaultClient is used. See the Context type's documentation.

The code will be in the *http.Request.FormValue("code"). Before calling Exchange, be sure to validate FormValue("state").

func (*Config) TokenSource

func (c *Config) TokenSource(ctx Context, t *Token) TokenSource

TokenSource returns a TokenSource that returns t until t expires, automatically refreshing it as necessary using the provided context. See the the Context documentation.

Most users will use Config.Client instead.

type Context

type Context interface{}

Context can be an golang.org/x/net.Context, or an App Engine Context. In the future these will be unified. If you don't care and aren't running on App Engine, you may use NoContext.

var NoContext Context = nil

NoContext is the default context. If you're not running this code on App Engine or not using golang.org/x/net.Context to provide a custom HTTP client, you should use NoContext.

type Endpoint

type Endpoint struct {
	AuthURL  string
	TokenURL string
}

Endpoint contains the OAuth 2.0 provider's authorization and token endpoint URLs.

type JWTConfig

type JWTConfig struct {
	// Email is the OAuth client identifier used when communicating with
	// the configured OAuth provider.
	Email string

	// 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

	// Subject is the optional user to impersonate.
	Subject string

	// Scopes optionally specifies a list of requested permission scopes.
	Scopes []string

	// TokenURL is the endpoint required to complete the 2-legged JWT flow.
	TokenURL string
}

JWTConfig is the configuration for using JWT to fetch tokens, commonly known as "two-legged OAuth".

Example
package main

import (
	"golang.org/x/oauth2"
)

func main() {
	var initialToken *oauth2.Token // nil means no initial token
	conf := &oauth2.JWTConfig{
		Email: "xxx@developer.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("-----BEGIN RSA PRIVATE KEY-----..."),
		Subject:    "user@example.com",
		TokenURL:   "https://provider.com/o/oauth2/token",
	}
	// Initiate an http.Client, the following GET request will be
	// authorized and authenticated on the behalf of user@example.com.
	client := conf.Client(oauth2.NoContext, initialToken)
	client.Get("...")
}
Output:

func (*JWTConfig) Client

func (c *JWTConfig) Client(ctx Context, initialToken *Token) *http.Client

Client returns an HTTP client wrapping the context's HTTP transport and adding Authorization headers with tokens obtained from c.

The provided initialToken may be nil, in which case the first call to TokenSource will do a new JWT request.

The returned client and its Transport should not be modified.

func (*JWTConfig) TokenSource

func (c *JWTConfig) TokenSource(ctx Context, initialToken *Token) TokenSource

TokenSource returns a JWT TokenSource using the configuration in c and the HTTP client from the provided context.

The returned TokenSource only does JWT requests when necessary but otherwise returns the same token repeatedly until it expires.

The provided initialToken may be nil, in which case the first call to TokenSource will do a new JWT request.

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 crendentials 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 derivate OAuth2 flows.

func (*Token) Expired

func (t *Token) Expired() bool

Expired returns true if there is no access token or the access token is expired.

func (*Token) Extra

func (t *Token) Extra(key string) string

Extra returns an extra field returned from the server during token retrieval.

func (*Token) SetAuthHeader

func (t *Token) SetAuthHeader(r *http.Request)

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.

func (*Token) Type

func (t *Token) Type() string

Type returns t.TokenType if non-empty, else "Bearer".

type TokenSource

type TokenSource interface {
	// Token returns a token or an error.
	Token() (*Token, error)
}

A TokenSource is anything that can return a token.

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
	// contains filtered or unexported fields
}

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

func (t *Transport) CancelRequest(req *http.Request)

CancelRequest cancels an in-flight request by closing its connection.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)

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 github provides constants for using OAuth2 to access Github.
Package github provides constants for using OAuth2 to access Github.
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 internal contains support packages for oauth2 package.
Package internal contains support packages for oauth2 package.
Package jws provides encoding and decoding utilities for signed JWS messages.
Package jws provides encoding and decoding utilities for signed JWS messages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL