oauth2

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2021 License: MIT, BSD-3-Clause Imports: 12 Imported by: 0

README

OAuth2 for Go

Go Reference Build Status

oauth2 package contains a client implementation for OAuth 2.0 spec.

Installation

go get github.com/shimt/pam-exec-oauth2/internal/oauth2

Or you can manually git clone the repository to $(go env GOPATH)/src/github.com/shimt/pam-exec-oauth2/internal/oauth2.

See pkg.go.dev for further documentation and examples.

Policy for new packages

We no longer accept new provider-specific packages in this repo if all they do is add a single endpoint variable. If you just want to add a single endpoint, add it to the godoc.org/github.com/shimt/pam-exec-oauth2/internal/oauth2/endpoints package.

Report Issues / Send Patches

This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html.

The main issue tracker for the oauth2 repository is located at https://github.com/golang/oauth2/issues.

Documentation

Overview

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.

Index

Examples

Constants

This section is empty.

Variables

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.

View Source
var NoContext = context.TODO()

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.

Functions

func NewClient

func NewClient(ctx context.Context, src TokenSource) *http.Client

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.

func RegisterBrokenAuthHeaderProvider deprecated

func RegisterBrokenAuthHeaderProvider(tokenURL string)

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.

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 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.
	AccessTypeOnline  AuthCodeOption = SetAuthURLParam("access_type", "online")
	AccessTypeOffline AuthCodeOption = SetAuthURLParam("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 = SetAuthURLParam("prompt", "consent")
)

func SetAuthURLParam

func SetAuthURLParam(key, value string) AuthCodeOption

SetAuthURLParam builds an AuthCodeOption which passes key/value parameters to a provider's authorization endpoint.

type AuthStyle

type AuthStyle int

AuthStyle represents how requests for tokens are authenticated to the server.

const (
	// AuthStyleAutoDetect means to auto-detect which authentication
	// style the provider wants by trying both ways and caching
	// the successful way for the future.
	AuthStyleAutoDetect AuthStyle = 0

	// AuthStyleInParams sends the "client_id" and "client_secret"
	// in the POST body as application/x-www-form-urlencoded parameters.
	AuthStyleInParams AuthStyle = 1

	// 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.
	AuthStyleInHeader AuthStyle = 2
)

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 constants specific to each server and are
	// often available via site-specific packages, such as
	// 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 endpoint URLs. For the client credentials 2-legged OAuth2 flow, see the clientcredentials package (https://github.com/shimt/pam-exec-oauth2/internal/oauth2/clientcredentials).

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/shimt/pam-exec-oauth2/internal/oauth2"
)

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("...")
}
Output:

Example (CustomHTTP)
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/shimt/pam-exec-oauth2/internal/oauth2"
)

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

func (*Config) Client

func (c *Config) Client(ctx context.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.Context, code string, opts ...AuthCodeOption) (*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 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.

func (*Config) PasswordCredentialsToken

func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)

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.

func (*Config) PasswordCredentialsTokenEx

func (c *Config) PasswordCredentialsTokenEx(ctx context.Context, username, password string, parameters url.Values) (*Token, error)

PasswordCredentialsTokenEx 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 HTTP client to use is derived from the context. If nil, http.DefaultClient is used.

func (*Config) TokenSource

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

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.

type Endpoint

type Endpoint struct {
	AuthURL  string
	TokenURL string

	// AuthStyle optionally specifies how the endpoint wants the
	// client ID & client secret sent. The zero value means to
	// auto-detect.
	AuthStyle AuthStyle
}

Endpoint represents an OAuth 2.0 provider's authorization and token endpoint URLs.

type RetrieveError

type RetrieveError struct {
	Response *http.Response
	// Body is the body that was consumed by reading Response.Body.
	// It may be truncated.
	Body []byte
}

RetrieveError is the error returned when the token endpoint returns a non-2XX HTTP status code.

func (*RetrieveError) Error

func (r *RetrieveError) Error() string

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

func (*Token) Extra

func (t *Token) Extra(key string) interface{}

Extra returns an extra field. Extra fields are key-value pairs returned by the server as a part of the token retrieval response.

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

func (*Token) Valid

func (t *Token) Valid() bool

Valid reports whether t is non-nil, has an AccessToken, and is not expired.

func (*Token) WithExtra

func (t *Token) WithExtra(extra interface{}) *Token

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.

type TokenSource

type TokenSource interface {
	// Token returns a token or an error.
	// Token must be safe for concurrent use by multiple goroutines.
	// The returned Token must not be modified.
	Token() (*Token, error)
}

A TokenSource is anything that can return a token.

func ReuseTokenSource

func ReuseTokenSource(t *Token, src TokenSource) TokenSource

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.

func StaticTokenSource

func StaticTokenSource(t *Token) TokenSource

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.

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
}

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 deprecated

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

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.

func (*Transport) RoundTrip

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

RoundTrip authorizes and authenticates the request with an access token from Transport's Source.

Directories

Path Synopsis
Package amazon provides constants for using OAuth2 to access Amazon.
Package amazon provides constants for using OAuth2 to access Amazon.
Package authhandler implements a TokenSource to support "three-legged OAuth 2.0" via a custom AuthorizationHandler.
Package authhandler implements a TokenSource to support "three-legged OAuth 2.0" via a custom AuthorizationHandler.
Package bitbucket provides constants for using OAuth2 to access Bitbucket.
Package bitbucket provides constants for using OAuth2 to access Bitbucket.
Package cern provides constants for using OAuth2 to access CERN services.
Package cern provides constants for using OAuth2 to access CERN services.
Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0".
Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0".
Package endpoints provides constants for using OAuth2 to access various services.
Package endpoints provides constants for using OAuth2 to access various services.
Package facebook provides constants for using OAuth2 to access Facebook.
Package facebook provides constants for using OAuth2 to access Facebook.
Package fitbit provides constants for using OAuth2 to access the Fitbit API.
Package fitbit provides constants for using OAuth2 to access the Fitbit API.
Package foursquare provides constants for using OAuth2 to access Foursquare.
Package foursquare provides constants for using OAuth2 to access Foursquare.
Package github provides constants for using OAuth2 to access Github.
Package github provides constants for using OAuth2 to access Github.
Package gitlab provides constants for using OAuth2 to access GitLab.
Package gitlab provides constants for using OAuth2 to access GitLab.
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 heroku provides constants for using OAuth2 to access Heroku.
Package heroku provides constants for using OAuth2 to access Heroku.
Package hipchat provides constants for using OAuth2 to access HipChat.
Package hipchat provides constants for using OAuth2 to access HipChat.
Package instagram provides constants for using OAuth2 to access Instagram.
Package instagram provides constants for using OAuth2 to access Instagram.
Package internal contains support packages for oauth2 package.
Package internal contains support packages for oauth2 package.
Package jira provides claims and JWT signing for OAuth2 to access JIRA/Confluence.
Package jira provides claims and JWT signing for OAuth2 to access JIRA/Confluence.
Package jws provides a partial implementation of JSON Web Signature encoding and decoding.
Package jws provides a partial implementation of JSON Web Signature encoding and decoding.
Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0".
Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0".
Package kakao provides constants for using OAuth2 to access Kakao.
Package kakao provides constants for using OAuth2 to access Kakao.
Package linkedin provides constants for using OAuth2 to access LinkedIn.
Package linkedin provides constants for using OAuth2 to access LinkedIn.
Package mailchimp provides constants for using OAuth2 to access MailChimp.
Package mailchimp provides constants for using OAuth2 to access MailChimp.
Package mailru provides constants for using OAuth2 to access Mail.Ru.
Package mailru provides constants for using OAuth2 to access Mail.Ru.
Package mediamath provides constants for using OAuth2 to access MediaMath.
Package mediamath provides constants for using OAuth2 to access MediaMath.
Package microsoft provides constants for using OAuth2 to access Windows Live ID.
Package microsoft provides constants for using OAuth2 to access Windows Live ID.
Package nokiahealth provides constants for using OAuth2 to access the Nokia Health Mate API.
Package nokiahealth provides constants for using OAuth2 to access the Nokia Health Mate API.
Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki.
Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki.
Package paypal provides constants for using OAuth2 to access PayPal.
Package paypal provides constants for using OAuth2 to access PayPal.
Package slack provides constants for using OAuth2 to access Slack.
Package slack provides constants for using OAuth2 to access Slack.
Package spotify provides constants for using OAuth2 to access Spotify.
Package spotify provides constants for using OAuth2 to access Spotify.
Package stackoverflow provides constants for using OAuth2 to access Stack Overflow.
Package stackoverflow provides constants for using OAuth2 to access Stack Overflow.
Package twitch provides constants for using OAuth2 to access Twitch.
Package twitch provides constants for using OAuth2 to access Twitch.
Package uber provides constants for using OAuth2 to access Uber.
Package uber provides constants for using OAuth2 to access Uber.
Package vk provides constants for using OAuth2 to access VK.com.
Package vk provides constants for using OAuth2 to access VK.com.
Package yahoo provides constants for using OAuth2 to access Yahoo.
Package yahoo provides constants for using OAuth2 to access Yahoo.
Package yandex provides constants for using OAuth2 to access Yandex APIs.
Package yandex provides constants for using OAuth2 to access Yandex APIs.

Jump to

Keyboard shortcuts

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