Documentation
¶
Overview ¶
Package oauth2 provides an implementation of OAuth2 server-related logic, including the registration and retrieval of clients, authorization codes, device codes, tokens, and consent handling.
Index ¶
- Constants
- Variables
- func AllowPolicies(policies ...Policy) context.Handler
- func AllowScopes(requiredScopes ...string) context.Handler
- func ClientTokenSignOptions(clientID string, maxAge int) []jwt.SignOption
- func DisallowPolicies(policies ...Policy) context.Handler
- func DisallowScopes(disallowedScopes ...string) context.Handler
- func GenerateSharedKey() (string, error)
- func JoinScopes(scopes ...string) string
- func PolicyScopes(policies ...Policy) []string
- func SplitScopes(scope string) []string
- type AuthCode
- type AuthCodeStore
- type AuthUserData
- type AuthorizeRequest
- type Client
- type ClientFilter
- type ClientRegistration
- type ClientStore
- type ClientTokenClaims
- type ConfirmConsentRequest
- type DeviceCode
- type DeviceCodeStore
- type Option
- func WithAuthCodeStore(authCodeStore AuthCodeStore) Option
- func WithClientStore(clientStore ClientStore) Option
- func WithConsentPageURL(consentPageURL string) Option
- func WithDeviceCodeStore(deviceCodeStore DeviceCodeStore) Option
- func WithDeviceInterval(intervalSeconds int) Option
- func WithLoginPageURL(loginPageURL string) Option
- type Policy
- type PostgresConn
- type ResourcePolicy
- type ScopePolicy
- type Server
- func (s *Server[UserData]) AuthorizeHandler() context.Handler
- func (s *Server[UserData]) ClientStore() ClientStore
- func (s *Server[UserData]) ClientVerifier() auth.VerifyUserFunc[ClientTokenClaims]
- func (s *Server[UserData]) ConfirmConsentHandler() context.Handler
- func (s *Server[UserData]) CreateClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)
- func (s *Server[UserData]) DefaultConsentPageHandler() context.Handler
- func (s *Server[UserData]) DeviceCodeHandler() context.Handler
- func (s *Server[UserData]) EnsureClientScopes(ctx stdContext.Context, client *Client, scopes []string) (bool, error)
- func (s *Server[UserData]) RegisterClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)
- func (s *Server[UserData]) RevokeConsentHandler() context.Handler
- func (s *Server[UserData]) Routing(r router.Router)
- func (s *Server[UserData]) SignToken(clientID string, accessMaxAge, refreshMaxAge int, claims ...any) (*oauth2.Token, error)
- func (s *Server[UserData]) TokenHandler() context.Handler
- func (s *Server[UserData]) TokenIntrospectHandler() context.Handler
- type Token
Constants ¶
const ( // DecisionApprove indicates the user approved the requested scopes. DecisionApprove = "approve" // DecisionDeny indicates the user denied the requested scopes. DecisionDeny = "deny" )
const ( // GrantTypeAuthorizationCode is the default grant type. // It's used when the client has an authorization code. GrantTypeAuthorizationCode = "authorization_code" // the default one. // GrantTypeDeviceCode is used when the client has a device code. GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code" // GrantTypePassword is used when the client has a username and password. GrantTypePassword = "password" // GrantTypeRefreshToken is used when the client wants to refresh the token. GrantTypeRefreshToken = "refresh_token" )
const MaxAgeAccessToken = -1
Variables ¶
var ( // ErrClientNotFound is returned when the client is not found in the client store. ErrClientNotFound = fmt.Errorf("oauth2: client not found") // ErrClientAlreadyExists is returned by CreateClient when a client with the same name exists. ErrClientAlreadyExists = errors.New("oauth2: client already exists") // ErrClientMissing is returned when the client id and client secret are missing from the token. ErrClientMissing = errors.New("client id and client secret are required") // ErrClientMismatch is returned when the client's secret or version does not match // the stored client, or when the client_id claim does not match the token's audience. ErrClientMismatch = fmt.Errorf("client_id or secret or version mismatch") )
var ( // ErrClientTokenMissing is returned when the token does not contain any oauth2 client claims. ErrClientTokenMissing = fmt.Errorf("client token claims: %w", jwt.ErrMissing) // ErrClientInsufficientScopes is returned when the client does not have the required scopes. ErrClientInsufficientScopes = fmt.Errorf("client has insufficient scopes") )
var Clock = jwt.Clock
Clock returns the current server's time. By default it returns the time.Now(). It can be overridden to return other time value.
Usage: now := Clock()
var ErrInvalidClientFilter = errors.New("oauth2: invalid client filter")
ErrInvalidClientFilter is returned by ListClients and CountClients when the filter is not valid, for example an unknown Sort field.
Functions ¶
func AllowPolicies ¶
AllowPolicies returns a middleware that validates an OAuth2 client's access token for a given resource (and action). E.g. "users:read" (as ResourcePolicy{"users", "read"}), "users:*" or even "users".
Storing Policy-Like Scopes on the OAuth2 Client When registering a client, you can define resource-based scopes, e.g.:
client, err := oauth2Server.RegisterClient(ctx, oauth2.ClientRegistration{
Name: "ExampleClient",
Website: "https://example.com",
LogoURL: "https://example.com/logo.png",
RedirectURI: "https://localhost:8081/callback",
VerificationURI: "...device_verification...",
GrantTypes: []string{"authorization_code", "refresh_token"},
Scopes: []string{"users:read", "users:write", "orders:read", "orders:write"}, // resource-based scopes
CodeMaxAge: 3600,
AccessMaxAge: 3600,
RefreshMaxAge: 604800,
})
Usage:
app.Post("/",
AuthInstance.VerifyHandler(),
oauth2.AllowPolicies(oauth2.ResourcePolicy{Resource: "users", Action: "write"}),
createUserHandler)
func AllowScopes ¶
AllowScopes returns a middleware that validates an OAuth2 client's access token. If the token is invalid or the client does not exist, the request is halted.
This middleware handles two scenarios:
- Direct application sign-in: The token does not carry OAuth2 client data, so all resources are accessible without scope checks.
- OAuth2 client sign-in: The token embeds the client_id and scopes, which are validated to ensure the client has the necessary permissions.
Usage:
admin := app.Router("/admin", AuthInstance.VerifyHandler(), oauth2.AllowScopes("users:read", "users:write"))
admin.Get("/restricted", mainHandler)
func ClientTokenSignOptions ¶
func ClientTokenSignOptions(clientID string, maxAge int) []jwt.SignOption
ClientTokenSignOptions returns the signing options for the client token.
func DisallowPolicies ¶
DisallowPolicies returns a middleware that ensures an OAuth2 client's access token does not contain any of the specified resource policies. If the token contains any of the disallowed policies, the request is halted.
func DisallowScopes ¶
DisallowScopes returns a middleware that ensures an OAuth2 client's access token does not contain any of the specified scopes. If the token contains any of the disallowed scopes, the request is halted.
func GenerateSharedKey ¶
GenerateSharedKey returns a base64-encoded (standard encoding) random 16-byte key (128-bit AES key). This is convenient for returning as JSON in an HTTP response.
func JoinScopes ¶
JoinScopes joins multiple scopes into a space-separated string.
func PolicyScopes ¶
PolicyScopes converts the given policies to scopes for app clients to be registered with.
func SplitScopes ¶
SplitScopes splits a space-separated scope string into a slice.
Types ¶
type AuthCode ¶
type AuthCode struct {
// Code is the short-lived authorization code string.
Code string `pg:"type=varchar(128),primary" json:"code"`
// CreatedAt is the timestamp of code creation.
CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
// UpdatedAt is the timestamp of last code update.
UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`
// ExpiresAt is the time when the code becomes invalid.
ExpiresAt types.ISO8601 `pg:"type=timestamp" json:"expires_at"`
// ClientID refers to the client that requested the code.
ClientID string `pg:"type=uuid,ref=oauth2_clients(id cascade),index" json:"client_id"`
// UserData contains data about the authenticated user.
UserData AuthUserData `pg:"type=jsonb" json:"user_data"`
// State is an optional value for client tracking.
State string `pg:"type=varchar(128)" json:"state"`
// Scopes lists the permissions granted by the user.
Scopes []string `pg:"type=varchar[]" json:"scopes"`
// CodeChallenge is the PKCE S256 challenge, empty when the client did not send one.
CodeChallenge string `json:"code_challenge,omitempty"`
// CodeChallengeMethod is "S256" when CodeChallenge is set.
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
}
AuthCode holds the data for an OAuth2 authorization code.
func NewAuthCode ¶
func NewAuthCode(clientID string, userData AuthUserData, state string, scopes []string, maxAge int) (*AuthCode, error)
NewAuthCode creates a new authorization code instance.
func (*AuthCode) HasExpired ¶
HasExpired checks if this authorization code is expired.
type AuthCodeStore ¶
type AuthCodeStore interface {
// InsertAuthCode saves a new authorization code into the store.
InsertAuthCode(ctx context.Context, authCode *AuthCode) error
// GetAndDeleteAuthCode retrieves and deletes the code from the store in one step.
GetAndDeleteAuthCode(ctx context.Context, code string) (*AuthCode, bool, error)
}
AuthCodeStore describes the actions needed for storing and retrieving OAuth2 authorization codes.
func NewMemoryAuthCodeStore ¶
func NewMemoryAuthCodeStore() AuthCodeStore
NewMemoryAuthCodeStore returns an AuthCodeStore backed by an in-memory cache.
func NewPostgresAuthCodeStore ¶
func NewPostgresAuthCodeStore(clientsTableName, tableName string, conn PostgresConn) AuthCodeStore
NewPostgresAuthCodeStore creates a new instance of postgresAuthCodeStore using the specified clientsTableName, auth code tableName, and a PostgresConn connection. It ensures the table structure exists on initialization and returns an AuthCodeStore implementation for managing OAuth2 authorization codes.
type AuthUserData ¶
AuthUserData is the user data that is associated with the auth code. It can be any custom data type.
type AuthorizeRequest ¶
type AuthorizeRequest struct {
// ClientID is the unique client identifier.
ClientID string `json:"client_id" url:"client_id" form:"client_id"`
// State is an optional opaque value for client tracking.
State string `json:"state" url:"state" form:"state"`
// Scope is the set of requested scopes, space-separated.
Scope string `json:"scope" url:"scope" form:"scope"`
// CodeChallenge is the optional PKCE challenge. When set, the method must be S256.
CodeChallenge string `json:"code_challenge,omitempty" url:"code_challenge,omitempty" form:"code_challenge,omitempty"`
// CodeChallengeMethod is the PKCE method. Only S256 is accepted.
CodeChallengeMethod string `json:"code_challenge_method,omitempty" url:"code_challenge_method,omitempty" form:"code_challenge_method,omitempty"`
}
AuthorizeRequest holds the data submitted during authorization.
func (*AuthorizeRequest) ConsentCookieName ¶
func (req *AuthorizeRequest) ConsentCookieName() string
ConsentCookieName returns a cookie name specific to the client ID.
func (*AuthorizeRequest) Scopes ¶
func (req *AuthorizeRequest) Scopes() []string
Scopes parses and returns the requested scopes.
type Client ¶
type Client struct {
// ID is the unique identifier for the client.
ID string `pg:"type=uuid,primary" json:"id,omitempty"`
// CreatedAt is the timestamp when the client was created.
CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
// UpdatedAt is the timestamp of the last update to the client.
UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`
// Name is the name of the client application.
Name string `pg:"type=varchar(255),unique" json:"name"`
// Website is the website URL of the client application.
Website string `pg:"type=varchar(255)" json:"website"`
// LogoURL is the URL of the client's logo.
LogoURL string `pg:"type=varchar(255)" json:"logo_url"`
// RedirectURI is the callback URL for the client.
RedirectURI string `pg:"type=text" json:"redirect_uri"`
// VerificationURI is the URL where the user should enter the user code.
VerificationURI string `pg:"type=text,default=''" json:"verification_uri"`
// Secret is the randomly generated secret of the client,
// stored as-is (plaintext, it is neither encrypted nor hashed).
// Client send it to the server to authenticate itself on every request,
// server matches it with the stored secret to verify the client.
Secret string `pg:"type=varchar(255)" json:"secret,omitempty"`
// GrantTypes are the allowed grant types for the client.
// If empty then no grant type is allowed;
// NewClient fills it in automatically when it is not provided.
GrantTypes []string `pg:"type=varchar[]" json:"grant_types"`
// Scopes are the allowed scopes for the client.
// It checks if the requested scopes are allowed by the client,
// and passes only what is defined in the request to the actual generated token,
// so the end-server knows what the client is allowed to do.
Scopes []string `pg:"type=varchar[]" json:"scopes"`
// CodeMaxAge is the maximum age for the codes, in seconds.
// Defaults to 1 hour (3600 seconds).
CodeMaxAge int `pg:"type=int,default=3600" json:"code_max_age"`
// AccessMaxAge is the max age for the access tokens, in seconds. Defaults to 1 hour.
AccessMaxAge int `pg:"type=int,default=3600" json:"access_max_age"`
// RefreshMaxAge is the max age for the refresh tokens, in seconds. Defaults to 7 days.
RefreshMaxAge int `pg:"type=int,default=604800" json:"refresh_max_age"`
// Version is the version of the client. It is used as an extra claim.
// In order to invalidate all tokens created by this client just upgrade the version.
Version int `pg:"type=smallint,default=0" json:"version"`
}
Client represents a client application that is registered to the server. The client is the application that wants to access the user's data.
If the client is a - web application then the client is the web application itself. - mobile application then the client is the mobile application itself. - server-side application then the client is the server-side application itself.
Note that if custom ownership is required then end-developer can create a separate store/table to store the owner id and the client id from this store/table.
func NewClient ¶
func NewClient(reg ClientRegistration) (*Client, error)
NewClient creates and returns a new client from reg. The client's ID and secret are generated automatically. See ClientRegistration for the required fields, the defaults and the validation.
func (*Client) AccessTokenOptions ¶
func (c *Client) AccessTokenOptions() jwt.SignOption
AccessTokenOptions returns the signing option for the access token.
func (*Client) Claims ¶
func (c *Client) Claims(scopes []string) ClientTokenClaims
Claims returns the client's token claims.
func (*Client) MatchGrantType ¶
MatchGrantType returns true if the client has the specific grant type.
func (*Client) MatchScopes ¶
MatchScopes returns true if the client has the specific scopes. If "scopes" is empty then it returns true, as there is nothing to check.
func (*Client) RefreshTokenOptions ¶
func (c *Client) RefreshTokenOptions() jwt.SignOption
RefreshTokenOptions returns the signing option for the refresh token.
type ClientFilter ¶
type ClientFilter struct {
// Name matches the clients whose name contains this text, ignoring case.
Name string `json:"name,omitempty"`
// Scope matches the clients that have exactly this scope, e.g. "clients:create".
Scope string `json:"scope,omitempty"`
// Sort is the field to order by: "name", "created_at" or "updated_at".
// Empty means "created_at". Any other value is an ErrInvalidClientFilter.
Sort string `json:"sort,omitempty"`
// SortDescending reverses the order.
SortDescending bool `json:"sort_descending,omitzero"`
}
ClientFilter holds the optional conditions and the ordering of ListClients and CountClients. The zero value matches every client, ordered by creation time ascending.
type ClientRegistration ¶
type ClientRegistration struct {
// Name is the unique name of the client application. Required.
Name string
// Website is the website URL of the client application. Required.
Website string
// LogoURL is the URL of the client's logo. Required.
LogoURL string
// RedirectURI is the callback URL. Required when GrantTypes contains the authorization code
// or the device code grant type.
RedirectURI string
// VerificationURI is the URL where the user enters the user code. Required when GrantTypes
// contains the device code grant type.
VerificationURI string
// GrantTypes are the allowed grant types. When empty they are resolved from the URIs:
// password and refresh_token always, plus authorization_code when RedirectURI is set,
// plus the device code grant type when VerificationURI is set too.
GrantTypes []string
// Scopes are the allowed scopes, stored as given.
Scopes []string
// CodeMaxAge is the max age of the authorization and device codes, in seconds.
// Zero or negative means 3600 (one hour).
CodeMaxAge int
// AccessMaxAge is the max age of the access tokens, in seconds, stored as given.
// Zero or negative means the token does not expire.
AccessMaxAge int
// RefreshMaxAge is the max age of the refresh tokens, in seconds, stored as given.
// Zero or negative means the token does not expire. When both max ages are above zero,
// RefreshMaxAge must be at least AccessMaxAge plus 60.
RefreshMaxAge int
}
ClientRegistration holds the values NewClient, Server.RegisterClient and Server.CreateClient build a Client from. The ID and the secret are generated.
Name, Website and LogoURL are required: an empty one makes NewClient return "name, website, logo and (redirect_uri or verification_uri) are required".
type ClientStore ¶
type ClientStore interface {
// InsertClient adds a new client to the store.
InsertClient(ctx stdContext.Context, client *Client) error
// GetClient fetches a client by its ID.
GetClient(ctx stdContext.Context, id string) (*Client, bool, error)
// GetClientByName fetches a client by its name.
GetClientByName(ctx stdContext.Context, name string) (*Client, bool, error)
// ListClients returns one page of the clients that match the filter (nil matches all)
// and the total number of matches. Clients are returned as stored, secrets included.
ListClients(ctx stdContext.Context, page pagination.PageOptions, filter *ClientFilter) ([]*Client, int64, error)
// CountClients returns the number of clients that match the filter (nil matches all).
CountClients(ctx stdContext.Context, filter *ClientFilter) (int64, error)
// DeleteClient removes a client by its ID. It reports false when there is no such client.
DeleteClient(ctx stdContext.Context, id string) (bool, error)
// UpdateClientScopes replaces the scopes of a client. The secret and the version are untouched.
// It reports false when there is no such client.
UpdateClientScopes(ctx stdContext.Context, id string, scopes []string) (bool, error)
// IncrementClientVersion adds one to the version of a client, which invalidates the tokens
// issued for the previous version. The secret is untouched.
// It reports false when there is no such client.
IncrementClientVersion(ctx stdContext.Context, id string) (bool, error)
}
ClientStore describes methods to insert and retrieve OAuth2 clients.
func NewMemoryClientStore ¶
func NewMemoryClientStore() ClientStore
NewMemoryClientStore creates an in-memory client store.
func NewPostgresClientStore ¶
func NewPostgresClientStore(tableName string, conn PostgresConn) ClientStore
NewPostgresClientStore initializes a new postgresClientStore with the given table name and ensures the table is created if it doesn’t exist.
type ClientTokenClaims ¶
type ClientTokenClaims struct {
// ClientID is the unique ID of the client requesting the token.
ClientID string `json:"client_id" form:"client_id" url:"client_id"`
// ClientName is the name of the client application.
ClientName string `json:"client_name" form:"client_name" url:"client_name"`
// ClientWebsite is the website URL of the client application.
ClientWebsite string `json:"client_website" form:"client_website" url:"client_website"`
// ClientLogoURL is the URL of the client's logo.
ClientLogoURL string `json:"client_logo_url" form:"client_logo_url" url:"client_logo_url"`
// Scopes are the list of permissions or resources the client may access.
Scopes []string `json:"scopes" form:"scopes" url:"scopes"`
// ClientSecret is the client's secret key.
// It's only available outside of oauth2 routes,
// when the app is server-side and has rights to write to the users.
ClientSecret string `json:"client_secret,omitempty" form:"client_secret,omitempty" url:"client_secret,omitempty"`
// Used to verify the token's version. Useful for invalidating tokens.
Version int `json:"version" form:"-" url:"-"`
}
ClientTokenClaims holds client-specific data embedded in tokens (e.g., client ID and scopes).
func GetClientClaims ¶
func GetClientClaims(ctx *context.Context) (ClientTokenClaims, error)
GetClientClaims returns the token's claims of the OAuth2 client that is making the request.
func (*ClientTokenClaims) MatchPolicies ¶
func (c *ClientTokenClaims) MatchPolicies(ctx stdContext.Context, requiredPolicies []Policy) bool
MatchPolicies reports whether the token satisfies at least one of the requiredPolicies. It returns true when requiredPolicies is empty.
type ConfirmConsentRequest ¶
type ConfirmConsentRequest struct {
// Decision stores the user's response: "approve" or "deny."
Decision string `url:"decision" form:"decision"`
// Remember indicates whether the user wants to remember this decision for future requests.
Remember string `url:"remember" form:"remember"`
AuthorizeRequest
}
ConfirmConsentRequest is the form data submitted by the user on the consent page.
func (*ConfirmConsentRequest) Approved ¶
func (req *ConfirmConsentRequest) Approved() bool
Approved returns true if the user decided to approve the requested scopes.
func (*ConfirmConsentRequest) ShouldRemember ¶
func (req *ConfirmConsentRequest) ShouldRemember() bool
ShouldRemember returns true if the user wants to remember the consent decision.
type DeviceCode ¶
type DeviceCode struct {
// Code is the unique device code that the client will use to request a token.
Code string `pg:"type=varchar(128),primary" json:"code"`
// CreatedAt indicates when the code was generated.
CreatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"created_at,omitempty"`
// UpdatedAt is the timestamp of last code update.
UpdatedAt types.ISO8601 `pg:"type=timestamp,default=clock_timestamp()" json:"updated_at,omitempty"`
// ExpiresAt is the time at which the device code will no longer be valid.
ExpiresAt types.ISO8601 `pg:"type=timestamp" json:"expires_at"`
// ClientID is the ID of the client requesting the device code.
ClientID string `pg:"type=uuid,ref=oauth2_clients(id cascade),index" json:"client_id"`
// UserData contains the authenticated user’s data.
UserData AuthUserData `pg:"type=jsonb" json:"user_data"`
// UserCode is the code displayed to the user, who must enter it on the verification URI.
UserCode string `pg:"type=varchar(128)" json:"user_code"`
// Scopes lists the permissions requested by the client.
Scopes []string `pg:"type=varchar[]" json:"scopes"`
// Interval is the polling interval in seconds for the client to check the device code.
Interval int `pg:"type=int,default=0" json:"interval,omitzero"`
}
DeviceCode holds information for the device code flow authorization.
func NewDeviceCode ¶
func NewDeviceCode(clientID string, userData AuthUserData, interval int, scopes []string, maxAge int) (*DeviceCode, error)
NewDeviceCode creates and initializes a new DeviceCode with a unique device code and user code, to be used in the OAuth2 device flow.
func (*DeviceCode) AuthResponse ¶
func (d *DeviceCode) AuthResponse(verificationURI string) oauth2.DeviceAuthResponse
AuthResponse constructs and returns a device authorization response that includes the user code and verification URIs.
func (*DeviceCode) HasExpired ¶
func (d *DeviceCode) HasExpired() bool
HasExpired returns true if the current time is after the code’s ExpiresAt.
type DeviceCodeStore ¶
type DeviceCodeStore interface {
// InsertDeviceCode saves a device code entry in the store.
InsertDeviceCode(ctx stdContext.Context, device *DeviceCode) error
// GetAndDeleteDeviceCode retrieves and deletes a device code by its code value.
GetAndDeleteDeviceCode(ctx stdContext.Context, code string) (*DeviceCode, bool, error)
// GetDeviceCodeByUserCode retrieves a device code using the user code field.
GetDeviceCodeByUserCode(ctx stdContext.Context, userCode string) (*DeviceCode, bool, error)
}
DeviceCodeStore defines methods to persist device codes and retrieve them by code or user code.
func NewMemoryDeviceCodeStore ¶
func NewMemoryDeviceCodeStore() DeviceCodeStore
NewMemoryDeviceCodeStore creates an in-memory device code store.
func NewPostgresDeviceCodeStore ¶
func NewPostgresDeviceCodeStore(clientsTableName, tableName string, conn PostgresConn) DeviceCodeStore
NewPostgresDeviceCodeStore creates a new postgresDeviceCodeStore instance and ensures the associated table is created if it doesn't exist.
type Option ¶
type Option func(*serverOptions)
Option is a function that configures the server.
func WithAuthCodeStore ¶
func WithAuthCodeStore(authCodeStore AuthCodeStore) Option
WithAuthCodeStore sets the authorization code store for the server.
func WithClientStore ¶
func WithClientStore(clientStore ClientStore) Option
WithClientStore sets the client store for the server.
func WithConsentPageURL ¶
WithConsentPageURL sets the consent page URL for the server.
func WithDeviceCodeStore ¶
func WithDeviceCodeStore(deviceCodeStore DeviceCodeStore) Option
WithDeviceCodeStore sets the device code store for the server.
func WithDeviceInterval ¶
WithDeviceInterval sets the default polling interval for device code confirmation.
func WithLoginPageURL ¶
WithLoginPageURL sets the login page URL for the server.
type Policy ¶
type Policy interface {
// Matches checks if the policy matches the given claims.
Matches(ctx stdContext.Context, claims *ClientTokenClaims) bool
}
Policy is an interface that all policy types must implement.
func NewScopePolicies ¶
NewScopePolicies creates a new slice of string scope policies.
func WrapPolicies ¶
WrapPolicies wraps the given policies into a single policy. Example:
policies := append(oauth2.NewScopePolicies("users:read", "users:write"),
oauth2.ResourcePolicy{Resource: "orders", Action: "read"},
)
policy := oauth2.WrapPolicies(policies...)
app.Get("/protected", oauth2.AllowPolicies(policy), handler)
type PostgresConn ¶
type PostgresConn interface {
// Exec executes a query that doesn't return rows.
Exec(ctx stdContext.Context, sql string, arguments ...any) (pgconn.CommandTag, error)
// QueryRow executes a query that is expected to return at most one row.
QueryRow(ctx stdContext.Context, sql string, arguments ...any) pgx.Row
// Query executes a query that returns rows.
Query(ctx stdContext.Context, sql string, args ...any) (pgx.Rows, error)
}
PostgresConn is an interface that defines the methods required to interact with a PostgreSQL database (pool connection).
type ResourcePolicy ¶
type ResourcePolicy struct {
Resource string `json:"resource" yaml:"Resource"`
Action string `json:"action" yaml:"Action"` // more can be added by separating them with a space.
}
ResourcePolicy represents a fine-grained rule for a given resource/action. For example, Resource="users" and Action="read" => "users:read" scope.
A policy of {Resource: "users", Action: "create read update delete"}} generates the following scopes: "users:create", "users:read", "users:update", "users:delete".
func (ResourcePolicy) Actions ¶
func (rp ResourcePolicy) Actions() []string
Actions returns just the actions.
func (ResourcePolicy) Matches ¶
func (rp ResourcePolicy) Matches(_ stdContext.Context, claims *ClientTokenClaims) bool
Matches checks if a scope string matches the resource:action requirement. For instance, a scope "invoices:read" means resource="invoices", action="read". If more than one Action is provided (separated by space), at least one of them must match. If Actions is empty, then all scopes that match the resource are accepted.
func (ResourcePolicy) Scopes ¶
func (rp ResourcePolicy) Scopes() []string
Scopes returns the resource:action scope strings.
func (ResourcePolicy) String ¶
func (rp ResourcePolicy) String() string
String returns the resource:action scope string.
type ScopePolicy ¶
type ScopePolicy struct {
Scope string `json:"scope" yaml:"Scope"`
}
ScopePolicy represents a simple string-based scope policy.
func (ScopePolicy) Matches ¶
func (p ScopePolicy) Matches(_ stdContext.Context, claims *ClientTokenClaims) bool
Matches checks if the given scope matches the policy's scope.
func (ScopePolicy) String ¶
func (p ScopePolicy) String() string
String returns the scope as a string.
type Server ¶
type Server[UserData AuthUserData] struct { // Auth is the Iris Auth instance used for user authentication and verification. Auth *auth.Auth[UserData] // contains filtered or unexported fields }
Server defines an OAuth2 server capable of handling various grant types and flows.
Usage:
type User struct {
ID string `json:"id"`
// Add any other fields you need.
}
oauth2Server := oauth2.New[User](s,
oauth2.WithClientStore(oauth2.NewMemoryClientStore()),
oauth2.WithAuthCodeStore(oauth2.NewMemoryAuthCodeStore()),
oauth2.WithDeviceCodeStore(oauth2.NewMemoryDeviceCodeStore()),
oauth2.WithLoginPageURL("/signin"),
oauth2.WithConsentPageURL("/oauth2/consent"),
)
app.Router("/oauth2", oauth2Server)
- GET /authorize: the authorization endpoint. - GET /consent: the built-in consent page, if the ConsentPageURL is "default" or matches the *relpath*/consent endpoint. - POST /consent: the confirmation endpoint, if the ConsentPageURL is not empty. - GET /consent/revoke: the revoke consent endpoint, if the ConsentPageURL is not empty. - POST /device/code: the device code endpoint. - POST /token: the token endpoint. - POST /token/introspect: the token introspection endpoint.
func New ¶
func New[UserData AuthUserData](a *auth.Auth[UserData], opts ...Option) *Server[UserData]
New creates a new OAuth2 server with the given Auth instance and options. If the Auth instance is not provided, it will try to resolve it using the auth.Resolve function. The server will be built with the provided options.
It can be registered as a router, as it implements the router.Router's Routing method, e.g. app.Router("/oauth2", server).
func (*Server[UserData]) AuthorizeHandler ¶
AuthorizeHandler returns the handler for the authorization endpoint. If ConsentPageURL is set, it returns the consent handler; otherwise, it returns the auth code handler.
func (*Server[UserData]) ClientStore ¶
func (s *Server[UserData]) ClientStore() ClientStore
ClientStore returns the client store the server was configured with.
func (*Server[UserData]) ClientVerifier ¶
func (s *Server[UserData]) ClientVerifier() auth.VerifyUserFunc[ClientTokenClaims]
ClientVerifier returns a VerifyUserFunc that verifies the full client (auth) claims.
func (*Server[UserData]) ConfirmConsentHandler ¶
ConfirmConsentHandler returns the handler for confirming user consent.
func (*Server[UserData]) CreateClient ¶
func (s *Server[UserData]) CreateClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)
CreateClient creates a new client from reg and inserts it into the client store. Unlike RegisterClient it never returns an existing client: it returns ErrClientAlreadyExists when the name is taken.
func (*Server[UserData]) DefaultConsentPageHandler ¶
DefaultConsentPageHandler returns the default consent page handler.
func (*Server[UserData]) DeviceCodeHandler ¶
DeviceCodeHandler returns the handler for the device code endpoint.
func (*Server[UserData]) EnsureClientScopes ¶
func (s *Server[UserData]) EnsureClientScopes(ctx stdContext.Context, client *Client, scopes []string) (bool, error)
EnsureClientScopes adds to the stored client the scopes it lacks (a union that keeps the existing order and removes nothing) and updates client.Scopes to match. The secret and the version are untouched, so every token already issued for the client stays valid. It reports false, with a nil error, when nothing was missing.
func (*Server[UserData]) RegisterClient ¶
func (s *Server[UserData]) RegisterClient(ctx stdContext.Context, reg ClientRegistration) (*Client, error)
RegisterClient creates a new client from reg and inserts it into the configured client store, unless a client with the same name already exists, in which case it returns that one unchanged. See ClientRegistration for the required fields and the defaults.
func (*Server[UserData]) RevokeConsentHandler ¶
RevokeConsentHandler returns the handler for revoking user consent.
func (*Server[UserData]) Routing ¶
Routing registers the necessary routes for the OAuth2 server. - GET /authorize: the authorization endpoint. - GET /consent: the built-in consent page, if the ConsentPageURL is "default" or matches the *relpath*/consent endpoint. - POST /consent: the confirmation endpoint, if the ConsentPageURL is not empty. - GET /consent/revoke: the revoke consent endpoint, if the ConsentPageURL is not empty. - POST /device/code: the device code endpoint. - POST /token: the token endpoint. - POST /token/introspect: the token introspection endpoint.
func (*Server[UserData]) SignToken ¶
func (s *Server[UserData]) SignToken(clientID string, accessMaxAge, refreshMaxAge int, claims ...any) (*oauth2.Token, error)
SignToken signs a token with the given client ID, max age (seconds) and one or more claims.
func (*Server[UserData]) TokenHandler ¶
TokenHandler returns the handler for the token endpoint.
func (*Server[UserData]) TokenIntrospectHandler ¶
TokenIntrospectHandler returns the handler for the token introspection endpoint.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack.
|
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that enables unified, context-aware policy enforcement across the stack. |