oauth2

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2023 License: MIT Imports: 13 Imported by: 0

README

oauth2

build-img pkg-img reportcard-img coverage-img version-img

OAuth2 client for Go.

Features

  • Simple API.
  • Tiny codebase.
  • Dependency-free.

See GUIDE.md for more details.

Install

Go version 1.17

go get github.com/cristalhq/oauth2

Example

config := oauth2.Config{
    ClientID:     "YOUR_CLIENT_ID",
    ClientSecret: "YOUR_CLIENT_SECRET",
    AuthURL:      "https://provider.com/o/oauth2/auth",
    TokenURL:     "https://provider.com/o/oauth2/token",
    Scopes:       []string{"email", "avatar"},
}

// create a client
client := oauth2.NewClient(http.DefaultClient, config)

// url to fetch the code
url := client.AuthCodeURL("state")
fmt.Printf("Visit the URL with 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.
var code string
if _, err := fmt.Scan(&code); err != nil {
    panic(err)
}

// get a token
token, err := client.Exchange(context.Background(), code)
if err != nil {
    panic(err)
}

var _ string = token.AccessToken  // OAuth2 token
var _ string = token.TokenType    // type of the token
var _ string = token.RefreshToken // token for a refresh
var _ time.Time = token.Expiry    // token expiration time
var _ bool = token.IsExpired()    // have token expired?

Also see examples: example_test.go.

Documentation

See these docs.

License

MIT License.

Documentation

Overview

Example
package main

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

	"github.com/cristalhq/oauth2"
)

func main() {
	config := oauth2.Config{
		ClientID:     "YOUR_CLIENT_ID",
		ClientSecret: "YOUR_CLIENT_SECRET",
		AuthURL:      "https://example.com/o/oauth2/auth",
		TokenURL:     "https://example.com/o/oauth2/token",
		Scopes:       []string{"email", "avatar"},
	}

	// create a client
	client := oauth2.NewClient(http.DefaultClient, config)

	// url to fetch the code
	url := client.AuthCodeURL("state")
	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.
	var code string
	if _, err := fmt.Scan(&code); err != nil {
		log.Fatal(err)
	}

	// get a token
	token, err := client.Exchange(context.Background(), code)
	if err != nil {
		panic(err)
	}

	var _ string = token.AccessToken  // OAuth2 token
	var _ string = token.TokenType    // type of the token
	var _ string = token.RefreshToken // token for a refresh
	var _ time.Time = token.Expiry    // token expiration time
	var _ bool = token.IsExpired()    // have token expired?
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Wrap

func Wrap(header, value string, c *http.Client) (*http.Client, error)

Wrap adds an additional header to the given http.Client. The header will be `Authorization`. All the params cannot be empty or nil.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents an OAuth2 HTTP client.

func NewClient

func NewClient(client *http.Client, config Config) *Client

NewClient instantiates a new client with a given config.

func (*Client) AuthCodeURL

func (c *Client) AuthCodeURL(state string) 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.

func (*Client) AuthCodeURLWithParams

func (c *Client) AuthCodeURLWithParams(state string, params url.Values) string

AuthCodeURLWithParams same as AuthCodeURL but allows to pass additional URL parameters.

func (*Client) CredentialsToken

func (c *Client) CredentialsToken(ctx context.Context, username, password string) (*Token, error)

CredentialsToken retrieves a token for given username and password.

func (*Client) Exchange

func (c *Client) Exchange(ctx context.Context, code string) (*Token, error)

Exchange converts an authorization code into an OAuth2 token.

func (*Client) ExchangeWithParams

func (c *Client) ExchangeWithParams(ctx context.Context, code string, params url.Values) (*Token, error)

ExchangeWithParams converts an authorization code into an OAuth2 token.

func (*Client) Token

func (c *Client) Token(ctx context.Context, refreshToken string) (*Token, error)

Token renews a token based on previous token.

type Config

type Config struct {
	ClientID     string   // ClientID is the application's ID.
	ClientSecret string   // ClientSecret is the application's secret.
	AuthURL      string   // AuthURL is a URL for authentication.
	TokenURL     string   // TokenURL is a URL for retrieving a token.
	Mode         Mode     // Mode represents how tokens are represented in requests.
	RedirectURL  string   // RedirectURL is the URL to redirect users going through the OAuth flow.
	Scopes       []string // Scope specifies optional requested permissions.
	// contains filtered or unexported fields
}

Config describes a 3-legged OAuth2 flow.

type Mode

type Mode int

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

const (
	// AutoDetectMode means to auto-detect which authentication style the provider wants.
	AutoDetectMode Mode = 0

	// InParamsMode sends the `client_id` and `client_secret` in the POST body
	// as application/x-www-form-urlencoded parameters.
	InParamsMode Mode = 1

	// InHeaderMode sends the `client_id` and `client_secret` using HTTP Basic Authorization.
	// This is an optional style described in the OAuth2 RFC 6749 section 2.3.1.
	InHeaderMode Mode = 2
)

type Token

type Token struct {
	AccessToken  string      `json:"access_token"`            // AccessToken is the token that authorizes and authenticates the requests.
	TokenType    string      `json:"token_type,omitempty"`    // TokenType is the type of token. The Type method returns either this or "Bearer".
	RefreshToken string      `json:"refresh_token,omitempty"` // RefreshToken is a token that's used by the application to refresh the access token if it expires.
	Expiry       time.Time   `json:"expiry,omitempty"`        // Expiry is the expiration time of the access token.
	Raw          interface{} // Raw optionally contains extra metadata from the server when updating a token.
}

Token represents the credentials used to authorize the requests to access protected resources on the OAuth 2.0 provider's backend.

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) IsExpired

func (t *Token) IsExpired() bool

IsExpired reports whether the token is expired.

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.

Jump to

Keyboard shortcuts

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