oauth

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2022 License: MIT Imports: 43 Imported by: 0

README

Hiro Oauth 2.0

This package provides a base OAuth 2.0 implementation for Model Rocket projects.

Pre-requisites

The comsumer only needs to implements the Controller and associated interfaces to provide backend storage for requests, tokens, and sessions.

Controller

Structs
Interfaces
Client
User

Flows

Hiro OAuth supports a limited set of authorization flows. This is due both to need, but also to avoid unecessary security risk.

Authorization Code

Unlike other OAuth libraries, for the authorization_code grant hiro does not provide any html forms, these are abstracted securly from the project and expected to be hosted externally. This allows for each application to have custom login interfaces.

hiro makes his process secure by generating a login request token in the authorize route handler and redirecting the browser to the app_uri specified in the query. The browser will then post the the login route, including this token and the PKCE code verifier to authenticate the user. The browser will then be redirected to the redirect_uri provided in the authorize call, which will have the standard code parameter that can be used to request a bearer token.

sequenceDiagram
    browser->>hiro:GET /authroize?response_type=code...
    hiro->>browser: 302 FOUND Location: {api_uri}
    browser->>app: GET {app_uri}?request_token={request_token}
    app->>browser: 200 OK
    Note right of browser: User enters credentials into form
    browser->>hiro: POST /oauth/login
    hiro->>browser: 302 FOUND Location: {redirect_uri}?code={auth_code}
    browser->>app: GET {redirect_uri}?code={auth_code}
    app->>hiro: POST /oauth/token
    hiro->>app: 200 OK
Client Credentials
Refresh Token

API

The API is informally defined in this OpenAPI 2.0 Spec. This spec is self-contained and is served in the /oauth/swagger.{json|yaml} route for clients to access.

Routes

The package provides a Routes set that is designed to be used with the api.Server package, which can extend another api service adding authentication support.

GET /authorize
POST /login
GET /token

Documentation

Overview

Package oauth provides the base auth interfaces

Index

Constants

View Source
const (
	// NotificationTypeVerify are verification notifications
	NotificationTypeVerify NotificationType = "verify"

	// NotificationTypePassword are password notification
	NotificationTypePassword NotificationType = "password"

	// NotificationTypeInvite are invitation notification
	NotificationTypeInvite NotificationType = "invite"

	// NotificationChannelEmail is an email notification
	NotificationChannelEmail NotificationChannel = "email"

	// NotificationChannelPhone is an sms notification
	NotificationChannelPhone NotificationChannel = "phone"
)
View Source
const (
	// ScopeOpenID is the openid scope
	ScopeOpenID = "openid"

	// ScopeProfile is the scope required to query for a users profile
	ScopeProfile = "profile"

	// ScopeProfileWrite is the scope required to write to a users profile
	ScopeProfileWrite = "profile:write"

	// ScopeOfflineAccess is the scope necessary to request a refresh_token
	ScopeOfflineAccess = "offline_access"

	// ScopeAddress is required to read a user's physical address
	ScopeAddress = "address"

	// ScopeEmail is the scope require to get a user's email address
	ScopeEmail = "email"

	// ScopeEmailVerify is the scope required to verify a user's email address
	ScopeEmailVerify = "emai:verify"

	// ScopePhone is the scope required to verify the user's phone number
	ScopePhone = "phone"

	// ScopePhoneVerify is the scope required to verify a user's phone number
	ScopePhoneVerify = "phone:verify"

	// ScopeTokenRead is provided for token introspection
	ScopeTokenRead = "token:read"

	// ScopeTokenRevoke is required for token revocation
	ScopeTokenRevoke = "token:revoke"

	// ScopeSession creates a login session
	ScopeSession = "session"

	// ScopePassword allows a user to set their password
	ScopePassword = "password"
)
View Source
const (
	// RequestTokenParam is the name of the request token parameter passed on redirect from /authorize
	RequestTokenParam = "request_token"
)

Variables

View Source
var (
	// ErrUnauthorized is returned when authentication has failed
	ErrUnauthorized = api.ErrUnauthorized.WithCode("access_denied")

	// ErrForbidden is returned when authorization has failed
	ErrForbidden = api.ErrForbidden.WithCode("access_denied")

	// ErrClientNotFound is returned when the controller could not find the client
	ErrClientNotFound = api.ErrNotFound.WithMessage("client not found")

	// ErrAudienceNotFound is returned when the store could not find the audience
	ErrAudienceNotFound = api.ErrNotFound.WithMessage("audience not found")

	// ErrUserNotFound is returned when the store could not find the user
	ErrUserNotFound = api.ErrNotFound.WithMessage("user not found")

	// ErrSessionNotFound is returned when the session was not found by the controller
	ErrSessionNotFound = api.ErrNotFound.WithMessage("session not found")

	// ErrUnsupportedAlogrithm is returned when the Authorizer gets a bad token
	ErrUnsupportedAlogrithm = api.ErrBadRequest.WithMessage("unsupported signing algorithm")

	// ErrInvalidToken is returned when the token is not valid
	ErrInvalidToken = api.ErrBadRequest.WithCode("invalid_token")

	// ErrInvalidGrant is returned when the grant is not valid for the client
	ErrInvalidGrant = api.ErrBadRequest.WithCode("invalid_grant")

	// ErrInvalidClient is returned when the client is not valid
	ErrInvalidClient = ErrUnauthorized.WithCode("invalid_client")

	// ErrKeyNotFound is returned when the authorizer can not find a good key
	ErrKeyNotFound = ErrUnauthorized.WithMessage("suitable verification key not found")

	// ErrRevokedToken is returned when the token is revoked
	ErrRevokedToken = ErrUnauthorized.WithCode("revoked_token")

	// ErrExpiredToken is returned when the token is expired
	ErrExpiredToken = ErrUnauthorized.WithCode("expired_token")

	// ErrPasswordLen is returned when a password does not meet length requirements
	ErrPasswordLen = api.ErrBadRequest.WithMessage("invalid password length")

	// ErrPasswordComplexity is returned if the password does not meet complexity requirements
	ErrPasswordComplexity = api.ErrBadRequest.WithMessage("password does not meet complexity requirements")

	// ErrPasswordResuse is returned if password does not meet the reuse constraints
	ErrPasswordResuse = api.ErrBadRequest.WithMessage("password has been used before")

	// ErrPasswordExpired is returned when the password has expired
	ErrPasswordExpired = api.ErrBadRequest.WithMessage("password has expired")

	// ErrInvalidInviteCode is returned when an invitation code is bad
	ErrInvalidInviteCode = api.ErrBadRequest.WithMessage("invite code is invalid")

	// ErrUnauthorizedClient is returned when a client is not allow access to a method
	ErrUnauthorizedClient = api.ErrUnauthorized.WithCode("unauthorized_client")

	// ErrInvalidScope is returned when a client requests an invalid scope
	ErrInvalidScope = api.ErrBadRequest.WithCode("invalid_code")

	// ErrInvalidRequest is returned when a client request is invalid
	ErrInvalidRequest = api.ErrBadRequest.WithCode("invalid_request")
)
View Source
var (
	// PasscodeLength is the length of random passcodes to generate for OTPs
	PasscodeLength = 6

	// SessionPrefix is the prefix used for session names
	SessionPrefix = "hiro-session#"
)
View Source
var (
	// Scopes is the list of all oauth scopes
	// verify scopes have special use and should not be granted to users implicitly
	Scopes = Scope{
		ScopeOpenID,
		ScopeProfile,
		ScopeProfileWrite,
		ScopeOfflineAccess,
		ScopeAddress,
		ScopeEmail,
		ScopeEmailVerify,
		ScopePhone,
		ScopePhoneVerify,
		ScopeTokenRead,
		ScopeTokenRevoke,
	}

	// IsValidScope is used by validators to check if a scope atom is valid
	IsValidScope = validation.NewStringRuleWithError(IsScope, validation.NewError("oauth_is_scope", "scope atoms must not contain whitespace"))
)
View Source
var (
	// DefaultCodeChallengeMethod is the only challenge method
	DefaultCodeChallengeMethod = "S256"
)

Functions

func ApiSwaggerV1OauthSwaggerYaml

func ApiSwaggerV1OauthSwaggerYaml() (*asset, error)

func ApiSwaggerV1OauthSwaggerYamlBytes

func ApiSwaggerV1OauthSwaggerYamlBytes() ([]byte, error)

func Asset

func Asset(name string) ([]byte, error)

Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetDir

func AssetDir(name string) ([]string, error)

AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:

data/
  foo.txt
  img/
    a.png
    b.png

then AssetDir("data") would return []string{"foo.txt", "img"} AssetDir("data/img") would return []string{"a.png", "b.png"} AssetDir("foo.txt") and AssetDir("notexist") would return an error AssetDir("") will return []string{"data"}.

func AssetInfo

func AssetInfo(name string) (os.FileInfo, error)

AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.

func AssetNames

func AssetNames() []string

AssetNames returns the names of the assets.

func Authorizer

func Authorizer(opts ...AuthorizerOption) api.Authorizer

Authorizer returns a oauth api.Authorizer

func ClientCredentials

func ClientCredentials(config clientcredentials.Config, secure bool) (credentials.PerRPCCredentials, error)

ClientCredentials returns the ClientCredentials for the hiro

func EnsureURI added in v0.1.2

func EnsureURI(ctx context.Context, uri string, search []string) (*url.URL, error)

EnsureURI checks that a uri matches within a list

func IsScope added in v0.1.2

func IsScope(s string) bool

IsScope ensures the scope conforms to oauth rfc spec

func MustAsset

func MustAsset(name string) []byte

MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables.

func RestoreAsset

func RestoreAsset(dir, name string) error

RestoreAsset restores an asset under the given directory

func RestoreAssets

func RestoreAssets(dir, name string) error

RestoreAssets restores an asset under the given directory recursively

func Routes

func Routes() []api.Route

Routes returns the oauth api routes

Types

type Audience

type Audience interface {
	// ID returns the audience identifier
	ID() string

	// Secret returns a token secret from the audience, implementations should rotate the secrets
	Secrets() []TokenSecret

	// Permissions returns the fullset of audience permissions
	Permissions() Scope

	// RefreshTokenLifetime returns the duration a refreshtoken should last
	RefreshTokenLifetime() time.Duration
}

Audience is the common oauth audience interface

type AudienceGetInput added in v0.1.2

type AudienceGetInput struct {
	Audience string `json:"audience"`
}

AudienceGetInput is the input for AudienceGet

func (AudienceGetInput) Validate added in v0.1.2

func (i AudienceGetInput) Validate() error

Validate implements the validation.Validatable interface

type AuthorizeClientInput added in v0.1.2

type AuthorizeClientInput struct {
	GrantType   GrantType
	AppURI      *string
	RedirectURI *string
	Scope       Scope
	Request     *http.Request
}

type AuthorizeParams

type AuthorizeParams struct {
	AppURI              string               `json:"app_uri"`
	Audience            string               `json:"audience"`
	ClientID            string               `json:"client_id"`
	CodeChallenge       PKCEChallenge        `json:"code_challenge"`
	CodeChallengeMethod *PKCEChallengeMethod `json:"code_challenge_method,omitempty"`
	RedirectURI         string               `json:"redirect_uri"`
	ResponseType        string               `json:"response_type"`
	Scope               Scope                `json:"scope"`
	State               *string              `json:"state,omitempty"`
}

AuthorizeParams contains all the bound params for the authorize operation

func (AuthorizeParams) Validate

func (p AuthorizeParams) Validate() error

Validate validates the params

type AuthorizeRoute

type AuthorizeRoute func(ctx context.Context, params *AuthorizeParams) api.Responder

AuthorizeRoute is the authorize route handler

func (AuthorizeRoute) Methods

func (AuthorizeRoute) Methods() []string

Methods implements api.Route

func (AuthorizeRoute) Name

func (AuthorizeRoute) Name() string

Name implements api.Route

func (AuthorizeRoute) Path

func (AuthorizeRoute) Path() string

Path implements api.Route

func (AuthorizeRoute) Validate

func (AuthorizeRoute) Validate(params validation.Validatable) error

Validate implements validation.Validatable

type AuthorizerOption

type AuthorizerOption func(a *authorizer)

AuthorizerOption is an authorizer option

func WithPermitQueryBearer

func WithPermitQueryBearer(permit bool) AuthorizerOption

WithPermitQueryBearer allows full bearer tokens to be passed in to the query

func WithPermitQueryToken

func WithPermitQueryToken(permit bool) AuthorizerOption

WithPermitQueryToken allows token ids to be passed in the query supporting persistent tokens

type BearerToken

type BearerToken struct {
	// The token to be used for authorization
	AccessToken string `json:"access_token"`

	// The time from `now` that the token expires
	ExpiresIn int64 `json:"expires_in"`

	// The idenity token contains claims about the users identity. This token is
	// returned if the `openid` scope was granted.
	// If the `profile` scope was granted, this will contain the user profile.
	// These scopes are outside of the context of this library, it is up to the
	// provider to maintain these scopes.
	IdentityToken string `json:"id_token,omitempty"`

	// The refresh token maybe used to generate a new access token so client
	// and user credentials do not have to traverse the wire again.
	// The is provided if the `offline_access` scope is request.
	// This scopes are outside of the context of this library, it is up to the
	RefreshToken *string `json:"refresh_token,omitempty"`

	// The token type, always Bearer
	TokenType string `json:"token_type"`
}

BearerToken BearerTokens are returned by the `/token` method. These token always include an `access_token` which can be used to access api methods from a related service. These are the only objects managed by the api itself. The integration is expected to implement the `oauth.Controller` interface.

func NewBearer

func NewBearer(secret TokenSecret, tokens ...Token) (*BearerToken, error)

NewBearer creates a bearer from the tokens

type Claims

type Claims map[string]interface{}

Claims is generic map of token claims that may represent a jwt

func (Claims) All

func (c Claims) All() map[string]interface{}

All implements the api.Claims interface

func (Claims) Audience

func (c Claims) Audience() string

Audience returns the audience for the token

func (Claims) ClientID

func (c Claims) ClientID() string

ClientID returns the client id for the token

func (Claims) Delete

func (c Claims) Delete(keys ...string) Claims

Delete delete the keys from the claim

func (*Claims) Encode

func (c *Claims) Encode(v interface{}) Claims

Encode encodes the value into a claims object

func (Claims) ExpiresAt

func (c Claims) ExpiresAt() time.Time

ExpiresAt returns the expiration for the token

func (Claims) Get

func (c Claims) Get(key string) interface{}

Get implements the api.Claims interface

func (Claims) ID

func (c Claims) ID() string

ID returns the token id

func (Claims) IssuedAt

func (c Claims) IssuedAt() time.Time

IssuedAt returns the issue time for the token

func (Claims) Merge

func (c Claims) Merge(claims Claims) Claims

Merge merges claims

func (Claims) Scan

func (c Claims) Scan(value interface{}) error

Scan reads a json value from the database into a Map

func (Claims) Scope

func (c Claims) Scope() Scope

Scope returns the scope for the token

func (Claims) Set

func (c Claims) Set(key string, value interface{})

Set implements the api.Claims interface

func (Claims) Sign

func (c Claims) Sign(s TokenSecret) (string, error)

Sign signs the claims using the token

func (Claims) Subject

func (c Claims) Subject() string

Subject returns the subject for the token

func (Claims) Use

func (c Claims) Use() string

Use returns the token use

func (Claims) Valid

func (c Claims) Valid() error

Valid validates the claims

func (Claims) Value

func (c Claims) Value() (driver.Value, error)

Value returns Map as a value that can be stored as json in the database

type Client

type Client interface {
	Principal

	// Type returns the client type
	Type() ClientType

	// TokenSecret returns the client token secret
	TokenSecret() TokenSecret

	// AuthorizedGrants returns the grants this client is authorized to use
	AuthorizedGrants() GrantList

	// ApplicationEndpoints are uris that can be used as valid application flow redirects
	ApplicationEndpoints() []string

	// RedirectEndpoints are uris that can be used as valid authorization flow redirects
	RedirectEndpoints() []string
}

Client is an oauth client interface

type ClientGetInput added in v0.1.2

type ClientGetInput struct {
	Audience     string  `json:"audience"`
	ClientID     string  `json:"client_id"`
	ClientSecret *string `json:"client_secret,omitempty"`
}

ClientGetInput is the input for ClientGet

func (ClientGetInput) Validate added in v0.1.2

func (i ClientGetInput) Validate() error

Validate implements the validation.Validatable interface

type ClientType

type ClientType string

ClientType is an oauth client type

const (
	// ClientTypeWeb defines a web based client type
	// 	Web based clients are restricted from passing client_secret values
	// 	and using password grants
	ClientTypeWeb ClientType = "web"

	// ClientTypeNative defines a native application client type
	ClientTypeNative ClientType = "native"

	// ClientTypeMachine defines a machine to machine client type
	ClientTypeMachine ClientType = "machine"
)

func (ClientType) Validate

func (c ClientType) Validate() error

Validate handles validation for ClientType

type Controller

type Controller interface {
	// AudienceGet returns an audience
	AudienceGet(context.Context, AudienceGetInput) (Audience, error)

	// ClientGet returns a client principal object
	ClientGet(context.Context, ClientGetInput) (Client, error)

	// RequestTokenCreate creates a new authentication request token using the controller
	RequestTokenCreate(context.Context, RequestToken) (string, error)

	// RequestTokenGet looks up a request from the controller
	RequestTokenGet(context.Context, RequestTokenGetInput) (RequestToken, error)

	// RequestTokenDelete deletes a request token
	RequestTokenDelete(context.Context, RequestTokenDeleteInput) error

	// UserCreate creates a user with the audience
	UserCreate(context.Context, UserCreateInput) (User, error)

	// UserGet gets a user principal object
	UserGet(context.Context, UserGetInput) (User, error)

	// UserUpdate updates a user
	UserUpdate(context.Context, UserUpdateInput) (User, error)

	// UserNotify should create an email or sms with the verification link or code for the user
	UserNotify(context.Context, Notification) error

	// TokenCreate creates a new token and allows the controller to add custom claims
	TokenCreate(context.Context, Token) (Token, error)

	// TokenGet gets a token
	TokenGet(context.Context, TokenGetInput) (Token, error)

	// TokenRevoke revokes a token
	TokenRevoke(context.Context, TokenRevokeInput) error

	// TokenCleanup should cleanup all expired and revoked tokens from the stores
	TokenCleanup(ctx context.Context) error
}

Controller defines an oauth controller interface

type ErrTooManyLoginAttempts

type ErrTooManyLoginAttempts struct {
	api.ErrorResponse
	Attempts int
}

ErrTooManyLoginAttempts is returned when too many login attempts have been exceeded

func NewErrTooManyLoginAttempts

func NewErrTooManyLoginAttempts(attempts int) *ErrTooManyLoginAttempts

NewErrTooManyLoginAttempts creates a new too many login attempts error

func (ErrTooManyLoginAttempts) WithError

WithError implements some of api.ErrorResponse interface

type GrantList

type GrantList []GrantType

GrantList is a list of grants

func (GrantList) Contains

func (g GrantList) Contains(value GrantType) bool

Contains return true if the scope contains the value

func (GrantList) Unique

func (g GrantList) Unique() GrantList

Unique returns a scope withonly unique values

type GrantType

type GrantType string

GrantType is an oauth grant type

const (
	// GrantTypeNone is used to filter Authorization parameters
	GrantTypeNone GrantType = "none"

	// GrantTypeAuthCode is the authorization_code grant type
	GrantTypeAuthCode GrantType = "authorization_code"

	// GrantTypeClientCredentials is the client_credentials grant type
	GrantTypeClientCredentials GrantType = "client_credentials"

	// GrantTypePassword is the password grant type
	GrantTypePassword GrantType = "password"

	// GrantTypeRefreshToken is the refresh_token grant type
	GrantTypeRefreshToken GrantType = "refresh_token"
)

func (GrantType) Validate

func (g GrantType) Validate() error

Validate handles validation for GrantType

type ID

type ID interface {
	String() string
}

ID is a simple id interface used to abstract from the controller interfaces

type JWKSInput

type JWKSInput struct {
	Audience string `json:"audience"`
}

JWKSInput is the input for the jwks route

func (JWKSInput) Validate

func (j JWKSInput) Validate() error

Validate validates the JWKSInput struct

type JWKSRoute

type JWKSRoute func(ctx context.Context, params *JWKSInput) api.Responder

JWKSRoute is the jwks route

func (JWKSRoute) Methods

func (JWKSRoute) Methods() []string

Methods implements api.Route

func (JWKSRoute) Name

func (JWKSRoute) Name() string

Name implements api.Route

func (JWKSRoute) Path

func (JWKSRoute) Path() string

Path implements api.Route

type LoginParams

type LoginParams struct {
	Login        string `json:"login"`
	Password     string `json:"password"`
	RequestToken string `json:"request_token"`
	CodeVerifier string `json:"code_verifier"`
}

LoginParams contains all the bound params for the login operation

func (LoginParams) Validate

func (p LoginParams) Validate() error

Validate validates LoginParams

type LoginRoute

type LoginRoute func(ctx context.Context, params *LoginParams) api.Responder

LoginRoute is the login route handler

func (LoginRoute) Methods

func (LoginRoute) Methods() []string

Methods implements api.Route

func (LoginRoute) Name

func (LoginRoute) Name() string

Name implements api.Route

func (LoginRoute) Path

func (LoginRoute) Path() string

Path implements api.Route

type LogoutParams

type LogoutParams struct {
	Audience              string  `json:"audience"`
	ClientID              string  `json:"client_id"`
	RedirectURI           *string `json:"redirect_uri"`
	PostLogoutRedirectURI *string `json:"post_logout_redirect_uri,omitempty"`
	State                 *string `json:"state"`
}

LogoutParams are the params to log a user out

func (LogoutParams) Validate

func (p LogoutParams) Validate() error

Validate validates the params

type LogoutRoute

type LogoutRoute func(ctx context.Context, params *LogoutParams) api.Responder

LogoutRoute is the logout route handler

func (LogoutRoute) Methods

func (LogoutRoute) Methods() []string

Methods implements api.Route

func (LogoutRoute) Name

func (LogoutRoute) Name() string

Name implements api.Route

func (LogoutRoute) Path

func (LogoutRoute) Path() string

Path implements api.Route

type Notification

type Notification interface {
	Audience() string
	Type() NotificationType
	Subject() string
	Channels() []NotificationChannel
	Context() map[string]interface{}
}

Notification is a simply a notification interface

type NotificationChannel

type NotificationChannel string

NotificationChannel is the channel to notify

type NotificationType

type NotificationType string

NotificationType is a notification type

type OIDConfigInput

type OIDConfigInput struct {
	Audience string `json:"audience"`
}

OIDConfigInput is the input for the jwks route

type OpenIDConfigRoute

type OpenIDConfigRoute func(ctx context.Context, params *OIDConfigInput) api.Responder

OpenIDConfigRoute is the openid-configuration route

func (OpenIDConfigRoute) Methods

func (OpenIDConfigRoute) Methods() []string

Methods implements api.Route

func (OpenIDConfigRoute) Name

func (OpenIDConfigRoute) Name() string

Name implements api.Route

func (OpenIDConfigRoute) Path

func (OpenIDConfigRoute) Path() string

Path implements api.Route

type PKCEChallenge

type PKCEChallenge string

PKCEChallenge is a PKCE challenge code

func (PKCEChallenge) Verify

func (c PKCEChallenge) Verify(v string) error

Verify verifies the challenge against the base64 encoded verifier

type PKCEChallengeMethod

type PKCEChallengeMethod string

PKCEChallengeMethod defines a code challenge method

const (
	// PKCEChallengeMethodNone is used to specify no challenge
	PKCEChallengeMethodNone PKCEChallengeMethod = "none"

	// PKCEChallengeMethodS256 is a sha-256 code challenge method
	PKCEChallengeMethodS256 PKCEChallengeMethod = "S256"
)

func (PKCEChallengeMethod) String

func (c PKCEChallengeMethod) String() string

func (PKCEChallengeMethod) Validate

func (c PKCEChallengeMethod) Validate() error

Validate validates the CodeChallengeMethod

type PasswordCreateParams

type PasswordCreateParams struct {
	Login        string                `json:"login"`
	Notify       []NotificationChannel `json:"notify"`
	Type         PasswordType          `json:"type"`
	RequestToken string                `json:"request_token"`
	RedirectURI  string                `json:"redirect_uri"`
	CodeVerifier string                `json:"code_verifier"`
}

PasswordCreateParams is the input to the password get route

func (PasswordCreateParams) Validate

func (p PasswordCreateParams) Validate() error

Validate validates PasswordGetInput

type PasswordCreateRoute

type PasswordCreateRoute func(ctx context.Context, params *PasswordCreateParams) api.Responder

PasswordCreateRoute is the password create handler

func (PasswordCreateRoute) Methods

func (PasswordCreateRoute) Methods() []string

Methods implements api.Route

func (PasswordCreateRoute) Name

func (PasswordCreateRoute) Name() string

Name implements api.Route

func (PasswordCreateRoute) Path

func (PasswordCreateRoute) Path() string

Path implements api.Route

type PasswordNotification

type PasswordNotification interface {
	Notification
	PasswordType() PasswordType
	Code() string
}

PasswordNotification is a password notification interface

type PasswordType

type PasswordType string

PasswordType defines a password type

const (
	// PasswordTypeLink is a magic password link
	PasswordTypeLink PasswordType = "link"

	// PasswordTypeCode is a one-time use password code
	PasswordTypeCode PasswordType = "code"

	// PasswordTypeReset sends both a link with the password scope and a code
	PasswordTypeReset PasswordType = "reset"
)
func (p PasswordType) IsLink() bool

IsLink returns true if its a link type

func (PasswordType) String

func (p PasswordType) String() string

func (PasswordType) Validate

func (p PasswordType) Validate() error

Validate validates the PasswordType

type PasswordUpdateParams

type PasswordUpdateParams struct {
	Password    string  `json:"password"`
	ResetToken  string  `json:"reset_token"`
	RedirectURI *string `json:"redirect_uri,omitempty"`
}

PasswordUpdateParams are used by the password update route

func (PasswordUpdateParams) Validate

func (p PasswordUpdateParams) Validate() error

Validate validates PasswordGetInput

type PasswordUpdateRoute

type PasswordUpdateRoute func(ctx context.Context, params *PasswordUpdateParams) api.Responder

PasswordUpdateRoute is the password update handler

func (PasswordUpdateRoute) Methods

func (PasswordUpdateRoute) Methods() []string

Methods implements api.Route

func (PasswordUpdateRoute) Name

func (PasswordUpdateRoute) Name() string

Name implements api.Route

func (PasswordUpdateRoute) Path

func (PasswordUpdateRoute) Path() string

Path implements api.Route

func (PasswordUpdateRoute) RequireAuth

func (PasswordUpdateRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (PasswordUpdateRoute) Scopes

func (PasswordUpdateRoute) Scopes() ScopeList

Scopes implements oauth.Route

type Principal added in v0.1.2

type Principal interface {
	// ID returns the principal identifier
	ID() string

	//  Audience is the audience for the principal
	Audience() string

	// Scope returns the scope for the oauth Principal
	Permissions() Scope
}

Principal is the oauth principal

type RequestToken

type RequestToken struct {
	ID                  ID
	Type                RequestTokenType
	CreatedAt           int64
	Audience            string
	ClientID            string
	Subject             *string
	Passcode            *string
	Uses                int
	Scope               Scope
	ExpiresAt           int64
	CodeChallenge       PKCEChallenge
	CodeChallengeMethod PKCEChallengeMethod
	AppURI              *string
	RedirectURI         *string
	State               *string
}

RequestToken represents an oauth request used for several different flows These tokens are generally single use and should not be exposed, other than their id

func (RequestToken) Expired added in v0.1.2

func (r RequestToken) Expired() bool

Expired returns true if the token is expired

func (RequestToken) Validate

func (r RequestToken) Validate() error

Validate validates the Request

type RequestTokenDeleteInput added in v0.1.2

type RequestTokenDeleteInput struct {
	TokenID string `json:"token_id"`
}

RequestTokenDeleteInput is the input for RequestTokenDelete

func (RequestTokenDeleteInput) Validate added in v0.1.2

func (i RequestTokenDeleteInput) Validate() error

Validate implements the validation.Validatable interface

type RequestTokenGetInput added in v0.1.2

type RequestTokenGetInput struct {
	TokenID   string            `json:"token_id"`
	TokenType *RequestTokenType `json:"token_type"`
}

RequestTokenGetInput is the input for RequestTokenGet

func (RequestTokenGetInput) Validate added in v0.1.2

func (i RequestTokenGetInput) Validate() error

Validate implements the validation.Validatable interface

type RequestTokenType

type RequestTokenType string

RequestTokenType is the request token type

const (
	// RequestTokenTypeLogin is used for login or signup routes
	RequestTokenTypeLogin RequestTokenType = "login"

	// RequestTokenTypeSession is used for sessions
	RequestTokenTypeSession RequestTokenType = "session"

	// RequestTokenTypeVerify is verification, i.e. password resets
	RequestTokenTypeVerify RequestTokenType = "verify"

	// RequestTokenTypeInvite is used to invite users to the platform
	RequestTokenTypeInvite RequestTokenType = "invite"

	// RequestTokenTypeAuthCode is used to request token
	RequestTokenTypeAuthCode RequestTokenType = "auth_code"

	// RequestTokenTypeRefreshToken is used to request refresh token
	RequestTokenTypeRefreshToken RequestTokenType = "refresh_token"
)

func RequestTokenTypePtr added in v0.1.2

func RequestTokenTypePtr(t RequestTokenType) *RequestTokenType

func (RequestTokenType) Validate added in v0.1.2

func (t RequestTokenType) Validate() error

type Route

type Route interface {
	api.AuthorizedRoute
	Scopes() ScopeList
}

Route defines an oauth route that has a scope

type Scope

type Scope []string

Scope is an oauth scope

func (Scope) Append

func (s Scope) Append(e ...string) Scope

Append appends to a scope

func (Scope) Contains

func (s Scope) Contains(value string) bool

Contains return true if the scope contains the value

func (Scope) Every

func (s Scope) Every(elements ...string) bool

Every returns true if every element is contained in the scope

func (Scope) MarshalJSON

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

MarshalJSON handles json marshaling of this type

func (*Scope) Scan

func (s *Scope) Scan(value interface{}) error

Scan reads a json value from the database into a Permissions

func (Scope) Some

func (s Scope) Some(elements ...string) bool

Some returns true if at least one of the elements is contained in the scope

func (*Scope) String added in v0.1.1

func (s *Scope) String() string

func (Scope) Unique

func (s Scope) Unique() Scope

Unique returns a scope with only unique values

func (*Scope) UnmarshalText

func (s *Scope) UnmarshalText(v []byte) error

UnmarshalText handles text unmarshaling

func (Scope) Value

func (s Scope) Value() (driver.Value, error)

Value returns Permissions as a value that can be stored as json in the database

func (Scope) Without

func (s Scope) Without(elements ...string) Scope

Without returns the scope excluding the elements

type ScopeList

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

ScopeList is used to build scopes

func BuildScope

func BuildScope(scopes ...string) ScopeList

BuildScope returns a []Scope from the string scope values

func (ScopeList) And

func (s ScopeList) And(scopes ...string) ScopeList

And appends the scopes to the tail Scope on the list

func (ScopeList) Check added in v0.1.1

func (s ScopeList) Check(scope Scope) bool

func (ScopeList) Every

func (s ScopeList) Every(scopes ...string) bool

Every checks if any of the scopes in the list have all of the scopes

func (ScopeList) Or

func (s ScopeList) Or(scopes ...string) ScopeList

Or adds an or to the list

func (ScopeList) Some

func (s ScopeList) Some(scopes ...string) bool

Some checks if any of the scopes in the list have any of the scopes

func (ScopeList) String added in v0.1.1

func (s ScopeList) String() string

type SessionParams

type SessionParams struct {
	RequestToken string  `json:"request_token"`
	RedirectURI  *string `json:"redirect_uri,omitempty"`
	State        *string `json:"state,omitempty"`
}

SessionParams is the session request parameters

func (SessionParams) Validate

func (p SessionParams) Validate() error

Validate validates the SessionParams struct

type SessionRoute

type SessionRoute func(ctx context.Context, params *SessionParams) api.Responder

SessionRoute is the session handler

func (SessionRoute) Methods

func (SessionRoute) Methods() []string

Methods implements api.Route

func (SessionRoute) Name

func (SessionRoute) Name() string

Name implements api.Route

func (SessionRoute) Path

func (SessionRoute) Path() string

Path implements api.Route

func (SessionRoute) RequireAuth

func (SessionRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (SessionRoute) Scopes

func (SessionRoute) Scopes() ScopeList

Scopes implements oauth.Route

type SignupParams

type SignupParams struct {
	Login        string          `json:"login"`
	Password     *string         `json:"password,omitempty"`
	InviteToken  *string         `json:"invite_token,omitempty"`
	RequestToken string          `json:"request_token"`
	CodeVerifier string          `json:"code_verifier"`
	Profile      *openid.Profile `json:"profile,omitempty"`
}

SignupParams are used in the signup route

func (SignupParams) Validate

func (p SignupParams) Validate() error

Validate validates SignupParams

type SignupRoute

type SignupRoute func(ctx context.Context, params *SignupParams) api.Responder

SignupRoute is the signup handler

func (SignupRoute) Methods

func (SignupRoute) Methods() []string

Methods implements api.Route

func (SignupRoute) Name

func (SignupRoute) Name() string

Name implements api.Route

func (SignupRoute) Path

func (SignupRoute) Path() string

Path implements api.Route

type SpecGetInput

type SpecGetInput struct {
	Format string `json:"format"`
	Pretty bool   `json:"pretty"`
}

SpecGetInput is the input for spec get method

type SpecRoute

type SpecRoute func(ctx context.Context, params *SpecGetInput) api.Responder

SpecRoute is the swagger spec route handler

func (SpecRoute) Methods

func (SpecRoute) Methods() []string

Methods implements api.Route

func (SpecRoute) Name

func (SpecRoute) Name() string

Name implements api.Route

func (SpecRoute) Path

func (SpecRoute) Path() string

Path implements api.Route

type Token

type Token struct {
	ID         string   `json:"jti,omitempty"`
	Issuer     *string  `json:"iss,omitempty"`
	Subject    *string  `json:"sub,omitempty"`
	Audience   string   `json:"aud,omitempty"`
	ClientID   string   `json:"azp,omitempty"`
	Use        TokenUse `json:"use,omitempty"`
	AuthTime   int64    `json:"auth_time,omitempty"`
	Scope      Scope    `json:"scope,omitempty"`
	IssuedAt   int64    `json:"iat,omitempty"`
	ExpiresAt  *int64   `json:"exp,omitempty"`
	Revokable  bool     `json:"-"`
	Persistent bool     `json:"-"`
	RevokedAt  *int64   `json:"-"`
	Claims     Claims   `json:"-"`
	Bearer     *string  `json:"-"`
}

Token represents a revokable set of claims

func NewToken

func NewToken(use TokenUse) Token

NewToken intializes a token of use type

func ParseBearer

func ParseBearer(bearer string, keyFn func(kid string, c Claims) (TokenSecret, error)) (Token, error)

ParseBearer parses the jwt token into claims

func TokenFromClaims

func TokenFromClaims(c Claims) (Token, error)

TokenFromClaims parse the claims into a Token

func (Token) AuthClaims

func (t Token) AuthClaims() api.Claims

AuthClaims implements the api.Principal interface

func (Token) CredentialType

func (t Token) CredentialType() api.CredentialType

CredentialType implements the api.Principal interface

func (Token) Credentials

func (t Token) Credentials() string

Credentials implements the api.Principal interface

func (Token) Expired added in v0.1.2

func (t Token) Expired() bool

Expired returns true of the token expires and is expired

func (Token) Sign

func (t Token) Sign(s TokenSecret) (string, error)

Sign generates an encoded and sign token using the secret

func (Token) Type

func (t Token) Type() api.PrincipalType

Type implements the api.Principal interface

func (Token) Validate

func (t Token) Validate() error

Validate validates the token

type TokenAlgorithm

type TokenAlgorithm string

TokenAlgorithm is a token algorithm type

const (
	// TokenLifetimeMinimum is the minimum token lifetime
	TokenLifetimeMinimum = time.Minute

	// TokenAlgorithmRS256 is the RSA 256 token algorithm
	TokenAlgorithmRS256 TokenAlgorithm = "RS256"

	// TokenAlgorithmHS256 is the HMAC with SHA-256 token algorithm
	TokenAlgorithmHS256 TokenAlgorithm = "HS256"

	// TokenAlgorithmNone is used for updating other parameters
	TokenAlgorithmNone TokenAlgorithm = ""
)

func (TokenAlgorithm) Ptr

func (a TokenAlgorithm) Ptr() *TokenAlgorithm

Ptr returns a pointer to the algorithm

func (TokenAlgorithm) String

func (a TokenAlgorithm) String() string

func (TokenAlgorithm) Validate

func (a TokenAlgorithm) Validate() error

Validate handles validation for TokenAlgorithm types

type TokenGetInput added in v0.1.2

type TokenGetInput struct {
	TokenID  string    `json:"token_id"`
	TokenUse *TokenUse `json:"token_use,omitempty"`
}

TokenGetInput is the input to TokenGet

func (TokenGetInput) Validate added in v0.1.2

func (i TokenGetInput) Validate() error

Validate implements the validation.Validatable interface

type TokenIntrospectParams

type TokenIntrospectParams struct {
	Token string `json:"token"`
}

TokenIntrospectParams is the parameters for token introspect

func (TokenIntrospectParams) Validate

func (p TokenIntrospectParams) Validate() error

Validate handles the validation for the TokenParams struct

type TokenIntrospectRoute

type TokenIntrospectRoute func(ctx context.Context, params *TokenIntrospectParams) api.Responder

TokenIntrospectRoute is the openid token introspection route

func (TokenIntrospectRoute) Methods

func (TokenIntrospectRoute) Methods() []string

Methods implements api.Route

func (TokenIntrospectRoute) Name

Name implements api.Route

func (TokenIntrospectRoute) Path

Path implements api.Route

func (TokenIntrospectRoute) RequireAuth

func (TokenIntrospectRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (TokenIntrospectRoute) Scopes

Scopes implements oauth.Route

type TokenParams

type TokenParams struct {
	ClientID     string    `json:"client_id"`
	Audience     string    `json:"audience,omitempty"`
	ClientSecret *string   `json:"client_secret"`
	GrantType    GrantType `json:"grant_type"`
	Code         *string   `json:"code,omitempty"`
	RefreshToken *string   `json:"refresh_token,omitempty"`
	Scope        Scope     `json:"scope,omitempty"`
	RedirectURI  *string   `json:"redirect_uri,omitempty"`
	CodeVerifier *string   `json:"code_verifier,omitempty"`
}

TokenParams is the parameters for the token request

func (TokenParams) Validate

func (p TokenParams) Validate() error

Validate handles the validation for the TokenParams struct

type TokenRevokeInput added in v0.1.2

type TokenRevokeInput struct {
	TokenID  *string   `json:"token_id,omitempty"`
	Subject  *string   `json:"subject,omitempty"`
	TokenUse *TokenUse `json:"token_use,omitempty"`
}

TokenRevokeInput is the input to TokenRevoke

func (TokenRevokeInput) Validate added in v0.1.2

func (i TokenRevokeInput) Validate() error

Validate implements the validation.Validatable interface

type TokenRevokeParams

type TokenRevokeParams struct {
	Token string `json:"token"`
}

TokenRevokeParams is the parameters for token revoke

func (TokenRevokeParams) Validate

func (p TokenRevokeParams) Validate() error

Validate handles the validation for the TokenParams struct

type TokenRevokeRoute

type TokenRevokeRoute func(ctx context.Context, params *TokenRevokeParams) api.Responder

TokenRevokeRoute is the openid token revoke route

func (TokenRevokeRoute) Methods

func (TokenRevokeRoute) Methods() []string

Methods implements api.Route

func (TokenRevokeRoute) Name

func (TokenRevokeRoute) Name() string

Name implements api.Route

func (TokenRevokeRoute) Path

func (TokenRevokeRoute) Path() string

Path implements api.Route

func (TokenRevokeRoute) RequireAuth

func (TokenRevokeRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (TokenRevokeRoute) Scopes

func (TokenRevokeRoute) Scopes() ScopeList

Scopes implements oauth.Route

type TokenRoute

type TokenRoute func(ctx context.Context, params *TokenParams) api.Responder

TokenRoute is the token route

func (TokenRoute) Methods

func (TokenRoute) Methods() []string

Methods implements api.Route

func (TokenRoute) Name

func (TokenRoute) Name() string

Name implements api.Route

func (TokenRoute) Path

func (TokenRoute) Path() string

Path implements api.Route

type TokenSecret

type TokenSecret interface {
	ID() string
	Algorithm() TokenAlgorithm
	Key() interface{}
	VerifyKey() interface{}
	ExpiresAt() *time.Time
}

TokenSecret is a token secret interface

type TokenUse

type TokenUse string

TokenUse defines token usage

const (
	// TokenUseAccess is a token to be used for access
	TokenUseAccess TokenUse = "access"

	// TokenUseIdentity is a token to be used for identity
	TokenUseIdentity TokenUse = "identity"

	// TokenUseVerify is a token to be used for verification purposes
	TokenUseVerify TokenUse = "verify"
)

func (TokenUse) Ptr added in v0.1.2

func (u TokenUse) Ptr() *TokenUse

Ptr returns a pointer to the use

func (TokenUse) Validate added in v0.1.2

func (u TokenUse) Validate() error

Validate implements validation.Validatable interface

type User

type User interface {
	Principal

	// Profile returns the users openid profile claims, filtering on the provided scope
	Profile() *openid.Profile
}

User is an oauth user interface

type UserCreateInput added in v0.1.2

type UserCreateInput struct {
	Audience string          `json:"audience"`
	Login    string          `json:"login"`
	Password *string         `json:"password,omitempty"`
	Profile  *openid.Profile `json:"profile,omitempty"`
	Invite   *RequestToken   `json:"invite,omitempty"`
}

UserCreateInput is the input to UserCreate

func (UserCreateInput) Validate added in v0.1.2

func (i UserCreateInput) Validate() error

Validate implements the validation.Validatable interface

type UserGetInput added in v0.1.2

type UserGetInput struct {
	Audience string  `json:"audience"`
	Login    *string `json:"login,omitempty"`
	Subject  *string `json:"subject,omitempty"`
	Password *string `json:"password,omitempty"`
}

UserGetInput is the input for UserGet

func (UserGetInput) Validate added in v0.1.2

func (i UserGetInput) Validate() error

Validate implements the validation.Validatable interface

type UserInfoParams

type UserInfoParams struct{}

UserInfoParams are the params for user info

func (UserInfoParams) Validate

func (p UserInfoParams) Validate() error

Validate validates the params

type UserInfoRoute

type UserInfoRoute func(ctx context.Context, params *UserInfoParams) api.Responder

UserInfoRoute is the user info route

func (UserInfoRoute) Methods

func (UserInfoRoute) Methods() []string

Methods implements api.Route

func (UserInfoRoute) Name

func (UserInfoRoute) Name() string

Name implements api.Route

func (UserInfoRoute) Path

func (UserInfoRoute) Path() string

Path implements api.Route

func (UserInfoRoute) RequireAuth

func (UserInfoRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (UserInfoRoute) Scopes

func (UserInfoRoute) Scopes() ScopeList

Scopes implements oauth.Route

type UserInfoUpdateParams

type UserInfoUpdateParams struct {
	*openid.Profile
}

UserInfoUpdateParams are the params to update the user profile

func (UserInfoUpdateParams) Validate

func (p UserInfoUpdateParams) Validate() error

Validate validates the params

type UserInfoUpdateRoute

type UserInfoUpdateRoute func(ctx context.Context, params *UserInfoUpdateParams) api.Responder

UserInfoUpdateRoute is the user info update route

func (UserInfoUpdateRoute) Methods

func (UserInfoUpdateRoute) Methods() []string

Methods implements api.Route

func (UserInfoUpdateRoute) Name

func (UserInfoUpdateRoute) Name() string

Name implements api.Route

func (UserInfoUpdateRoute) Path

func (UserInfoUpdateRoute) Path() string

Path implements api.Route

func (UserInfoUpdateRoute) RequireAuth

func (UserInfoUpdateRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (UserInfoUpdateRoute) Scopes

func (UserInfoUpdateRoute) Scopes() ScopeList

Scopes implements oauth.Route

type UserUpdateInput added in v0.1.2

type UserUpdateInput struct {
	Audience  string          `json:"audience"`
	Login     *string         `json:"login,omitempty"`
	Subject   *string         `json:"subject,omitempty"`
	Password  *string         `json:"password,omitempty"`
	Profile   *openid.Profile `json:"profile,omitempty"`
	Lockout   *bool           `json:"lockout,omitempty"`
	LockUntil *time.Time      `json:"lock_until,omitempty"`
}

UserUpdateInput is the input to UserUpdate

func (UserUpdateInput) Validate added in v0.1.2

func (i UserUpdateInput) Validate() error

Validate implements the validation.Validatable interface

type VerificationNotification

type VerificationNotification interface {
	Notification
}

VerificationNotification is a user verification notification

type VerifyParams

type VerifyParams struct {
	RedirectURI string  `json:"redirect_uri"`
	State       *string `json:"state,omitempty"`
}

VerifyParams are the params for user verify

func (VerifyParams) Validate

func (p VerifyParams) Validate() error

Validate validates the params

type VerifyRoute

type VerifyRoute func(ctx context.Context, params *VerifyParams) api.Responder

VerifyRoute is the verify route

func (VerifyRoute) Methods

func (VerifyRoute) Methods() []string

Methods implements api.Route

func (VerifyRoute) Name

func (VerifyRoute) Name() string

Name implements api.Route

func (VerifyRoute) Path

func (VerifyRoute) Path() string

Path implements api.Route

func (VerifyRoute) RequireAuth

func (VerifyRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (VerifyRoute) Scopes

func (VerifyRoute) Scopes() ScopeList

Scopes implements oauth.Route

type VerifySendParams

type VerifySendParams struct {
	Method NotificationChannel `json:"method"`
}

VerifySendParams are the params for the verification send method

func (VerifySendParams) Validate

func (p VerifySendParams) Validate() error

Validate validates the params

type VerifySendRoute

type VerifySendRoute func(ctx context.Context, params *VerifySendParams) api.Responder

VerifySendRoute is the verify send route

func (VerifySendRoute) Methods

func (VerifySendRoute) Methods() []string

Methods implements api.Route

func (VerifySendRoute) Name

func (VerifySendRoute) Name() string

Name implements api.Route

func (VerifySendRoute) Path

func (VerifySendRoute) Path() string

Path implements api.Route

func (VerifySendRoute) RequireAuth

func (VerifySendRoute) RequireAuth() []api.CredentialType

RequireAuth implements the api.AuthorizedRoute

func (VerifySendRoute) Scopes

func (VerifySendRoute) Scopes() ScopeList

Scopes implements oauth.Route

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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