oauth2

package module
v0.0.0-...-2f30af1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: Apache-2.0 Imports: 1 Imported by: 0

README

Golang Oauth2 Server

Based on the secondary development github.com/go-oauth2, provides TokenStore and TokenGenerator based on interface can be pull out plug type design, can easily customize their need TokenStore and the Generator, and support the TokenGC.

Features

  • clear configuration items with default configuration(config.go)
  • 7 custom hooks are supported to extend logic in the authorization process (server/handler.go)
  • support response in hook functions (such as output authorization page, error page, etc., subsequent authorization logic is automatically interrupted)
  • support for Token GC
  • support custom Token Store with any database (you need to implement the store.tokenstore interface yourself)
  • support custom Token Generator with any algorithm (you need to implement the Generator.Generator interface yourself)
  • based entirely on RFC 6749 implementation (support RedirectURI is empty, support multiple RedirectURI configuration)

Quick Start

Download and install
go get github.com/sagacioushugo/oauth2
Build and run example
go build server.go
./server

go build client.go
./client
Request to client in browser

After receiving the corresponding request, the client will automatically simulate a certain authorization pattern and return the token obtained to the browser

Test the authorization process with RFC 6749 and client logs

Authorization Pattern Client Url note
Authorization Code http://localhost:8080/test/authorization_code
Implicit http://localhost:8080/test/implicit
Password Credentials http://localhost:8080/test/password
Client Credentials http://localhost:8080/test/client_credentials
Refreshing an access token http://localhost:8080/test/refresh_token?refresh_token=yourtoken param refresh_token is required

Documentation

Apache License 2.0

Copyright (c) 2019 Guoyiming

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// oauth2 err https://tools.ietf.org/html/rfc6749#section-5.2
	ErrInvalidRequest          = NewError(http.StatusBadRequest, "invalid_request", "The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.")
	ErrUnauthorizedClient      = NewError(http.StatusUnauthorized, "unauthorized_client", "The authenticated client is not authorized to use this authorization grant type.")
	ErrAccessDenied            = NewError(http.StatusUnauthorized, "access_denied", "The resource owner or authorization server denied the request")
	ErrUnsupportedResponseType = NewError(http.StatusUnauthorized, "unsupported_response_type", "The authorization server does not support obtaining an authorization code or an access token using this method")
	ErrInvalidScope            = NewError(http.StatusBadRequest, "invalid_scope", "The requested scope is invalid, unknown, or malformed")
	ErrServerError             = NewError(http.StatusInternalServerError, "server_error", "The authorization server encountered an unexpected condition that prevented it from fulfilling the request")
	ErrTemporarilyUnavailable  = NewError(http.StatusServiceUnavailable, "temporarily_unavailable", "The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server")
	ErrInvalidClient           = NewError(http.StatusBadRequest, "invalid_client", "Client authentication failed")
	ErrInvalidGrant            = NewError(http.StatusUnauthorized, "invalid_grant", "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")
	ErrUnsupportedGrantType    = NewError(http.StatusUnauthorized, "unsupported_grant_type", "The authorization grant type is not supported by the authorization server")

	// extra customized errors
	ErrInvalidRedirectURI        = NewError(http.StatusBadRequest, "invalid_redirect_uri", "The request is missing redirect uri or includes an invalid redirect uri value")
	ErrInvalidAuthorizeCode      = NewError(http.StatusBadRequest, "invalid_authorize_code", "The request is missing authorize code or includes an invalid authorize code value")
	ErrInvalidAccessToken        = NewError(http.StatusBadRequest, "invalid_access_token", "The request is missing access token or includes an invalid access token value")
	ErrInvalidRefreshToken       = NewError(http.StatusBadRequest, "invalid_refresh_token", "The request is missing refresh token or includes an invalid refresh token value")
	ErrExpiredAuthorizeCode      = NewError(http.StatusBadRequest, "expired_authorize_code", "The request includes an expired authorize code value")
	ErrExpiredAccessToken        = NewError(http.StatusBadRequest, "expired_access_token", "The request includes an expired access token value")
	ErrExpiredRefreshToken       = NewError(http.StatusBadRequest, "expired_refresh_token", "The request includes an expired refresh token value")
	ErrInvalidUsernameOrPassword = NewError(http.StatusBadRequest, "invalid_username_or_password", "The request includes invalid username or password")
)
View Source
var DefaultOauth2Config = Config{
	TokenType:          "Bearer",
	RedirectUriSep:     "|",
	RedirectAllowEmpty: false,
	AllowGrantType: map[GrantType]GrantTypeConfig{
		AuthorizationCode: {
			AccessTokenExpire:  12 * 3600,
			RefreshTokenExpire: 72 * 3600,
			CodeExpire:         300,
			IsGenerateRefresh:  true,
			IsResetRefreshTime: false,
		},
		Implicit: {
			AccessTokenExpire:  6 * 3600,
			IsGenerateRefresh:  false,
			IsResetRefreshTime: false,
		},
		PasswordCredentials: {
			AccessTokenExpire:  6 * 3600,
			IsGenerateRefresh:  false,
			IsResetRefreshTime: false,
		},
		ClientCredentials: {
			AccessTokenExpire:  6 * 3600,
			IsGenerateRefresh:  false,
			IsResetRefreshTime: false,
		},
		RefreshToken: {
			AccessTokenExpire:  12 * 3600,
			RefreshTokenExpire: 72 * 3600,
			IsGenerateRefresh:  true,
			IsResetRefreshTime: false,
		},
	},
	ManagerConfig: ManagerConfig{
		TokenGcInterval:  7 * 24 * 3600,
		TokenStoreName:   "mem",
		GeneratorName:    "default",
		TokenStoreConfig: "",
	},
}

Functions

This section is empty.

Types

type Config

type Config struct {
	TokenType          string
	RedirectUriSep     string
	RedirectAllowEmpty bool
	AllowGrantType     map[GrantType]GrantTypeConfig
	ManagerConfig      ManagerConfig
}

func NewDefaultConfig

func NewDefaultConfig() *Config

type GrantType

type GrantType string
const (
	AuthorizationCode   GrantType = "authorization_code"
	Implicit            GrantType = "__implicit"
	PasswordCredentials GrantType = "password"
	ClientCredentials   GrantType = "client_credentials"
	RefreshToken        GrantType = "refresh_token"
)

func (GrantType) IsValid

func (gt GrantType) IsValid() bool

type GrantTypeConfig

type GrantTypeConfig struct {
	CodeExpire         int64
	AccessTokenExpire  int64
	RefreshTokenExpire int64
	IsGenerateRefresh  bool
	IsResetRefreshTime bool
}

type ManagerConfig

type ManagerConfig struct {
	TokenGcInterval  int64
	TokenStoreName   string
	TokenStoreConfig string
	GeneratorName    string
}

type Oauth2Error

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

func NewError

func NewError(statusCode int, msg string, description string) *Oauth2Error

func (Oauth2Error) Error

func (e Oauth2Error) Error() string

func (Oauth2Error) ErrorDescription

func (e Oauth2Error) ErrorDescription() string

func (Oauth2Error) StatusCode

func (e Oauth2Error) StatusCode() int

type Request

type Request struct {
	// authorize
	ResponseType ResponseType
	State        string

	// token
	ClientSecret string
	Code         string
	Refresh      string

	//common
	ClientId    string
	ClientInfo  map[string]string
	GrantType   GrantType
	UserId      string
	RedirectUri string
	Scope       string
}

type Response

type Response struct {
	Error       error
	ErrorCode   int
	Description string
	Uri         string
	StatusCode  int
	Header      http.Header
}

Response error response

type ResponseType

type ResponseType string
const (
	Token ResponseType = "token"
	Code  ResponseType = "code"
)

func (ResponseType) IsValid

func (rt ResponseType) IsValid() bool

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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