oauth2

package module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2020 License: MIT Imports: 6 Imported by: 1

README

oauth2

Build Status Coverage Status GoDoc Release Go Report Card

A fundamental and extendable OAuth2 library for Go.

Package oauth2 provides structures and functions to implement OAuth2 compatible authentication servers. The library can be used standalone or with any framework as it is built on top of the standard Go http library.

Specifications

The library considers and implements the following specifications:

Example

The server package implements a basic but feature-complete in-memory OAuth2 authentication server. The code can be used as a template to build a custom implementation of an OAuth2 compatible authentication server.

Installation

Get the package using the go tool:

$ go get -u github.com/256dpi/oauth2

License

The MIT License (MIT)

Copyright (c) 2016 Joël Gähwiler

Documentation

Overview

Package oauth2 provides structures and functions to implement OAuth2 compatible authentication servers.

The library can be used standalone or with any framework as it is built on top of the standard Go http library.

Index

Constants

View Source
const (
	PasswordGrantType          = "password"
	ClientCredentialsGrantType = "client_credentials"
	AuthorizationCodeGrantType = "authorization_code"
	RefreshTokenGrantType      = "refresh_token"
)

The known OAuth2 grant types.

View Source
const (
	TokenResponseType = "token"
	CodeResponseType  = "code"
)

The known OAuth2 response types.

Variables

This section is empty.

Functions

func KnownGrantType

func KnownGrantType(str string) bool

KnownGrantType returns true if the grant type is a known grant type (e.g. password, client credentials, authorization code or refresh token).

func KnownResponseType

func KnownResponseType(str string) bool

KnownResponseType returns true if the response type is a known response type (e.g. token or code).

func Write

func Write(w http.ResponseWriter, obj interface{}, status int) error

Write will encode the specified object as json and write a response to the response writer as specified by the OAuth2 spec.

func WriteCodeResponse added in v0.4.0

func WriteCodeResponse(w http.ResponseWriter, r *CodeResponse) error

WriteCodeResponse will write a redirection based on the specified code response to the response writer.

func WriteError

func WriteError(w http.ResponseWriter, err error) error

WriteError will write the specified error to the response writer. The function will fall back and write a server error if the specified error is not known. If the RedirectURI field is present on the error a redirection will be written instead.

func WriteRedirect added in v0.4.0

func WriteRedirect(w http.ResponseWriter, uri string, params map[string]string, useFragment bool) error

WriteRedirect will either add the specified parameters to the query of the specified uri or encode them and it as the fragment as specified by the OAuth2 spec.

func WriteTokenResponse

func WriteTokenResponse(w http.ResponseWriter, r *TokenResponse) error

WriteTokenResponse will write the specified response to the response writer. If the RedirectURI field is present on the response a redirection that transmits the token in the fragment will be written instead.

Types

type AuthorizationRequest

type AuthorizationRequest struct {
	ResponseType string
	Scope        Scope
	ClientID     string
	RedirectURI  string
	State        string

	HTTP *http.Request
}

A AuthorizationRequest is typically returned by ParseAuthorizationRequest and holds all information necessary to handle an authorization request.

func ParseAuthorizationRequest

func ParseAuthorizationRequest(r *http.Request) (*AuthorizationRequest, error)

ParseAuthorizationRequest parses an incoming request and returns an AuthorizationRequest. The functions validates basic constraints given by the OAuth2 spec.

type CodeResponse

type CodeResponse struct {
	Code  string `json:"code"`
	State string `json:"state,omitempty"`

	RedirectURI string `json:"-"`
}

A CodeResponse is typically constructed after an authorization code request has been authenticated to return an authorization code.

func NewCodeResponse

func NewCodeResponse(code, redirectURI, state string) *CodeResponse

NewCodeResponse constructs a CodeResponse.

func (*CodeResponse) Map

func (r *CodeResponse) Map() map[string]string

Map returns a map of all fields that can be presented to the client. This method can be used to construct query parameters or a fragment when redirecting the code response.

type Error

type Error struct {
	Name        string `json:"error"`
	State       string `json:"state,omitempty"`
	Description string `json:"error_description,omitempty"`
	URI         string `json:"error_uri,omitempty"`

	Status      int               `json:"-"`
	Headers     map[string]string `json:"-"`
	RedirectURI string            `json:"-"`
	UseFragment bool              `json:"-"`
}

An Error represents an error object defined by the OAuth2 specification. All functions that are used during the authorization and token request processing flow return such error instances.

func AccessDenied

func AccessDenied(description string) *Error

AccessDenied constructs an error that indicates that the resource owner or authorization server denied the request.

func InvalidClient

func InvalidClient(description string) *Error

InvalidClient constructs an error that indicates that the client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method).

func InvalidGrant

func InvalidGrant(description string) *Error

InvalidGrant constructs an error that indicates that the provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

func InvalidRequest

func InvalidRequest(description string) *Error

InvalidRequest constructs an error that indicates that the request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed.

func InvalidScope

func InvalidScope(description string) *Error

InvalidScope constructs an error that indicates that the requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.

func ServerError

func ServerError(description string) *Error

ServerError constructs an error that indicates that the authorization server encountered an unexpected condition that prevented it from fulfilling the request.

func TemporarilyUnavailable

func TemporarilyUnavailable(description string) *Error

TemporarilyUnavailable constructs an error that indicates that the authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server.

func UnauthorizedClient

func UnauthorizedClient(description string) *Error

UnauthorizedClient constructs an error that indicates that the authenticated client is not authorized to use this authorization grant type or method to request and access token.

func UnsupportedGrantType

func UnsupportedGrantType(description string) *Error

UnsupportedGrantType constructs an error that indicates that the authorization grant type is not supported by the authorization server.

func UnsupportedResponseType

func UnsupportedResponseType(description string) *Error

UnsupportedResponseType constructs an error that indicates that the authorization server does not support obtaining an access token using this method.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Map

func (e *Error) Map() map[string]string

Map returns a map of all fields that can be presented to the client. This method can be used to construct query parameters or a fragment when redirecting the error.

func (*Error) SetRedirect added in v0.4.1

func (e *Error) SetRedirect(uri, state string, useFragment bool) *Error

SetRedirect marks the error to be redirected by setting the state value as well as the redirect URI and whether the error should be added to the query parameter or fragment part of the URI.

func (*Error) String

func (e *Error) String() string

String implements the fmt.Stringer interface.

type Scope

type Scope []string

A Scope is received typically in an authorization and token request.

func ParseScope

func ParseScope(str string) Scope

ParseScope parses the joined string representation of a scope.

func (Scope) Contains

func (s Scope) Contains(str string) bool

Contains returns true if the specified string is part of the scope.

func (Scope) Empty

func (s Scope) Empty() bool

Empty return true if the scope is empty.

func (Scope) Includes

func (s Scope) Includes(scope Scope) bool

Includes returns true if the specified scope is included in this scope.

func (Scope) MarshalJSON

func (s Scope) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Scope) String

func (s Scope) String() string

String implements the fmt.Stringer interface.

type TokenRequest

type TokenRequest struct {
	GrantType    string
	Scope        Scope
	ClientID     string
	ClientSecret string
	Username     string
	Password     string
	RefreshToken string
	RedirectURI  string
	Code         string

	HTTP *http.Request
}

A TokenRequest is typically returned by ParseTokenRequest and holds all information necessary to handle a token request.

func ParseTokenRequest

func ParseTokenRequest(r *http.Request) (*TokenRequest, error)

ParseTokenRequest parses an incoming request and returns a TokenRequest. The functions validates basic constraints given by the OAuth2 spec.

Note: Obtaining the client id and secret from the request body (form data) is not implemented by default due to security considerations.

type TokenResponse

type TokenResponse struct {
	TokenType    string `json:"token_type"`
	AccessToken  string `json:"access_token"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
	Scope        Scope  `json:"scope,omitempty"`
	State        string `json:"state,omitempty"`

	RedirectURI string `json:"-"`
}

A TokenResponse is typically constructed after a token request has been authenticated and authorized to return an access token, a potential refresh token and more detailed information.

func NewTokenResponse

func NewTokenResponse(tokenType, accessToken string, expiresIn int) *TokenResponse

NewTokenResponse constructs a TokenResponse.

func (*TokenResponse) Map

func (r *TokenResponse) Map() map[string]string

Map returns a map of all fields that can be presented to the client. This method can be used to construct query parameters or a fragment when redirecting the token response.

func (*TokenResponse) SetRedirect added in v0.4.1

func (r *TokenResponse) SetRedirect(uri, state string) *TokenResponse

SetRedirect marks the response to be redirected by setting the redirect URI and state.

Directories

Path Synopsis
Package bearer provides structures and functions to implement the additional OAuth2 Bearer Token specification.
Package bearer provides structures and functions to implement the additional OAuth2 Bearer Token specification.
Package client implements a low-level OAuth2 client to perform the various request/response flows against a OAuth2 authentication server.
Package client implements a low-level OAuth2 client to perform the various request/response flows against a OAuth2 authentication server.
Package hmacsha provides a simple token implementation using the hmac-sha256 algorithm.
Package hmacsha provides a simple token implementation using the hmac-sha256 algorithm.
Package introspection provides structures and functions to implement the additional OAuth2 Token Introspection specification.
Package introspection provides structures and functions to implement the additional OAuth2 Token Introspection specification.
Package revocation provides structures and functions to implement the additional OAuth2 Token Revocation specification.
Package revocation provides structures and functions to implement the additional OAuth2 Token Revocation specification.
Package server provides a basic in-memory OAuth2 authentication server intended for testing purposes.
Package server provides a basic in-memory OAuth2 authentication server intended for testing purposes.
Package spec implements reusable integration tests to test against any OAuth2 authentication server.
Package spec implements reusable integration tests to test against any OAuth2 authentication server.

Jump to

Keyboard shortcuts

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