oidcprovider

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: Apache-2.0 Imports: 34 Imported by: 0

README

OIDC Provider Plugin - Enterprise Edition

Comprehensive enterprise-grade OpenID Connect Provider plugin for AuthSome with multi-tenancy support, org-specific configurations, and RFC-compliant OAuth2/OIDC implementation.

Features

Core OIDC/OAuth2
  • ✅ OAuth2 Authorization Code Flow with PKCE
  • ✅ OpenID Connect ID Tokens (JWT)
  • ✅ Refresh Tokens
  • ✅ Automatic Key Rotation
  • ✅ JWKS Endpoint
  • ✅ UserInfo Endpoint
  • ✅ Discovery Endpoint (.well-known/openid-configuration)
Enterprise Features (RFC-Compliant)
  • RFC 7591: Dynamic Client Registration
  • RFC 7662: Token Introspection
  • RFC 7009: Token Revocation (with cascade support)
  • ✅ Client Authentication (client_secret_basic, client_secret_post, none/PKCE)
  • ✅ Persistent Consent Management
  • ✅ Org-specific OAuth Clients with hierarchy fallback
  • ✅ Session-linked Token Lifecycle
  • ✅ Admin Client Management Endpoints
Multi-Tenancy Architecture
  • App-Level Clients: Default OAuth clients available to all organizations
  • Org-Level Clients: Organization-specific OAuth clients with custom configurations
  • Hierarchy Resolution: Org-specific clients override app-level clients
  • Context-Aware: Full integration with App/Environment/Organization contexts

Architecture

Schema Updates
OAuthClient
type OAuthClient struct {
    // Context
    AppID          xid.ID
    EnvironmentID  xid.ID
    OrganizationID *xid.ID  // null = app-level, set = org-specific
    
    // OAuth2/OIDC Config
    RedirectURIs            []string
    PostLogoutRedirectURIs  []string
    GrantTypes              []string
    ResponseTypes           []string
    AllowedScopes           []string
    
    // Security
    TokenEndpointAuthMethod string  // client_secret_basic, client_secret_post, none
    ApplicationType         string  // web, native, spa
    RequirePKCE             bool
    RequireConsent          bool
    TrustedClient           bool
    
    // RFC 7591 Metadata
    LogoURI    string
    PolicyURI  string
    TosURI     string
    Contacts   []string
    Metadata   map[string]interface{}
}
AuthorizationCode
type AuthorizationCode struct {
    AppID          xid.ID
    EnvironmentID  xid.ID
    OrganizationID *xid.ID
    SessionID      *xid.ID     // Links to user session
    
    ConsentGranted bool
    ConsentScopes  string
    AuthTime       time.Time   // For max_age checks
}
OAuthToken
type OAuthToken struct {
    AppID          xid.ID
    EnvironmentID  xid.ID
    OrganizationID *xid.ID
    SessionID      *xid.ID     // For session-based revocation
    
    IDToken    string
    TokenClass string          // access_token, refresh_token, id_token
    
    // JWT Claims
    JTI       string           // For revocation by ID
    Issuer    string
    Audience  []string
    NotBefore *time.Time
    
    // Authentication Context
    AuthTime *time.Time
    ACR      string
    AMR      []string
}
OAuthConsent (New)
type OAuthConsent struct {
    AppID          xid.ID
    EnvironmentID  xid.ID
    OrganizationID *xid.ID
    UserID         xid.ID
    ClientID       string
    Scopes         []string
    ExpiresAt      *time.Time  // Optional consent expiration
}

API Endpoints

Public Endpoints
GET /.well-known/openid-configuration

Returns OIDC discovery document with all supported endpoints and capabilities.

GET /oauth2/jwks

Returns JSON Web Key Set for token verification.

GET /oauth2/authorize

OAuth2/OIDC authorization endpoint. Initiates authorization flow.

Query Parameters:

  • client_id (required)
  • redirect_uri (required)
  • response_type (required): code
  • scope: Space-separated scopes (e.g., openid profile email)
  • state: Opaque value for CSRF protection
  • nonce: For ID token replay protection
  • code_challenge: PKCE challenge
  • code_challenge_method: S256 or plain
POST /oauth2/token

Exchanges authorization code for tokens.

Request:

{
  "grant_type": "authorization_code",
  "code": "...",
  "redirect_uri": "...",
  "client_id": "...",
  "client_secret": "...",  // Not required for public clients
  "code_verifier": "..."   // Required for PKCE
}

Response:

{
  "access_token": "...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "...",
  "id_token": "...",        // Only if openid scope requested
  "scope": "openid profile email"
}
GET /oauth2/userinfo

Returns user information. Requires Bearer token.

Response:

{
  "sub": "user_id",
  "email": "user@example.com",
  "email_verified": true,
  "name": "John Doe",
  "preferred_username": "johndoe",
  "picture": "https://..."
}
Enterprise Endpoints
POST /oauth2/introspect (RFC 7662)

Introspects access or refresh token. Requires client authentication.

Request:

{
  "token": "...",
  "token_type_hint": "access_token"  // Optional: access_token or refresh_token
}

Response:

{
  "active": true,
  "scope": "openid profile",
  "client_id": "client_123",
  "username": "johndoe",
  "token_type": "Bearer",
  "exp": 1609459200,
  "iat": 1609455600,
  "sub": "user_id",
  "aud": ["https://api.example.com"],
  "iss": "https://auth.example.com",
  "jti": "token_id"
}
POST /oauth2/revoke (RFC 7009)

Revokes access or refresh token. Requires client authentication.

Request:

{
  "token": "...",
  "token_type_hint": "access_token"  // Optional
}

Response:

{
  "status": "revoked"
}
Admin Endpoints
POST /oauth2/register (RFC 7591)

Registers a new OAuth client (admin only).

Request:

{
  "client_name": "My Application",
  "redirect_uris": ["https://app.example.com/callback"],
  "post_logout_redirect_uris": ["https://app.example.com"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "application_type": "web",  // web, native, spa
  "token_endpoint_auth_method": "client_secret_basic",
  "logo_uri": "https://app.example.com/logo.png",
  "policy_uri": "https://app.example.com/privacy",
  "tos_uri": "https://app.example.com/terms",
  "contacts": ["admin@example.com"],
  "scope": "openid profile email",
  "require_pkce": true,
  "require_consent": true,
  "trusted_client": false
}

Response:

{
  "client_id": "client_01HZ...",
  "client_secret": "secret_...",  // Omitted for public clients
  "client_id_issued_at": 1609459200,
  "client_secret_expires_at": 0,  // 0 = never expires
  "client_name": "My Application",
  "redirect_uris": ["https://app.example.com/callback"],
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "application_type": "web",
  "token_endpoint_auth_method": "client_secret_basic",
  ...
}
GET /oauth2/clients

Lists all OAuth clients (admin only).

Query Parameters:

  • page: Page number (default: 1)
  • page_size: Results per page (default: 20, max: 100)
GET /oauth2/clients/:clientId

Gets OAuth client details (admin only).

PUT /oauth2/clients/:clientId

Updates OAuth client (admin only).

DELETE /oauth2/clients/:clientId

Deletes OAuth client and revokes all tokens (admin only).

Configuration

auth:
  oidcprovider:
    issuer: "https://auth.example.com"
    
    keys:
      privateKeyPath: "/path/to/private_key.pem"
      publicKeyPath: "/path/to/public_key.pem"
      rotationInterval: "24h"
      keyLifetime: "168h"  # 7 days
    
    tokens:
      accessTokenExpiry: "1h"
      idTokenExpiry: "1h"
      refreshTokenExpiry: "720h"  # 30 days

Usage

Initialize Plugin
import "github.com/xraph/authsome/plugins/oidcprovider"

plugin := oidcprovider.NewPlugin(
    oidcprovider.WithIssuer("https://auth.example.com"),
)

authsome.RegisterPlugin(plugin)
Register App-Level Client
// Via API (admin authenticated)
POST /oauth2/register
{
  "client_name": "Platform App",
  "redirect_uris": ["https://app.example.com/callback"],
  "application_type": "web"
}
Register Org-Specific Client
// Set organization context, then register
// Client will be scoped to the organization
POST /oauth2/register
{
  "client_name": "Org Custom App",
  "redirect_uris": ["https://org.example.com/callback"]
}
Authorization Flow
  1. Redirect to Authorization Endpoint:
GET /oauth2/authorize?
  client_id=client_123&
  redirect_uri=https://app.example.com/callback&
  response_type=code&
  scope=openid profile email&
  state=random_state&
  code_challenge=challenge&
  code_challenge_method=S256
  1. User Authenticates & Consents

    • If not logged in, redirected to login
    • If consent required, shown consent screen
    • Consent stored for future requests
  2. Redirect Back with Code:

https://app.example.com/callback?code=auth_code&state=random_state
  1. Exchange Code for Tokens:
POST /oauth2/token
{
  "grant_type": "authorization_code",
  "code": "auth_code",
  "redirect_uri": "https://app.example.com/callback",
  "client_id": "client_123",
  "client_secret": "secret",
  "code_verifier": "verifier"
}
  1. Use Access Token:
GET /oauth2/userinfo
Authorization: Bearer access_token

Security Considerations

PKCE (Proof Key for Code Exchange)
  • Mandatory for native and SPA applications
  • Recommended for all authorization code flows
  • Prevents authorization code interception attacks
  • Use S256 method (SHA256) over plain
Client Authentication
  • Confidential Clients (web apps): Use client_secret_basic or client_secret_post
  • Public Clients (native/SPA): Use none with mandatory PKCE
  • Client secrets never expire (rotate manually if compromised)
Token Security
  • Access tokens expire after 1 hour
  • Refresh tokens expire after 30 days
  • Tokens linked to sessions (revoked when session ends)
  • Support revocation by token, session, user, or client
  • JWT IDs (jti) enable revocation by ID
  • Persistent consent storage
  • Optional consent expiration
  • Trusted clients skip consent
  • Consent can be revoked by user

Migration Guide

From Basic OIDC to Enterprise
  1. Update Schema:
# Run migrations to add new fields and tables
authsome migrate
  1. Update Existing Clients:

    • Set application_type based on client type
    • Configure token_endpoint_auth_method
    • Enable require_pkce for public clients
    • Set require_consent based on trust level
  2. Update Client Applications:

    • Implement PKCE for public clients
    • Handle consent screens
    • Use introspection for resource servers
    • Implement token revocation on logout

Advanced Features

Session-Based Token Lifecycle

Tokens are linked to user sessions. When a session is terminated:

  • All associated tokens are automatically revoked
  • Prevents orphaned tokens after logout
Org-Specific Configurations

Organizations can override app-level OAuth clients:

App Level: Default Google OAuth (app client_id)
  ↓
Org Level: Custom Google OAuth (org client_id)

Resolution order:

  1. Try org-specific client first
  2. Fall back to app-level client
  3. Return not found if neither exists
Token Revocation Strategies
  • By Token: Revoke specific access/refresh token
  • By JWT ID: Revoke by jti claim
  • By Session: Cascade revoke all session tokens
  • By User: Revoke all user tokens in org
  • By Client: Revoke all client tokens

Testing

# Run OIDC provider tests
go test -v ./plugins/oidcprovider/...

# Test with coverage
go test -v -cover ./plugins/oidcprovider/...

# Integration tests
go test -v -tags=integration ./plugins/oidcprovider/...

Troubleshooting

Common Issues

"Invalid redirect_uri"

  • Ensure redirect URI is exactly registered (including trailing slashes)
  • Check for HTTPS requirement (except localhost)

"PKCE required for this client"

  • Client configured with require_pkce: true
  • Must provide code_challenge and code_challenge_method in authorize request
  • Must provide code_verifier in token request

"Invalid client credentials"

  • Check client authentication method matches client configuration
  • For Basic auth: Properly encode credentials in Authorization header
  • For POST: Include client_id and client_secret in request body

"Token expired or revoked"

  • Access tokens expire after 1 hour
  • Use refresh token to obtain new access token
  • Check if session was terminated

License

Copyright (c) 2025 AuthSome. All rights reserved.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetTokenScopes

func GetTokenScopes(scope string) []string

GetTokenScopes parses and returns the scopes from a token

func HasScope

func HasScope(tokenScope, requiredScope string) bool

HasScope checks if a token has a specific scope

Types

type AccessTokenClaims

type AccessTokenClaims struct {
	jwt.RegisteredClaims
	Scope     string `json:"scope,omitempty"`
	ClientID  string `json:"client_id"`
	TokenType string `json:"token_type"`
}

AccessTokenClaims represents the claims for an access token

type AdminHandler

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

AdminHandler handles admin-only OAuth client management endpoints

func NewAdminHandler

func NewAdminHandler(clientRepo *repo.OAuthClientRepository, registrationSvc *RegistrationService) *AdminHandler

NewAdminHandler creates a new admin handler

func (*AdminHandler) DeleteClient

func (h *AdminHandler) DeleteClient(c forge.Context) error

DeleteClient deletes an OAuth client

func (*AdminHandler) GetClient

func (h *AdminHandler) GetClient(c forge.Context) error

GetClient retrieves detailed information about an OAuth client

func (*AdminHandler) ListClients

func (h *AdminHandler) ListClients(c forge.Context) error

ListClients lists all OAuth clients for the current app/env/org

func (*AdminHandler) RegisterClient

func (h *AdminHandler) RegisterClient(c forge.Context) error

RegisterClient handles dynamic client registration (admin only)

func (*AdminHandler) UpdateClient

func (h *AdminHandler) UpdateClient(c forge.Context) error

UpdateClient updates an existing OAuth client

type AuthorizeRequest

type AuthorizeRequest struct {
	ClientID            string `json:"client_id" form:"client_id" validate:"required"`
	RedirectURI         string `json:"redirect_uri" form:"redirect_uri" validate:"required,url"`
	ResponseType        string `json:"response_type" form:"response_type" validate:"required"`
	Scope               string `json:"scope" form:"scope"`
	State               string `json:"state" form:"state"`
	Nonce               string `json:"nonce" form:"nonce"`
	CodeChallenge       string `json:"code_challenge" form:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method" form:"code_challenge_method"`
	Prompt              string `json:"prompt" form:"prompt"` // none, login, consent, select_account
	MaxAge              *int   `json:"max_age" form:"max_age"`
	UILocales           string `json:"ui_locales" form:"ui_locales"`
	IDTokenHint         string `json:"id_token_hint" form:"id_token_hint"`
	LoginHint           string `json:"login_hint" form:"login_hint"`
	ACRValues           string `json:"acr_values" form:"acr_values"`
}

AuthorizeRequest represents an OAuth2/OIDC authorization request

type ClientAuthResult

type ClientAuthResult struct {
	ClientID      string
	Authenticated bool
	Method        string // basic, post, none
}

ClientAuthResult represents the result of client authentication

type ClientAuthenticator

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

ClientAuthenticator handles OAuth2/OIDC client authentication

func NewClientAuthenticator

func NewClientAuthenticator(clientRepo *repo.OAuthClientRepository) *ClientAuthenticator

NewClientAuthenticator creates a new client authenticator

func (*ClientAuthenticator) AuthenticateClient

AuthenticateClient authenticates an OAuth2 client using various methods Supports: client_secret_basic, client_secret_post, and none (for public clients with PKCE)

func (*ClientAuthenticator) IsConfidentialClient

func (c *ClientAuthenticator) IsConfidentialClient(client *schema.OAuthClient) bool

IsConfidentialClient checks if a client is a confidential client (has client secret)

func (*ClientAuthenticator) IsPublicClient

func (c *ClientAuthenticator) IsPublicClient(client *schema.OAuthClient) bool

IsPublicClient checks if a client is a public client (no client secret)

func (*ClientAuthenticator) ValidateClientForEndpoint

func (c *ClientAuthenticator) ValidateClientForEndpoint(client *schema.OAuthClient, endpoint string) error

ValidateClientForEndpoint validates that a client can access a specific endpoint

type ClientDetailsResponse

type ClientDetailsResponse struct {
	ClientID                string   `json:"clientID"`
	Name                    string   `json:"name"`
	ApplicationType         string   `json:"applicationType"`
	RedirectURIs            []string `json:"redirectURIs"`
	PostLogoutRedirectURIs  []string `json:"postLogoutRedirectURIs,omitempty"`
	GrantTypes              []string `json:"grantTypes"`
	ResponseTypes           []string `json:"responseTypes"`
	AllowedScopes           []string `json:"allowedScopes,omitempty"`
	TokenEndpointAuthMethod string   `json:"tokenEndpointAuthMethod"`
	RequirePKCE             bool     `json:"requirePKCE"`
	RequireConsent          bool     `json:"requireConsent"`
	TrustedClient           bool     `json:"trustedClient"`
	LogoURI                 string   `json:"logoURI,omitempty"`
	PolicyURI               string   `json:"policyURI,omitempty"`
	TosURI                  string   `json:"tosURI,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	CreatedAt               string   `json:"createdAt"`
	UpdatedAt               string   `json:"updatedAt"`
	IsOrgLevel              bool     `json:"isOrgLevel"`
	OrganizationID          string   `json:"organizationID,omitempty"`
}

ClientDetailsResponse represents detailed information about an OAuth client

type ClientRegistrationRequest

type ClientRegistrationRequest struct {
	ClientName              string   `json:"client_name" validate:"required"`
	RedirectURIs            []string `json:"redirect_uris" validate:"required,min=1,dive,url"`
	PostLogoutRedirectURIs  []string `json:"post_logout_redirect_uris,omitempty" validate:"omitempty,dive,url"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	ApplicationType         string   `json:"application_type,omitempty" validate:"omitempty,oneof=web native spa"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty" validate:"omitempty,oneof=client_secret_basic client_secret_post none"`
	LogoURI                 string   `json:"logo_uri,omitempty" validate:"omitempty,url"`
	PolicyURI               string   `json:"policy_uri,omitempty" validate:"omitempty,url"`
	TosURI                  string   `json:"tos_uri,omitempty" validate:"omitempty,url"`
	Contacts                []string `json:"contacts,omitempty" validate:"omitempty,dive,email"`
	Scope                   string   `json:"scope,omitempty"`
	RequirePKCE             bool     `json:"require_pkce,omitempty"`
	RequireConsent          bool     `json:"require_consent,omitempty"`
	TrustedClient           bool     `json:"trusted_client,omitempty"`
}

ClientRegistrationRequest represents a dynamic client registration request (RFC 7591)

type ClientRegistrationResponse

type ClientRegistrationResponse struct {
	ClientID                string   `json:"client_id" example:"client_01HZ..."`
	ClientSecret            string   `json:"client_secret,omitempty" example:"secret_01HZ..."`
	ClientIDIssuedAt        int64    `json:"client_id_issued_at" example:"1609459200"`
	ClientSecretExpiresAt   int64    `json:"client_secret_expires_at" example:"0"` // 0 = never expires
	ClientName              string   `json:"client_name" example:"My Application"`
	RedirectURIs            []string `json:"redirect_uris" example:"https://example.com/callback"`
	PostLogoutRedirectURIs  []string `json:"post_logout_redirect_uris,omitempty"`
	GrantTypes              []string `json:"grant_types" example:"authorization_code,refresh_token"`
	ResponseTypes           []string `json:"response_types" example:"code"`
	ApplicationType         string   `json:"application_type" example:"web"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method" example:"client_secret_basic"`
	LogoURI                 string   `json:"logo_uri,omitempty"`
	PolicyURI               string   `json:"policy_uri,omitempty"`
	TosURI                  string   `json:"tos_uri,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
	Scope                   string   `json:"scope,omitempty"`
}

ClientRegistrationResponse represents a successful client registration response (RFC 7591)

type ClientSummary

type ClientSummary struct {
	ClientID        string `json:"clientID"`
	Name            string `json:"name"`
	ApplicationType string `json:"applicationType"`
	CreatedAt       string `json:"createdAt"`
	IsOrgLevel      bool   `json:"isOrgLevel"`
}

ClientSummary represents a summary of an OAuth client

type ClientUpdateRequest

type ClientUpdateRequest struct {
	Name                    string   `json:"name,omitempty"`
	RedirectURIs            []string `json:"redirect_uris,omitempty" validate:"omitempty,dive,url"`
	PostLogoutRedirectURIs  []string `json:"post_logout_redirect_uris,omitempty" validate:"omitempty,dive,url"`
	GrantTypes              []string `json:"grant_types,omitempty"`
	ResponseTypes           []string `json:"response_types,omitempty"`
	AllowedScopes           []string `json:"allowed_scopes,omitempty"`
	TokenEndpointAuthMethod string   `json:"token_endpoint_auth_method,omitempty" validate:"omitempty,oneof=client_secret_basic client_secret_post none"`
	RequirePKCE             *bool    `json:"require_pkce,omitempty"`
	RequireConsent          *bool    `json:"require_consent,omitempty"`
	TrustedClient           *bool    `json:"trusted_client,omitempty"`
	LogoURI                 string   `json:"logo_uri,omitempty" validate:"omitempty,url"`
	PolicyURI               string   `json:"policy_uri,omitempty" validate:"omitempty,url"`
	TosURI                  string   `json:"tos_uri,omitempty" validate:"omitempty,url"`
	Contacts                []string `json:"contacts,omitempty" validate:"omitempty,dive,email"`
}

ClientUpdateRequest represents a client update request

type ClientsListResponse

type ClientsListResponse struct {
	Clients    []ClientSummary `json:"clients"`
	Total      int             `json:"total"`
	Page       int             `json:"page"`
	PageSize   int             `json:"pageSize"`
	TotalPages int             `json:"totalPages"`
}

ClientsListResponse represents a list of OAuth clients

type Config

type Config struct {
	// Issuer URL for the OIDC Provider
	Issuer string `json:"issuer"`

	// Key configuration
	Keys struct {
		// Path to RSA private key file (PEM format)
		PrivateKeyPath string `json:"privateKeyPath"`
		// Path to RSA public key file (PEM format)
		PublicKeyPath string `json:"publicKeyPath"`
		// Key rotation settings
		RotationInterval string `json:"rotationInterval"` // e.g., "24h"
		KeyLifetime      string `json:"keyLifetime"`      // e.g., "168h" (7 days)
	} `json:"keys"`

	// Token settings
	Tokens struct {
		AccessTokenExpiry  string `json:"accessTokenExpiry"`  // e.g., "1h"
		IDTokenExpiry      string `json:"idTokenExpiry"`      // e.g., "1h"
		RefreshTokenExpiry string `json:"refreshTokenExpiry"` // e.g., "720h" (30 days)
	} `json:"tokens"`
}

Config represents the OIDC Provider configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default OIDC Provider configuration

type ConsentDecision

type ConsentDecision struct {
	Approved bool
	Scopes   []string
}

ConsentDecision represents a user's consent decision

type ConsentManager

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

ConsentManager handles OAuth consent with optional integration to enterprise consent plugin

func NewConsentManager

func NewConsentManager(consentSvc *ConsentService, enterpriseConsent EnterpriseConsentService) *ConsentManager

NewConsentManager creates a consent manager with optional enterprise integration

func (*ConsentManager) CheckConsent

func (cm *ConsentManager) CheckConsent(ctx context.Context, userID xid.ID, clientID, scope string, appID, envID xid.ID, orgID *xid.ID) (bool, error)

CheckConsent checks if user has granted consent for the client and scopes

func (*ConsentManager) GenerateConsentHTML

func (cm *ConsentManager) GenerateConsentHTML(clientName, clientLogoURI, scope string, redirectURL string) string

GenerateConsentHTML generates HTML for the OAuth consent screen

func (*ConsentManager) GetConsentPageData

func (cm *ConsentManager) GetConsentPageData(clientName, clientLogoURI, clientDescription, scope string) map[string]interface{}

GetConsentPageData returns data for rendering custom consent templates

func (*ConsentManager) RecordConsent

func (cm *ConsentManager) RecordConsent(ctx context.Context, userID xid.ID, clientID, scope string, granted bool, appID, envID xid.ID, orgID *xid.ID, expiresAt *time.Time) error

RecordConsent records user's consent decision

func (*ConsentManager) RevokeConsent

func (cm *ConsentManager) RevokeConsent(ctx context.Context, userID xid.ID, clientID string) error

RevokeConsent revokes user's consent for a client

func (*ConsentManager) ValidateConsentRequest

func (cm *ConsentManager) ValidateConsentRequest(consentDecision string) error

ValidateConsentRequest validates the consent decision from user

type ConsentRequest

type ConsentRequest struct {
	Action              string `json:"action" form:"action" validate:"required,oneof=allow deny"`
	ClientID            string `json:"client_id" form:"client_id" validate:"required"`
	RedirectURI         string `json:"redirect_uri" form:"redirect_uri" validate:"required"`
	ResponseType        string `json:"response_type" form:"response_type" validate:"required"`
	Scope               string `json:"scope" form:"scope"`
	State               string `json:"state" form:"state"`
	CodeChallenge       string `json:"code_challenge" form:"code_challenge"`
	CodeChallengeMethod string `json:"code_challenge_method" form:"code_challenge_method"`
}

ConsentRequest represents the consent form submission

type ConsentService

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

ConsentService handles OAuth2/OIDC consent management

func NewConsentService

func NewConsentService(consentRepo *repo.OAuthConsentRepository, clientRepo *repo.OAuthClientRepository) *ConsentService

NewConsentService creates a new consent service

func (*ConsentService) CheckConsent

func (s *ConsentService) CheckConsent(ctx context.Context, userID xid.ID, clientID string, requestedScopes []string, appID, envID xid.ID, orgID *xid.ID) (bool, error)

CheckConsent checks if user has already consented to the requested scopes for a client

func (*ConsentService) FormatScopes

func (s *ConsentService) FormatScopes(scopes []string) string

FormatScopes converts a scope slice to a space-separated string

func (*ConsentService) GetScopeDescriptions

func (s *ConsentService) GetScopeDescriptions(scopes []string) []ScopeInfo

GetScopeDescriptions returns user-friendly descriptions for scopes

func (*ConsentService) GrantConsent

func (s *ConsentService) GrantConsent(ctx context.Context, userID xid.ID, clientID string, scopes []string, appID, envID xid.ID, orgID *xid.ID, expiresIn *time.Duration) error

GrantConsent stores user's consent decision

func (*ConsentService) ListUserConsents

func (s *ConsentService) ListUserConsents(ctx context.Context, userID xid.ID, appID, envID xid.ID, orgID *xid.ID) ([]*schema.OAuthConsent, error)

ListUserConsents retrieves all consents granted by a user

func (*ConsentService) ParseScopes

func (s *ConsentService) ParseScopes(scopeString string) []string

ParseScopes converts a space-separated scope string to a slice

func (*ConsentService) RequiresConsent

func (s *ConsentService) RequiresConsent(ctx context.Context, clientID string, scopes []string, appID, envID xid.ID, orgID *xid.ID) (bool, error)

RequiresConsent checks if the requested scopes require user consent

func (*ConsentService) RevokeConsent

func (s *ConsentService) RevokeConsent(ctx context.Context, userID xid.ID, clientID string) error

RevokeConsent removes a user's consent for a client

type DiscoveryResponse

type DiscoveryResponse struct {
	Issuer                                    string   `json:"issuer" example:"https://auth.example.com"`
	AuthorizationEndpoint                     string   `json:"authorization_endpoint" example:"https://auth.example.com/oauth2/authorize"`
	TokenEndpoint                             string   `json:"token_endpoint" example:"https://auth.example.com/oauth2/token"`
	UserInfoEndpoint                          string   `json:"userinfo_endpoint" example:"https://auth.example.com/oauth2/userinfo"`
	JwksURI                                   string   `json:"jwks_uri" example:"https://auth.example.com/oauth2/jwks"`
	RegistrationEndpoint                      string   `json:"registration_endpoint,omitempty" example:"https://auth.example.com/oauth2/register"`
	IntrospectionEndpoint                     string   `json:"introspection_endpoint,omitempty" example:"https://auth.example.com/oauth2/introspect"`
	RevocationEndpoint                        string   `json:"revocation_endpoint,omitempty" example:"https://auth.example.com/oauth2/revoke"`
	ResponseTypesSupported                    []string `json:"response_types_supported" example:"code,token,id_token"`
	ResponseModesSupported                    []string `json:"response_modes_supported,omitempty" example:"query,fragment,form_post"`
	GrantTypesSupported                       []string `json:"grant_types_supported" example:"authorization_code,refresh_token,client_credentials"`
	SubjectTypesSupported                     []string `json:"subject_types_supported" example:"public"`
	IDTokenSigningAlgValuesSupported          []string `json:"id_token_signing_alg_values_supported" example:"RS256"`
	ScopesSupported                           []string `json:"scopes_supported" example:"openid,profile,email"`
	TokenEndpointAuthMethodsSupported         []string `json:"token_endpoint_auth_methods_supported" example:"client_secret_basic,client_secret_post"`
	ClaimsSupported                           []string `json:"claims_supported" example:"sub,name,email,picture"`
	CodeChallengeMethodsSupported             []string `json:"code_challenge_methods_supported,omitempty" example:"S256,plain"`
	IntrospectionEndpointAuthMethodsSupported []string `json:"introspection_endpoint_auth_methods_supported,omitempty"`
	RevocationEndpointAuthMethodsSupported    []string `json:"revocation_endpoint_auth_methods_supported,omitempty"`
	RequestParameterSupported                 bool     `json:"request_parameter_supported,omitempty"`
	RequestURIParameterSupported              bool     `json:"request_uri_parameter_supported,omitempty"`
	RequireRequestURIRegistration             bool     `json:"require_request_uri_registration,omitempty"`
	ClaimsParameterSupported                  bool     `json:"claims_parameter_supported,omitempty"`
}

DiscoveryResponse represents the OIDC discovery document

type DiscoveryService

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

DiscoveryService handles OIDC discovery document generation

func NewDiscoveryService

func NewDiscoveryService(config Config) *DiscoveryService

NewDiscoveryService creates a new discovery service

func (*DiscoveryService) GetDiscoveryDocument

func (s *DiscoveryService) GetDiscoveryDocument(ctx context.Context, baseURL string) *DiscoveryResponse

GetDiscoveryDocument generates the OIDC discovery document (.well-known/openid-configuration)

func (*DiscoveryService) GetIssuer

func (s *DiscoveryService) GetIssuer() string

GetIssuer returns the configured issuer URL

func (*DiscoveryService) SupportsGrantType

func (s *DiscoveryService) SupportsGrantType(grantType string) bool

SupportsGrantType checks if a grant type is supported

func (*DiscoveryService) SupportsResponseType

func (s *DiscoveryService) SupportsResponseType(responseType string) bool

SupportsResponseType checks if a response type is supported

func (*DiscoveryService) SupportsScope

func (s *DiscoveryService) SupportsScope(scope string) bool

SupportsScope checks if a scope is supported

type EnterpriseConsentService

type EnterpriseConsentService interface {
	// CreateConsent records user consent
	CreateConsent(ctx context.Context, orgID, userID string, req interface{}) (interface{}, error)

	// GetConsent retrieves consent status
	GetConsent(ctx context.Context, id string) (interface{}, error)

	// RevokeConsent revokes a consent
	RevokeConsent(ctx context.Context, id string) error
}

EnterpriseConsentService interface for enterprise consent plugin This allows optional integration without hard dependency

type ErrorResponse

type ErrorResponse = responses.ErrorResponse

ErrorResponse is the standard OAuth2/OIDC error response

type Handler

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

Handler handles OIDC provider HTTP endpoints

func NewHandler

func NewHandler(svc *Service) *Handler

NewHandler creates a new OIDC handler

func (*Handler) Authorize

func (h *Handler) Authorize(c forge.Context) error

Authorize handles OAuth2/OIDC authorization requests

func (*Handler) Discovery

func (h *Handler) Discovery(c forge.Context) error

Discovery handles the OIDC discovery endpoint (.well-known/openid-configuration)

func (*Handler) HandleConsent

func (h *Handler) HandleConsent(c forge.Context) error

HandleConsent processes the consent form submission

func (*Handler) IntrospectToken

func (h *Handler) IntrospectToken(c forge.Context) error

IntrospectToken handles token introspection requests

func (*Handler) JWKS

func (h *Handler) JWKS(c forge.Context) error

JWKS returns the JSON Web Key Set

func (*Handler) RevokeToken

func (h *Handler) RevokeToken(c forge.Context) error

RevokeToken handles token revocation requests

func (*Handler) Token

func (h *Handler) Token(c forge.Context) error

Token handles the token endpoint

func (*Handler) UserInfo

func (h *Handler) UserInfo(c forge.Context) error

UserInfo returns user information based on the access token

type IDTokenClaims

type IDTokenClaims struct {
	jwt.RegisteredClaims
	Nonce             string `json:"nonce,omitempty"`
	AuthTime          int64  `json:"auth_time"`
	SessionState      string `json:"session_state,omitempty"`
	PreferredUsername string `json:"preferred_username,omitempty"`
	Email             string `json:"email,omitempty"`
	EmailVerified     bool   `json:"email_verified,omitempty"`
	Name              string `json:"name,omitempty"`
	GivenName         string `json:"given_name,omitempty"`
	FamilyName        string `json:"family_name,omitempty"`
}

IDTokenClaims represents the claims for an OIDC ID token

type IntrospectionService

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

IntrospectionService handles RFC 7662 token introspection operations

func NewIntrospectionService

func NewIntrospectionService(tokenRepo *repo.OAuthTokenRepository, clientRepo *repo.OAuthClientRepository, userSvc UserService) *IntrospectionService

NewIntrospectionService creates a new token introspection service

func (*IntrospectionService) IntrospectByJTI

func (s *IntrospectionService) IntrospectByJTI(ctx context.Context, jti string, requestingClientID string) (*TokenIntrospectionResponse, error)

IntrospectByJTI introspects a token by its JWT ID

func (*IntrospectionService) IntrospectToken

func (s *IntrospectionService) IntrospectToken(ctx context.Context, req *TokenIntrospectionRequest, requestingClientID string) (*TokenIntrospectionResponse, error)

IntrospectToken implements RFC 7662 token introspection Returns token metadata if active, or {active: false} if inactive/invalid

func (*IntrospectionService) ValidateIntrospectionRequest

func (s *IntrospectionService) ValidateIntrospectionRequest(req *TokenIntrospectionRequest) error

ValidateIntrospectionRequest validates the introspection request

type JWK

type JWK struct {
	KeyType   string `json:"kty"`
	Use       string `json:"use"`
	KeyID     string `json:"kid"`
	Algorithm string `json:"alg"`
	N         string `json:"n"` // RSA modulus
	E         string `json:"e"` // RSA exponent
}

JWK represents a JSON Web Key

type JWKResponse

type JWKResponse = JWK

JWKResponse is an alias for the JWKS key structure defined in jwks.go

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set

type JWKSResponse

type JWKSResponse struct {
	Keys []JWK `json:"keys"`
}

JWKSResponse represents the JSON Web Key Set response

type JWKSService

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

JWKSService manages JSON Web Key Sets for the OIDC Provider

func NewJWKSService

func NewJWKSService() (*JWKSService, error)

NewJWKSService creates a new JWKS service

func NewJWKSServiceFromFiles

func NewJWKSServiceFromFiles(privateKeyPath, publicKeyPath, rotationInterval, keyLifetime string) (*JWKSService, error)

NewJWKSServiceFromFiles creates a JWKS service with keys loaded from files

func (*JWKSService) GetActiveKeyPair

func (j *JWKSService) GetActiveKeyPair() *KeyPair

GetActiveKeyPair returns the current active key pair for signing

func (*JWKSService) GetCurrentKeyID

func (j *JWKSService) GetCurrentKeyID() string

GetCurrentKeyID returns the ID of the current active key

func (*JWKSService) GetCurrentPrivateKey

func (j *JWKSService) GetCurrentPrivateKey() *rsa.PrivateKey

GetCurrentPrivateKey returns the private key of the current active key

func (*JWKSService) GetJWKS

func (j *JWKSService) GetJWKS() (*JWKS, error)

GetJWKS returns the current JSON Web Key Set

func (*JWKSService) GetKeyByID

func (j *JWKSService) GetKeyByID(keyID string) (*JWK, error)

GetKeyByID returns a specific key by its ID

func (*JWKSService) GetPublicKey

func (j *JWKSService) GetPublicKey(keyID string) (*rsa.PublicKey, error)

GetPublicKey returns the public key for a given key ID

func (*JWKSService) RotateKeys

func (j *JWKSService) RotateKeys() error

RotateKeys triggers key rotation

func (*JWKSService) ShouldRotate

func (j *JWKSService) ShouldRotate() bool

ShouldRotate checks if keys should be rotated

type JWTService

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

JWTService handles JWT token generation and signing for OIDC Provider

func NewJWTService

func NewJWTService(issuer string, jwksService *JWKSService) (*JWTService, error)

NewJWTService creates a new JWT service with JWKS service for key management

func (*JWTService) GenerateAccessToken

func (j *JWTService) GenerateAccessToken(userID, clientID, scope string) (string, error)

GenerateAccessToken creates a signed access token

func (*JWTService) GenerateIDToken

func (j *JWTService) GenerateIDToken(userID, clientID, nonce string, authTime time.Time, userInfo map[string]interface{}) (string, error)

GenerateIDToken creates a signed OIDC ID token

func (*JWTService) VerifyToken

func (j *JWTService) VerifyToken(tokenString string) (*jwt.Token, error)

VerifyToken verifies and parses a JWT token

type KeyPair

type KeyPair struct {
	ID         string
	PrivateKey *rsa.PrivateKey
	PublicKey  *rsa.PublicKey
	CreatedAt  time.Time
	ExpiresAt  time.Time
	Active     bool // Whether this key is used for signing new tokens
}

KeyPair represents an RSA key pair with metadata

type KeyStore

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

KeyStore manages multiple key pairs for rotation

func NewKeyStore

func NewKeyStore() (*KeyStore, error)

NewKeyStore creates a new key store with initial key pair

func NewKeyStoreFromFiles

func NewKeyStoreFromFiles(privateKeyPath, publicKeyPath, rotationInterval, keyLifetime string) (*KeyStore, error)

NewKeyStoreFromFiles creates a new key store with keys loaded from files

func (*KeyStore) GetActiveKey

func (ks *KeyStore) GetActiveKey() *KeyPair

GetActiveKey returns the current active key pair for signing

func (*KeyStore) GetAllValidKeys

func (ks *KeyStore) GetAllValidKeys() []*KeyPair

GetAllValidKeys returns all keys that haven't expired

func (*KeyStore) GetKeyByID

func (ks *KeyStore) GetKeyByID(keyID string) *KeyPair

GetKeyByID returns a key pair by its ID

func (*KeyStore) RotateKeys

func (ks *KeyStore) RotateKeys() error

RotateKeys generates a new key and cleans up expired keys

func (*KeyStore) ShouldRotate

func (ks *KeyStore) ShouldRotate() bool

ShouldRotate checks if keys should be rotated based on the rotation interval

type OAuthErrorResponse

type OAuthErrorResponse struct {
	Error            string `json:"error" example:"invalid_request"`
	ErrorDescription string `json:"error_description,omitempty" example:"The request is missing a required parameter"`
	ErrorURI         string `json:"error_uri,omitempty" example:"https://docs.example.com/errors/invalid_request"`
	State            string `json:"state,omitempty"`
}

OAuthErrorResponse represents an OAuth2-specific error response

type Plugin

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

Plugin wires the OIDC Provider service and registers routes

func NewPlugin

func NewPlugin(opts ...PluginOption) *Plugin

NewPlugin creates a new OIDC provider plugin instance with optional configuration

func (*Plugin) ID

func (p *Plugin) ID() string

func (*Plugin) Init

func (p *Plugin) Init(authInst core.Authsome) error

Init accepts auth instance with GetDB method

func (*Plugin) Migrate

func (p *Plugin) Migrate() error

Migrate runs database migrations

func (*Plugin) RegisterExtensions

func (p *Plugin) RegisterExtensions(reg interface{}) error

RegisterExtensions registers the plugin with the extension registry

func (*Plugin) RegisterHooks

func (p *Plugin) RegisterHooks(hooksRegistry *hooks.HookRegistry) error

RegisterHooks registers plugin hooks

func (*Plugin) RegisterRoutes

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes mounts OIDC Provider endpoints

func (*Plugin) RegisterServiceDecorators

func (p *Plugin) RegisterServiceDecorators(services *registry.ServiceRegistry) error

RegisterServiceDecorators registers service decorators

func (*Plugin) Shutdown

func (p *Plugin) Shutdown() error

Shutdown performs cleanup when the plugin is shutting down

type PluginOption

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring the OIDC provider plugin

func WithDefaultConfig

func WithDefaultConfig(cfg Config) PluginOption

WithDefaultConfig sets the default configuration for the plugin

func WithIssuer

func WithIssuer(issuer string) PluginOption

WithIssuer sets the OIDC issuer URL

type RegistrationService

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

RegistrationService handles RFC 7591 dynamic client registration operations

func NewRegistrationService

func NewRegistrationService(clientRepo *repo.OAuthClientRepository, config Config) *RegistrationService

NewRegistrationService creates a new client registration service

func (*RegistrationService) RegisterClient

func (s *RegistrationService) RegisterClient(ctx context.Context, req *ClientRegistrationRequest, appID, envID xid.ID, orgID *xid.ID) (*ClientRegistrationResponse, error)

RegisterClient implements RFC 7591 dynamic client registration

func (*RegistrationService) ValidateRegistrationRequest

func (s *RegistrationService) ValidateRegistrationRequest(req *ClientRegistrationRequest) error

ValidateRegistrationRequest validates a client registration request per RFC 7591

type RevokeTokenService

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

RevokeTokenService handles RFC 7009 token revocation operations

func NewRevokeTokenService

func NewRevokeTokenService(tokenRepo *repo.OAuthTokenRepository) *RevokeTokenService

NewRevokeTokenService creates a new token revocation service

func (*RevokeTokenService) AuthenticateClient

func (s *RevokeTokenService) AuthenticateClient(r *http.Request, clientRepo *repo.OAuthClientRepository) (*ClientAuthResult, error)

AuthenticateClient performs client authentication for the revocation endpoint Supports client_secret_basic and client_secret_post methods

func (*RevokeTokenService) RevokeByJTI

func (s *RevokeTokenService) RevokeByJTI(ctx context.Context, jti string) error

RevokeByJTI revokes a token by its JWT ID

func (*RevokeTokenService) RevokeToken

RevokeToken implements RFC 7009 token revocation Returns nil even if token doesn't exist (per RFC 7009 spec)

type ScopeInfo

type ScopeInfo struct {
	Name        string
	Description string
}

ScopeInfo represents a scope with its description for consent screens

type Service

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

Service provides enterprise OIDC Provider operations with org-aware support

func NewService

func NewService(config Config) *Service

NewService creates a new OIDC Provider service with default config

func NewServiceWithRepos

func NewServiceWithRepos(clientRepo *repo.OAuthClientRepository, config Config) *Service

NewServiceWithRepos creates a new OIDC Provider service with repositories

func (*Service) CreateAuthorizationCode

func (s *Service) CreateAuthorizationCode(ctx context.Context, req *AuthorizeRequest, userID xid.ID, sessionID xid.ID) (*schema.AuthorizationCode, error)

CreateAuthorizationCode creates and stores an authorization code with full context

func (*Service) ExchangeCodeForTokens

func (s *Service) ExchangeCodeForTokens(ctx context.Context, authCode *schema.AuthorizationCode, userInfo map[string]interface{}) (*TokenResponse, error)

ExchangeCodeForTokens exchanges an authorization code for JWT tokens

func (*Service) ExtractContext

func (s *Service) ExtractContext(ctx context.Context) (appID, envID xid.ID, orgID *xid.ID, err error)

ExtractContext extracts app, env, and org context from request context

func (*Service) GenerateAuthorizationCode

func (s *Service) GenerateAuthorizationCode() (string, error)

GenerateAuthorizationCode generates a secure authorization code

func (*Service) GenerateClientCredentialsToken

func (s *Service) GenerateClientCredentialsToken(ctx context.Context, client *schema.OAuthClient, scope string) (*TokenResponse, error)

GenerateClientCredentialsToken generates a token for client credentials grant (M2M) Implements OAuth2 Client Credentials Grant (RFC 6749 Section 4.4)

func (*Service) GetJWKS

func (s *Service) GetJWKS() (*JWKS, error)

GetJWKS returns the JSON Web Key Set for token verification

func (*Service) GetUserInfoFromToken

func (s *Service) GetUserInfoFromToken(ctx context.Context, accessToken string) (map[string]interface{}, error)

GetUserInfoFromToken retrieves user information based on an access token

func (*Service) MarkCodeAsUsed

func (s *Service) MarkCodeAsUsed(ctx context.Context, code string) error

MarkCodeAsUsed marks an authorization code as used

func (*Service) RefreshAccessToken

func (s *Service) RefreshAccessToken(ctx context.Context, refreshToken, clientID, requestedScope string) (*TokenResponse, error)

RefreshAccessToken refreshes an access token using a refresh token Implements OAuth2 Refresh Token Grant (RFC 6749 Section 6) Optionally rotates the refresh token for improved security

func (*Service) SetRepositories

func (s *Service) SetRepositories(
	clientRepo *repo.OAuthClientRepository,
	codeRepo *repo.AuthorizationCodeRepository,
	tokenRepo *repo.OAuthTokenRepository,
	consentRepo *repo.OAuthConsentRepository,
)

SetRepositories configures all required repositories

func (*Service) SetSessionService

func (s *Service) SetSessionService(sessionSvc *session.Service)

SetSessionService configures the session service

func (*Service) SetUserService

func (s *Service) SetUserService(userSvc *user.Service)

SetUserService sets the user service

func (*Service) StartKeyRotation

func (s *Service) StartKeyRotation()

StartKeyRotation begins automatic key rotation in the background

func (*Service) StopKeyRotation

func (s *Service) StopKeyRotation()

StopKeyRotation stops the automatic key rotation

func (*Service) ValidateAuthorizationCode

func (s *Service) ValidateAuthorizationCode(ctx context.Context, code, clientID, redirectURI, codeVerifier string) (*schema.AuthorizationCode, error)

ValidateAuthorizationCode validates and retrieves an authorization code

func (*Service) ValidateAuthorizeRequest

func (s *Service) ValidateAuthorizeRequest(ctx context.Context, req *AuthorizeRequest) error

ValidateAuthorizeRequest validates an OAuth2/OIDC authorization request

type TokenIntrospectionRequest

type TokenIntrospectionRequest struct {
	Token         string `json:"token" form:"token" validate:"required"`
	TokenTypeHint string `json:"token_type_hint" form:"token_type_hint"` // access_token, refresh_token
	ClientID      string `json:"client_id" form:"client_id"`
	ClientSecret  string `json:"client_secret" form:"client_secret"`
}

TokenIntrospectionRequest represents a token introspection request (RFC 7662)

type TokenIntrospectionResponse

type TokenIntrospectionResponse struct {
	Active    bool     `json:"active" example:"true"`
	Scope     string   `json:"scope,omitempty" example:"openid profile email"`
	ClientID  string   `json:"client_id,omitempty" example:"client_123"`
	Username  string   `json:"username,omitempty" example:"johndoe"`
	TokenType string   `json:"token_type,omitempty" example:"Bearer"`
	Exp       int64    `json:"exp,omitempty" example:"1609459200"`
	Iat       int64    `json:"iat,omitempty" example:"1609455600"`
	Nbf       int64    `json:"nbf,omitempty" example:"1609455600"`
	Sub       string   `json:"sub,omitempty" example:"01HZ..."`
	Aud       []string `json:"aud,omitempty" example:"https://api.example.com"`
	Iss       string   `json:"iss,omitempty" example:"https://auth.example.com"`
	Jti       string   `json:"jti,omitempty" example:"token_01HZ..."`
}

TokenIntrospectionResponse represents a token introspection response (RFC 7662)

type TokenRequest

type TokenRequest struct {
	GrantType    string `json:"grant_type" form:"grant_type" validate:"required"`
	Code         string `json:"code" form:"code"`
	RedirectURI  string `json:"redirect_uri" form:"redirect_uri"`
	ClientID     string `json:"client_id" form:"client_id"`
	ClientSecret string `json:"client_secret" form:"client_secret"`
	CodeVerifier string `json:"code_verifier" form:"code_verifier"`
	RefreshToken string `json:"refresh_token" form:"refresh_token"`
	Scope        string `json:"scope" form:"scope"`
	// Client Credentials grant
	Audience string `json:"audience" form:"audience"`
}

TokenRequest represents the token endpoint request

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token" example:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."`
	TokenType    string `json:"token_type" example:"Bearer"`
	ExpiresIn    int    `json:"expires_in" example:"3600"`
	RefreshToken string `json:"refresh_token,omitempty" example:"def50200..."`
	IDToken      string `json:"id_token,omitempty" example:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."`
	Scope        string `json:"scope,omitempty" example:"openid profile email"`
}

TokenResponse represents the OAuth2/OIDC token response

type TokenRevocationRequest

type TokenRevocationRequest struct {
	Token         string `json:"token" form:"token" validate:"required"`
	TokenTypeHint string `json:"token_type_hint" form:"token_type_hint"` // access_token, refresh_token
	ClientID      string `json:"client_id" form:"client_id"`
	ClientSecret  string `json:"client_secret" form:"client_secret"`
}

TokenRevocationRequest represents a token revocation request (RFC 7009)

type UserInfoResponse

type UserInfoResponse struct {
	Sub               string `json:"sub" example:"01HZ..."`
	Email             string `json:"email,omitempty" example:"user@example.com"`
	EmailVerified     bool   `json:"email_verified,omitempty" example:"true"`
	Name              string `json:"name,omitempty" example:"John Doe"`
	GivenName         string `json:"given_name,omitempty" example:"John"`
	FamilyName        string `json:"family_name,omitempty" example:"Doe"`
	MiddleName        string `json:"middle_name,omitempty"`
	Nickname          string `json:"nickname,omitempty"`
	PreferredUsername string `json:"preferred_username,omitempty" example:"johndoe"`
	Profile           string `json:"profile,omitempty"`
	Picture           string `json:"picture,omitempty" example:"https://example.com/avatar.jpg"`
	Website           string `json:"website,omitempty"`
	Gender            string `json:"gender,omitempty"`
	Birthdate         string `json:"birthdate,omitempty"`
	Zoneinfo          string `json:"zoneinfo,omitempty"`
	Locale            string `json:"locale,omitempty"`
	UpdatedAt         int64  `json:"updated_at,omitempty"`
	PhoneNumber       string `json:"phone_number,omitempty"`
	PhoneVerified     bool   `json:"phone_number_verified,omitempty"`
}

UserInfoResponse represents the OIDC userinfo endpoint response

type UserService

type UserService interface {
	FindByID(ctx context.Context, userID xid.ID) (interface{}, error)
}

UserService interface for getting user information during introspection Note: This uses interface{} for userID to allow xid.ID or string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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