server

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2021 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CODE  AuthorizeRequestType = "code"
	TOKEN AuthorizeRequestType = "token"

	PKCE_PLAIN = "plain"
	PKCE_S256  = "S256"
)
View Source
const (
	E_INVALID_REQUEST           string = "invalid_request"
	E_UNAUTHORIZED_CLIENT              = "unauthorized_client"
	E_ACCESS_DENIED                    = "access_denied"
	E_UNSUPPORTED_RESPONSE_TYPE        = "unsupported_response_type"
	E_INVALID_SCOPE                    = "invalid_scope"
	E_SERVER_ERROR                     = "server_error"
	E_TEMPORARILY_UNAVAILABLE          = "temporarily_unavailable"
	E_UNSUPPORTED_GRANT_TYPE           = "unsupported_grant_type"
	E_INVALID_GRANT                    = "invalid_grant"
	E_INVALID_CLIENT                   = "invalid_client"
)
View Source
const PackageName = "component.eoauth2.server"

Variables

View Source
var (
	// ErrNotFound is the error returned by Storage Get<...> and Load<...> functions in case
	// no entity is found in the storage. E.g. Storage.GetClient() returns ErrNotFound when
	// client is not found. All other returned errors must be treated as storage-specific errors,
	// like "connection lost", "connection refused", etc.
	ErrNotFound = errors.New("Entity not found")
)

Functions

func CheckClientSecret

func CheckClientSecret(client Client, secret string) bool

CheckClientSecret determines whether the given secret matches a secret held by the client. Public clients return true for a secret of ""

func FirstUri

func FirstUri(baseUriList string, separator string) string

FirstUri Returns the first uri from an uri list

func ParseUrls

func ParseUrls(baseUrl, redirectUrl string) (retBaseUrl, retRedirectUrl *url.URL, err error)

Parse urls, resolving uri references to base url

func ValidateUri

func ValidateUri(baseUri string, redirectUri string) (realRedirectUri string, err error)

ValidateUri validates that redirectUri is contained in baseUri

func ValidateUriList

func ValidateUriList(baseUriList string, redirectUri string, separator string) (realRedirectUri string, err error)

ValidateUriList validates that redirectUri is contained in baseUriList. baseUriList may be a string separated by separator. If separator is blank, validate only 1 URI.

Types

type AccessData

type AccessData struct {
	// Client information
	Client Client

	// Authorize data, for authorization code
	AuthorizeData *AuthorizeData

	// Previous access data, for refresh token
	AccessData *AccessData

	// Access token
	AccessToken string

	// Refresh Token. Can be blank
	RefreshToken string

	// Token expiration in seconds
	ExpiresIn int32

	// Requested scope
	Scope string

	// Redirect Uri from request
	RedirectUri string

	// Date created
	CreatedAt time.Time

	// Data to be passed to storage. Not used by the library.
	UserData interface{}
}

AccessData represents an access grant (tokens, expiration, client, etc)

func (*AccessData) ExpireAt

func (d *AccessData) ExpireAt() time.Time

ExpireAt returns the expiration date

func (*AccessData) IsExpired

func (d *AccessData) IsExpired() bool

IsExpired returns true if access expired

func (*AccessData) IsExpiredAt

func (d *AccessData) IsExpiredAt(t time.Time) bool

IsExpiredAt returns true if access expires at time 't'

type AccessRequest

type AccessRequest struct {
	Type          AccessRequestType
	Code          string
	Client        Client
	AuthorizeData *AuthorizeData
	AccessData    *AccessData

	// Force finish to use this access data, to allow access data reuse
	ForceAccessData *AccessData
	RedirectUri     string
	Scope           string
	Username        string
	Password        string
	AssertionType   string
	Assertion       string

	Expiration int32 // Token expiration in seconds. Change if different from default

	// Set if a refresh token should be generated
	GenerateRefresh bool

	// Optional code_verifier as described in rfc7636
	CodeVerifier string
	*Context
	// contains filtered or unexported fields
}

AccessRequest is a request for access tokens

func (*AccessRequest) Build

func (ar *AccessRequest) Build(options ...AccessRequestOption) error

Build ...

type AccessRequestOption

type AccessRequestOption func(ar *AccessRequest)

AccessRequestOption 可选项

func WithAccessRequestAuthorized

func WithAccessRequestAuthorized(flag bool) AccessRequestOption

WithAccessRequestAuthorized 设置authorized flag

type AccessRequestParam

type AccessRequestParam struct {
	Code         string
	Scope        string
	CodeVerifier string
	RedirectUri  string
	ClientAuthParam
}

type AccessRequestType

type AccessRequestType string

AccessRequestType is the type for OAuth param `grant_type`

const (
	AUTHORIZATION_CODE AccessRequestType = "authorization_code"
	REFRESH_TOKEN      AccessRequestType = "refresh_token"
	PASSWORD           AccessRequestType = "password"
	CLIENT_CREDENTIALS AccessRequestType = "client_credentials"
	ASSERTION          AccessRequestType = "assertion"
	IMPLICIT           AccessRequestType = "__implicit"
)

type AccessTokenGen

type AccessTokenGen interface {
	GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error)
}

AccessTokenGen generates access tokens

type AccessTokenGenDefault

type AccessTokenGenDefault struct {
}

AccessTokenGenDefault is the default authorization token generator

func (*AccessTokenGenDefault) GenerateAccessToken

func (a *AccessTokenGenDefault) GenerateAccessToken(data *AccessData, generaterefresh bool) (accesstoken string, refreshtoken string, err error)

GenerateAccessToken generates base64-encoded UUID access and refresh tokens

type AllowedAccessTypes

type AllowedAccessTypes []AccessRequestType

AllowedAccessTypes is a collection of allowed access request types

func (AllowedAccessTypes) Exists

Exists returns true if the access type exists in the list

type AllowedAuthorizeTypes

type AllowedAuthorizeTypes []AuthorizeRequestType

AllowedAuthorizeTypes is a collection of allowed auth request types

func (AllowedAuthorizeTypes) Exists

Exists returns true if the auth type exists in the list

type AuthorizeData

type AuthorizeData struct {
	Client              Client      // Client information
	Code                string      // Authorization code
	ExpiresIn           int32       // Token expiration in seconds
	Scope               string      // Requested scope
	RedirectUri         string      // Redirect Uri from request
	State               string      // State data from request
	CreatedAt           time.Time   // Date created
	UserData            interface{} // Data to be passed to storage. Not used by the library.
	CodeChallenge       string      // Optional code_challenge as described in rfc7636
	CodeChallengeMethod string      // Optional code_challenge_method as described in rfc7636
	*Context

	ParentToken string // 如果存在parent token,赋值
	// contains filtered or unexported fields
}

AuthorizeData ...

func (*AuthorizeData) ExpireAt

func (d *AuthorizeData) ExpireAt() time.Time

ExpireAt returns the expiration date

func (*AuthorizeData) IsExpired

func (d *AuthorizeData) IsExpired() bool

IsExpired is true if authorization expired

func (*AuthorizeData) IsExpiredAt

func (d *AuthorizeData) IsExpiredAt(t time.Time) bool

IsExpiredAt is true if authorization expires at time 't'

type AuthorizeRequest

type AuthorizeRequest struct {
	Type   AuthorizeRequestType
	Client Client
	Scope  string
	State  string

	// Token expiration in seconds. Change if different from default.
	// If type = TOKEN, this expiration will be for the ACCESS token.
	Expiration int32

	// Optional code_challenge as described in rfc7636
	CodeChallenge string
	// Optional code_challenge_method as described in rfc7636
	CodeChallengeMethod string
	*Context

	ParentToken string // 可选项,用于单点登录
	// contains filtered or unexported fields
}

AuthorizeRequest information

func (*AuthorizeRequest) Build

func (r *AuthorizeRequest) Build(options ...AuthorizeRequestOption) error

Build 处理authorize请求

type AuthorizeRequestOption

type AuthorizeRequestOption func(ar *AuthorizeRequest)

AuthorizeRequestOption 可选项

func WithAuthorizeRequestAuthorized

func WithAuthorizeRequestAuthorized(flag bool) AuthorizeRequestOption

WithAuthorizeRequestAuthorized 设置authorize的flag信息

func WithAuthorizeRequestUserData

func WithAuthorizeRequestUserData(userData interface{}) AuthorizeRequestOption

WithAuthorizeRequestUserData 设置authorize的user data信息

type AuthorizeRequestParam

type AuthorizeRequestParam struct {
	ClientId            string
	RedirectUri         string
	Scope               string
	State               string
	ResponseType        string
	CodeChallenge       string
	CodeChallengeMethod string
	ParentToken         string
}

type AuthorizeRequestType

type AuthorizeRequestType string

AuthorizeRequestType is the type for OAuth param `response_type`

type AuthorizeTokenGen

type AuthorizeTokenGen interface {
	GenerateAuthorizeToken(data *AuthorizeData) (string, error)
}

AuthorizeTokenGen is the token generator interface

type AuthorizeTokenGenDefault

type AuthorizeTokenGenDefault struct {
}

AuthorizeTokenGenDefault is the default authorization token generator

func (*AuthorizeTokenGenDefault) GenerateAuthorizeToken

func (a *AuthorizeTokenGenDefault) GenerateAuthorizeToken(data *AuthorizeData) (ret string, err error)

GenerateAuthorizeToken generates a base64-encoded UUID code

type BasicAuth

type BasicAuth struct {
	Username string
	Password string
}

Parse basic authentication header

func CheckBasicAuth

func CheckBasicAuth(param BasicAuthParam) (*BasicAuth, error)

Return authorization header data

type BasicAuthParam

type BasicAuthParam struct {
	Authorization string
}

type BearerAuth

type BearerAuth struct {
	Code string
}

Parse bearer authentication header

type Client

type Client interface {
	// Client id
	GetId() string

	// Client secret
	GetSecret() string

	// Base client uri
	GetRedirectUri() string

	// Data to be passed to storage. Not used by the library.
	GetUserData() interface{}
}

Client information

type ClientAuthParam

type ClientAuthParam struct {
	ClientId      string
	ClientSecret  string
	Authorization string
}

type ClientSecretMatcher

type ClientSecretMatcher interface {
	// SecretMatches returns true if the given secret matches
	ClientSecretMatches(secret string) bool
}

ClientSecretMatcher is an optional interface clients can implement which allows them to be the one to determine if a secret matches. If a Client implements ClientSecretMatcher, the framework will never call GetSecret

type Component

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

Component ...

func (*Component) HandleAccessRequest

func (c *Component) HandleAccessRequest(ctx context.Context, param ParamAccessRequest) *AccessRequest

HandleAccessRequest is the http.HandlerFunc for handling access token requests

func (*Component) HandleAuthorizeRequest

func (c *Component) HandleAuthorizeRequest(ctx context.Context, param AuthorizeRequestParam) *AuthorizeRequest

HandleAuthorizeRequest for handling

type Config

type Config struct {
	EnableAccessInterceptor bool                  // 是否开启,记录请求数据
	AuthorizationExpiration int32                 // Authorization token expiration in seconds (default 5 minutes)
	AccessExpiration        int32                 // Access token expiration in seconds (default 1 hour)
	TokenType               string                // Token type to return
	AllowedAuthorizeTypes   AllowedAuthorizeTypes // List of allowed authorize types (only CODE by default)
	AllowedAccessTypes      AllowedAccessTypes    // List of allowed access types (only AUTHORIZATION_CODE by default)
	// HTTP status code to return for errors - default 200
	// Only used if response was created from server
	ErrorStatusCode int
	// If true allows client secret also in params, else only in
	// Authorization header - default false
	AllowClientSecretInParams bool
	// If true allows access request using GET, else only POST - default false
	AllowGetAccessRequest bool
	// Require PKCE for code flows for public OAuth clients - default false
	RequirePKCEForPublicClients bool
	// Separator to support multiple URIs in Client.GetRedirectUri().
	// If blank (the default), don't allow multiple URIs.
	RedirectUriSeparator string
	// RetainTokenAfter Refresh allows the server to retain the access and
	// refresh token for re-use - default false
	RetainTokenAfterRefresh bool
	// contains filtered or unexported fields
}

Config contains server configuration information

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig ...

type Container

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

func DefaultContainer

func DefaultContainer() *Container

func Load

func Load(key string) *Container

func (*Container) Build

func (c *Container) Build(options ...Option) *Component

Build ...

type Context

type Context struct {
	Ctx context.Context
	// contains filtered or unexported fields
}

func (*Context) GetAllOutput

func (c *Context) GetAllOutput() interface{}

func (*Context) GetOutput

func (c *Context) GetOutput(key string) interface{}

func (*Context) GetRedirectUrl

func (c *Context) GetRedirectUrl() (string, error)

GetRedirectUrl returns the redirect url with all query string parameters

func (*Context) IsError

func (c *Context) IsError() bool

func (*Context) SetOutput

func (c *Context) SetOutput(key string, value interface{})

type DefaultClient

type DefaultClient struct {
	Id          string
	Secret      string
	RedirectUri string
	UserData    interface{}
}

DefaultClient stores all data in struct variables

func (*DefaultClient) ClientSecretMatches

func (d *DefaultClient) ClientSecretMatches(secret string) bool

Implement the ClientSecretMatcher interface

func (*DefaultClient) CopyFrom

func (d *DefaultClient) CopyFrom(client Client)

func (*DefaultClient) GetId

func (d *DefaultClient) GetId() string

func (*DefaultClient) GetRedirectUri

func (d *DefaultClient) GetRedirectUri() string

func (*DefaultClient) GetSecret

func (d *DefaultClient) GetSecret() string

func (*DefaultClient) GetUserData

func (d *DefaultClient) GetUserData() interface{}

type DefaultErrorId

type DefaultErrorId string

type Option

type Option func(c *Container)

func WithStorage

func WithStorage(storage Storage) Option

WithStorage 注入存储

type ParamAccessRequest

type ParamAccessRequest struct {
	Method    string
	GrantType string
	AccessRequestParam
}

type ResponseData

type ResponseData map[string]interface{}

ResponseData for response output

type ResponseType

type ResponseType int

ResponseType enum

const (
	DATA ResponseType = iota
	REDIRECT
)

type Storage

type Storage interface {
	// Clone the storage if needed. For example, using mgo, you can clone the session with session.Clone
	// to avoid concurrent access problems.
	// This is to avoid cloning the connection at each method access.
	// Can return itself if not a problem.
	Clone() Storage

	// Close the resources the Storage potentially holds (using Clone for example)
	Close()

	// GetClient loads the client by id (client_id)
	GetClient(ctx context.Context, id string) (Client, error)

	// SaveAuthorize saves authorize data.
	SaveAuthorize(context.Context, *AuthorizeData) error

	// LoadAuthorize looks up AuthorizeData by a code.
	// Client information MUST be loaded together.
	// Optionally can return error if expired.
	LoadAuthorize(ctx context.Context, code string) (*AuthorizeData, error)

	// RemoveAuthorize revokes or deletes the authorization code.
	RemoveAuthorize(ctx context.Context, code string) error

	// SaveAccess writes AccessData.
	// If RefreshToken is not blank, it must save in a way that can be loaded using LoadRefresh.
	SaveAccess(context.Context, *AccessData) error

	// LoadAccess retrieves access data by token. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadAccess(ctx context.Context, token string) (*AccessData, error)

	// RemoveAccess revokes or deletes an AccessData.
	RemoveAccess(ctx context.Context, token string) error

	// LoadRefresh retrieves refresh AccessData. Client information MUST be loaded together.
	// AuthorizeData and AccessData DON'T NEED to be loaded if not easily available.
	// Optionally can return error if expired.
	LoadRefresh(ctx context.Context, token string) (*AccessData, error)

	// RemoveRefresh revokes or deletes refresh AccessData.
	RemoveRefresh(ctx context.Context, token string) error
}

Storage interface

type UriValidationError

type UriValidationError string

error returned when validation don't match

func (UriValidationError) Error

func (e UriValidationError) Error() string

Jump to

Keyboard shortcuts

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