oauth2

package module
v0.0.0-...-9e23774 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2014 License: BSD-3-Clause Imports: 17 Imported by: 0

README

OAuth2 for Go

Build Status

oauth2 package contains a client implementation for OAuth 2.0 spec.

Installation

go get github.com/golang/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.

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("")
	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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CacheRoundTripper

type CacheRoundTripper struct {
	TransportDelegate Transport
	CacheFile         string
	Config            *Config
}

CacheRoundTripper is a simple caching transport. Example usage:

t := &CacherRoundTripper{ TransportDelegate: conf.NewTransport() }
client := http.Client{Transport: t}

func (*CacheRoundTripper) RoundTrip

func (c *CacheRoundTripper) RoundTrip(req *http.Request) (*http.Response, error)

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 round tripper 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

func NewConfig(opts *Options, authURL, tokenURL string) (*Config, error)

NewConfig creates a generic OAuth 2.0 configuration that talks to an OAuth 2.0 provider specified with authURL and tokenURL.

func (*Config) AuthCodeURL

func (c *Config) AuthCodeURL(state string) (authURL string)

AuthCodeURL returns a URL to OAuth 2.0 provider's consent page that asks for permissions for the required scopes explicitly.

func (*Config) Exchange

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

Exchange exchanges the authorization code with the OAuth 2.0 provider to retrieve a new access token.

func (*Config) FetchToken

func (c *Config) FetchToken(existing *Token) (*Token, error)

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

func (c *Config) NewTransport() *Transport

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

func (c *Config) NewTransportWithCode(code string) (*Transport, error)

NewTransportWithCode exchanges the OAuth 2.0 authorization 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 {
	// Client is the HTTP client to be used to retrieve
	// tokens from the OAuth 2.0 provider.
	Client *http.Client

	// Transport is the round tripper 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

func (c *JWTConfig) FetchToken(existing *Token) (*Token, error)

fetchToken retrieves a new access token and updates the existing token with the newly fetched credentials.

func (*JWTConfig) NewTransport

func (c *JWTConfig) NewTransport() *Transport

NewTransport creates a transport that is authorize with the parent JWT configuration.

func (*JWTConfig) NewTransportWithUser

func (c *JWTConfig) NewTransportWithUser(user string) *Transport

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"`

	// AccessType is an OAuth extension that gets sent as the
	// "access_type" field in the URL from AuthCodeURL.
	// See https://developers.google.com/accounts/docs/OAuth2WebServer.
	// It may be "online" (the 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.
	AccessType string `json:"access_type,omitempty"`

	// 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:"-"`
}

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 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"`

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

func (*Token) Expired

func (t *Token) Expired() bool

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

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

func (t *Transport) RefreshToken() error

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

func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err 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.

func (*Transport) SetToken

func (t *Transport) SetToken(v *Token)

SetToken sets a token to the transport in a thread-safe way.

func (*Transport) Token

func (t *Transport) Token() *Token

Token returns the token that authorizes and authenticates the transport.

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.

Jump to

Keyboard shortcuts

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