oauth

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2023 License: MIT Imports: 12 Imported by: 12

README

oauth

A library for Go client applications that need to perform OAuth authorization against a server, typically GitHub.com.


Traditionally, OAuth for web applications involves redirecting to a URI after the user authorizes an app. While web apps (and some native client apps) can receive a browser redirect, client apps such as CLI applications do not have such an option.

To accommodate client apps, this library implements the OAuth Device Authorization Grant which GitHub.com now supports. With Device flow, the user is presented with a one-time code that they will have to enter in a web browser while authorizing the app on the server. Device flow is suitable for cases where the web browser may be running on a separate device than the client app itself; for example a CLI application could run within a headless, containerized instance, but the user may complete authorization using a browser on their phone.

To transparently enable OAuth authorization on any GitHub host (e.g. GHES instances without OAuth “Device flow” support), this library also bundles an implementation of OAuth web application flow in which the client app starts a local server at http://127.0.0.1:<port>/ that acts as a receiver for the browser redirect. First, Device flow is attempted, and the localhost server is used as fallback. With the localhost server, the user's web browser must be running on the same machine as the client application itself.

Usage

Applications that need more control over the user experience around authentication should directly interface with github.com/cli/oauth/device and github.com/cli/oauth/webapp packages.

In theory, these packages would enable authorization on any OAuth-enabled host. In practice, however, this was only tested for authorizing with GitHub.

Documentation

Overview

Package oauth is a library for Go client applications that need to perform OAuth authorization against a server, typically GitHub.com.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Flow

type Flow struct {
	// The hostname to authorize the app with.
	//
	// Deprecated: Use Host instead.
	Hostname string
	// Host configuration to authorize the app with.
	Host *Host
	// OAuth scopes to request from the user.
	Scopes []string
	// OAuth application ID.
	ClientID string
	// OAuth application secret. Only applicable in web application flow.
	ClientSecret string
	// The localhost URI for web application flow callback, e.g. "http://127.0.0.1/callback".
	CallbackURI string

	// Display a one-time code to the user. Receives the code and the browser URL as arguments. Defaults to printing the
	// code to the user on Stdout with instructions to copy the code and to press Enter to continue in their browser.
	DisplayCode func(string, string) error
	// Open a web browser at a URL. Defaults to opening the default system browser.
	BrowseURL func(string) error
	// Render an HTML page to the user upon completion of web application flow. The default is to
	// render a simple message that informs the user they can close the browser tab and return to the app.
	WriteSuccessHTML func(io.Writer)

	// The HTTP client to use for API POST requests. Defaults to http.DefaultClient.
	HTTPClient httpClient
	// The stream to listen to keyboard input on. Defaults to os.Stdin.
	Stdin io.Reader
	// The stream to print UI messages to. Defaults to os.Stdout.
	Stdout io.Writer
}

Flow facilitates a single OAuth authorization flow.

func (*Flow) DetectFlow

func (oa *Flow) DetectFlow() (*api.AccessToken, error)

DetectFlow tries to perform Device flow first and falls back to Web application flow.

Example

DetectFlow attempts to initiate OAuth Device flow with the server and falls back to OAuth Web application flow if Device flow seems unsupported. This approach isn't strictly needed for github.com, as its Device flow support is globally available, but it enables logging in to self-hosted GitHub instances as well.

package main

import (
	"fmt"
	"os"

	"github.com/cli/oauth"
)

func main() {
	flow := &oauth.Flow{
		Host:         oauth.GitHubHost("https://github.com"),
		ClientID:     os.Getenv("OAUTH_CLIENT_ID"),
		ClientSecret: os.Getenv("OAUTH_CLIENT_SECRET"), // only applicable to web app flow
		CallbackURI:  "http://127.0.0.1/callback",      // only applicable to web app flow
		Scopes:       []string{"repo", "read:org", "gist"},
	}

	accessToken, err := flow.DetectFlow()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Access token: %s\n", accessToken.Token)
}
Output:

func (*Flow) DeviceFlow

func (oa *Flow) DeviceFlow() (*api.AccessToken, error)

DeviceFlow captures the full OAuth Device flow, including prompting the user to copy a one-time code and opening their web browser, and returns an access token upon completion.

func (*Flow) WebAppFlow

func (oa *Flow) WebAppFlow() (*api.AccessToken, error)

WebAppFlow starts a local HTTP server, opens the web browser to initiate the OAuth Web application flow, blocks until the user completes authorization and is redirected back, and returns the access token.

type Host added in v0.9.0

type Host struct {
	DeviceCodeURL string
	AuthorizeURL  string
	TokenURL      string
}

Host defines the endpoints used to authorize against an OAuth server.

func GitHubHost added in v0.9.0

func GitHubHost(hostURL string) *Host

GitHubHost constructs a Host from the given URL to a GitHub instance.

Directories

Path Synopsis
Package api implements request and response parsing logic shared between different OAuth strategies.
Package api implements request and response parsing logic shared between different OAuth strategies.
Package device facilitates performing OAuth Device Authorization Flow for client applications such as CLIs that can not receive redirects from a web site.
Package device facilitates performing OAuth Device Authorization Flow for client applications such as CLIs that can not receive redirects from a web site.
Package webapp implements the OAuth Web Application authorization flow for client applications by starting a server at localhost to receive the web redirect after the user has authorized the application.
Package webapp implements the OAuth Web Application authorization flow for client applications by starting a server at localhost to receive the web redirect after the user has authorized the application.

Jump to

Keyboard shortcuts

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