Documentation

AuthServer API Reference

← All docs

AuthServer API Reference

Complete method reference for login, signup, SSO, OIDC, token management, and admin operations.

Complete reference for every public method in the AuthServer module.

SqlOSAuthService

Core authentication service. Handles login, signup, sessions, tokens, and password management.


LoginWithPasswordAsync

Authenticate a user with email and password. If the user belongs to multiple organizations and no OrganizationId is specified, returns RequiresOrganizationSelection = true with a PendingAuthToken and the list of organizations.

var result = await authService.LoginWithPasswordAsync(
    new SqlOSPasswordLoginRequest(
        Email: request.Email,
        Password: request.Password,
        ClientId: "my-app",
        OrganizationId: null),
    httpContext);

if (result.RequiresOrganizationSelection)
    return Results.Ok(new
    {
        requiresOrgSelection = true,
        pendingAuthToken = result.PendingAuthToken,
        organizations = result.Organizations
    });

return Results.Ok(result.Tokens);

Parameters

NameTypeDescription
requestSqlOSPasswordLoginRequestLogin credentials.
httpContextHttpContextCurrent HTTP context (used for IP and user agent).
cancellationTokenCancellationTokenOptional cancellation token.

SqlOSPasswordLoginRequest

FieldTypeDescription
EmailstringUser's email address.
PasswordstringUser's password.
ClientIdstring?Client application ID.
OrganizationIdstring?If set, skips org selection and logs in directly.

Returns

Task<SqlOSLoginResult>

FieldTypeDescription
RequiresOrganizationSelectionbooltrue if the user must pick an org before tokens can be issued.
PendingAuthTokenstring?Temporary token for SelectOrganizationAsync.
OrganizationsIReadOnlyList<SqlOSOrganizationOption>Available organizations.
TokensSqlOSTokenResponse?Issued tokens (null if org selection required).

SignUpAsync

Create a new user with email and password. Optionally creates an organization at the same time.

var result = await authService.SignUpAsync(
    new SqlOSSignupRequest(
        DisplayName: "Jane Doe",
        Email: "jane@example.com",
        Password: "s3cureP@ss",
        OrganizationName: "Acme Corp",
        ClientId: "my-app",
        OrganizationId: null),
    httpContext);

return Results.Ok(result.Tokens);

Parameters

NameTypeDescription
requestSqlOSSignupRequestSignup details.
httpContextHttpContextCurrent HTTP context.

SqlOSSignupRequest

FieldTypeDescription
DisplayNamestringUser's display name.
EmailstringUser's email address.
PasswordstringUser's password.
OrganizationNamestring?If set, a new organization is created and the user is added.
ClientIdstring?Client application ID.
OrganizationIdstring?Join existing org instead of creating one.

Returns

Task<SqlOSLoginResult> — same shape as LoginWithPasswordAsync.


SelectOrganizationAsync

Complete login by selecting an organization. Called when LoginWithPasswordAsync returns RequiresOrganizationSelection = true.

var tokens = await authService.SelectOrganizationAsync(
    new SqlOSSelectOrganizationRequest(
        PendingAuthToken: result.PendingAuthToken!,
        OrganizationId: selectedOrgId),
    httpContext);

return Results.Ok(tokens);

Parameters

NameTypeDescription
request.PendingAuthTokenstringThe pending auth token from the login result.
request.OrganizationIdstringThe selected organization ID.
httpContextHttpContextCurrent HTTP context.

Returns

Task<SqlOSTokenResponse>

FieldTypeDescription
AccessTokenstringJWT access token.
RefreshTokenstringOpaque refresh token.
SessionIdstringSession identifier.
ClientIdstringClient application ID.
OrganizationIdstring?Organization the user is logged into.
AccessTokenExpiresAtDateTimeAccess token expiry (UTC).
RefreshTokenExpiresAtDateTimeRefresh token expiry (UTC).

RefreshAsync

Exchange a refresh token for new access and refresh tokens.

var tokens = await authService.RefreshAsync(
    new SqlOSRefreshRequest(
        RefreshToken: request.RefreshToken,
        OrganizationId: null));

return Results.Ok(tokens);

Parameters

NameTypeDescription
request.RefreshTokenstringThe current refresh token.
request.OrganizationIdstring?Optionally switch organization during refresh.

Returns

Task<SqlOSTokenResponse> — new token pair. The previous refresh token is revoked.


LogoutAsync

Revoke a session by refresh token or session ID. Provide at least one.

await authService.LogoutAsync(
    refreshToken: request.RefreshToken,
    sessionId: null);

return Results.Ok();

Parameters

NameTypeDescription
refreshTokenstring?The refresh token to revoke.
sessionIdstring?The session ID to revoke.

Returns

Task — completes when the session/token is invalidated.


LogoutAllAsync

Revoke all sessions for a user.

await authService.LogoutAllAsync(userId);

Parameters

NameTypeDescription
userIdstringThe user whose sessions to revoke.

Returns

Task


ValidateAccessTokenAsync

Validate a JWT access token and extract the claims principal.

var validated = await authService.ValidateAccessTokenAsync(rawToken);
if (validated is null)
    return Results.Unauthorized();

var userId = validated.UserId;
var orgId = validated.OrganizationId;

Parameters

NameTypeDescription
rawTokenstringThe raw JWT access token string.

Returns

Task<SqlOSValidatedToken?>null if the token is invalid or expired.

FieldTypeDescription
PrincipalClaimsPrincipalThe validated claims principal.
SessionIdstringThe session the token belongs to.
UserIdstring?The authenticated user's ID.
OrganizationIdstring?The organization from the token.
ClientIdstring?The client application ID.

ExchangeCodeAsync

Exchange an authorization code for tokens. Used in SSO callback flows.

var tokens = await authService.ExchangeCodeAsync(
    new SqlOSExchangeCodeRequest(
        Code: code,
        ClientId: "my-app"),
    httpContext);

Parameters

NameTypeDescription
request.CodestringThe authorization code.
request.ClientIdstringThe client application ID.
httpContextHttpContextCurrent HTTP context.

Returns

Task<SqlOSTokenResponse>


CreatePasswordResetTokenAsync

Generate a one-time password reset token. Send the returned token to the user via email.

var token = await authService.CreatePasswordResetTokenAsync(
    new SqlOSForgotPasswordRequest(Email: request.Email));

// Send token via email (you provide the email transport)
await emailService.SendResetEmail(request.Email, token);

Parameters

NameTypeDescription
request.EmailstringThe user's email address.

Returns

Task<string> — the raw reset token to deliver to the user.


ResetPasswordAsync

Consume a password reset token and set the new password.

await authService.ResetPasswordAsync(
    new SqlOSResetPasswordRequest(
        Token: request.Token,
        NewPassword: request.NewPassword));

Parameters

NameTypeDescription
request.TokenstringThe reset token from CreatePasswordResetTokenAsync.
request.NewPasswordstringThe new password.

Returns

Task


CreateEmailVerificationTokenAsync

Generate an email verification token. Send the returned token to the user via email.

var token = await authService.CreateEmailVerificationTokenAsync(
    new SqlOSCreateVerificationTokenRequest(Email: request.Email));

Parameters

NameTypeDescription
request.EmailstringThe email to verify.

Returns

Task<string> — the raw verification token.


VerifyEmailAsync

Consume a verification token and mark the email as verified.

await authService.VerifyEmailAsync(
    new SqlOSVerifyEmailRequest(Token: request.Token));

Parameters

NameTypeDescription
request.TokenstringThe verification token.

Returns

Task


CreateSessionTokensForUserAsync

Directly issue session tokens for a user. Used after OIDC/SSO flows complete, when you have a resolved user but need to create the SqlOS session.

var tokens = await authService.CreateSessionTokensForUserAsync(
    user, client, organizationId: org.Id,
    authenticationMethod: "oidc",
    userAgent: httpContext.Request.Headers.UserAgent,
    ipAddress: httpContext.Connection.RemoteIpAddress?.ToString());

Parameters

NameTypeDescription
userSqlOSUserThe authenticated user entity.
clientSqlOSClientApplicationThe client application.
organizationIdstring?The organization to scope the session to.
authenticationMethodstringHow the user authenticated (e.g., "password", "oidc", "saml").
userAgentstring?Browser user agent.
ipAddressstring?Client IP address.

Returns

Task<SqlOSTokenResponse>


SqlOSAdminService

Administrative operations for managing organizations, users, memberships, clients, and SSO connections.


CreateOrganizationAsync

Create a new organization.

var org = await adminService.CreateOrganizationAsync(
    new SqlOSCreateOrganizationRequest(
        Name: "Acme Corp",
        Slug: "acme",
        PrimaryDomain: "acme.com"));

Parameters

NameTypeDescription
request.NamestringOrganization display name.
request.Slugstring?URL-safe slug. Auto-generated from name if null.
request.PrimaryDomainstring?Primary email domain for SSO/home-realm discovery.

Returns

Task<SqlOSOrganization> — the created organization entity.


CreateUserAsync

Create a new user.

var user = await adminService.CreateUserAsync(
    new SqlOSCreateUserRequest(
        DisplayName: "Jane Doe",
        Email: "jane@acme.com",
        Password: "s3cureP@ss"));

Parameters

NameTypeDescription
request.DisplayNamestringDisplay name.
request.EmailstringEmail address (normalized and deduplicated).
request.Passwordstring?Password. If null, the user can only log in via SSO/OIDC.

Returns

Task<SqlOSUser> — the created user entity.


CreateMembershipAsync

Add a user to an organization with a role.

var membership = await adminService.CreateMembershipAsync(
    organizationId: org.Id,
    new SqlOSCreateMembershipRequest(
        UserId: user.Id,
        Role: "admin"));

Parameters

NameTypeDescription
organizationIdstringThe organization to add the user to.
request.UserIdstringThe user to add.
request.RolestringThe membership role (e.g., "admin", "member").

Returns

Task<SqlOSMembership> — the created membership.


CreateClientAsync

Register a client application.

var client = await adminService.CreateClientAsync(
    new SqlOSCreateClientRequest(
        ClientId: "my-app",
        Name: "My Application",
        Audience: "https://api.example.com",
        RedirectUris: ["https://example.com/callback"]));

Parameters

NameTypeDescription
request.ClientIdstringUnique client identifier.
request.NamestringDisplay name.
request.AudiencestringThe JWT audience claim.
request.RedirectUrisList<string>Allowed redirect URIs.

Returns

Task<SqlOSClientApplication> — the created client.


CreateSsoConnectionDraftAsync

Create a SAML SSO connection draft. After creating the draft, upload IdP metadata with ImportSsoMetadataAsync.

var draft = await adminService.CreateSsoConnectionDraftAsync(
    new SqlOSCreateSsoConnectionDraftRequest(
        OrganizationId: org.Id,
        DisplayName: "Acme Okta SSO",
        PrimaryDomain: "acme.com",
        AutoProvisionUsers: true,
        AutoLinkByEmail: true));

// Now import the metadata:
await adminService.ImportSsoMetadataAsync(
    draft.Id,
    new SqlOSImportSsoMetadataRequest(MetadataXml: xml));

Parameters

NameTypeDescription
request.OrganizationIdstringThe organization this connection belongs to.
request.DisplayNamestringDisplay name for the connection.
request.PrimaryDomainstring?Email domain for home-realm discovery.
request.AutoProvisionUsersboolCreate users on first SSO login.
request.AutoLinkByEmailboolLink existing users by email during SSO.

Returns

Task<SqlOSSsoConnectionDraft> — the created draft with an ID.


ImportSsoMetadataAsync

Upload SAML IdP metadata XML for an existing SSO connection draft.

await adminService.ImportSsoMetadataAsync(
    connectionId,
    new SqlOSImportSsoMetadataRequest(MetadataXml: metadataXml));

Parameters

NameTypeDescription
connectionIdstringThe SSO connection ID.
request.MetadataXmlstringThe raw SAML IdP metadata XML.

Returns

Task


CreateOidcConnectionAsync

Register an OIDC social login provider (Google, Microsoft, Apple, or custom).

var conn = await adminService.CreateOidcConnectionAsync(
    new SqlOSCreateOidcConnectionRequest(
        ProviderType: SqlOSOidcProviderType.Google,
        DisplayName: "Sign in with Google",
        ClientId: "google-client-id",
        ClientSecret: "google-client-secret",
        AllowedCallbackUris: ["https://example.com/callback"],
        UseDiscovery: true,
        DiscoveryUrl: "https://accounts.google.com/.well-known/openid-configuration",
        // remaining fields null/default
        Issuer: null, AuthorizationEndpoint: null,
        TokenEndpoint: null, UserInfoEndpoint: null,
        JwksUri: null, MicrosoftTenant: null,
        Scopes: null, ClaimMapping: null,
        ClientAuthMethod: null, UseUserInfo: null));

Parameters

NameTypeDescription
request.ProviderTypeSqlOSOidcProviderTypeGoogle, Microsoft, Apple, or Custom.
request.DisplayNamestringDisplay name for the provider.
request.ClientIdstringOAuth client ID from the provider.
request.ClientSecretstring?OAuth client secret.
request.AllowedCallbackUrisList<string>Allowed callback URIs.
request.UseDiscoveryboolWhether to use OIDC discovery.
request.DiscoveryUrlstring?The .well-known/openid-configuration URL.
request.MicrosoftTenantstring?Azure AD tenant ID (Microsoft only).
request.ScopesList<string>?Custom scopes to request.

Returns

Task<SqlOSOidcConnection> — the created connection.


GetUserOrganizationsAsync

List all organizations a user belongs to.

var orgs = await adminService.GetUserOrganizationsAsync(userId);
// Returns: [{ Id, Slug, Name, Role }, ...]

Parameters

NameTypeDescription
userIdstringThe user's ID.

Returns

Task<List<SqlOSOrganizationOption>>

FieldTypeDescription
IdstringOrganization ID.
SlugstringOrganization slug.
NamestringOrganization name.
RolestringThe user's role in this org.

UserHasMembershipAsync

Check if a user belongs to an organization.

var isMember = await adminService.UserHasMembershipAsync(userId, orgId);

Parameters

NameTypeDescription
userIdstringThe user's ID.
organizationIdstringThe organization ID.

Returns

Task<bool>


NormalizeEmail

Normalize an email address (lowercase, trim).

var email = SqlOSAdminService.NormalizeEmail("  Jane@ACME.com ");
// "jane@acme.com"

Parameters

NameTypeDescription
emailstringThe email to normalize.

Returns

string


SqlOSHomeRealmDiscoveryService

Determines how a user should authenticate based on their email domain.


DiscoverAsync

Look up the authentication method for an email address. Returns whether the domain maps to an SSO connection, OIDC provider, or password login.

var result = await hrdService.DiscoverAsync(
    new SqlOSHomeRealmDiscoveryRequest(Email: request.Email));

// result.Mode: "password" | "sso" | "oidc"
// result.ConnectionId: SSO/OIDC connection ID (if applicable)
// result.OrganizationId: matched org ID

Parameters

NameTypeDescription
request.EmailstringThe email to discover.

Returns

Task<SqlOSHomeRealmDiscoveryResult>

FieldTypeDescription
ModestringAuthentication mode: "password", "sso", or "oidc".
OrganizationIdstring?Matched organization.
OrganizationNamestring?Organization display name.
PrimaryDomainstring?The matched domain.
ConnectionIdstring?SSO or OIDC connection ID to use.

SqlOSSsoAuthorizationService

SAML SSO authorization flow.


StartAuthorizationAsync

Start a SAML SSO login flow. Returns the IdP authorization URL to redirect the user to.

var ssoResult = await ssoService.StartAuthorizationAsync(
    new SqlOSSsoAuthorizationStartRequest(
        Email: request.Email,
        ClientId: "my-app",
        RedirectUri: "https://example.com/callback",
        State: state,
        CodeChallenge: codeChallenge,
        CodeChallengeMethod: "S256"));

// Redirect the user:
return Results.Redirect(ssoResult.AuthorizationUrl);

Parameters

NameTypeDescription
request.EmailstringUser's email (determines the SSO connection via domain).
request.ClientIdstringClient application ID.
request.RedirectUristringWhere to redirect after SSO.
request.StatestringCSRF state parameter.
request.CodeChallengestringPKCE code challenge.
request.CodeChallengeMethodstring"S256".

Returns

Task<SqlOSSsoAuthorizationStartResult>

FieldTypeDescription
AuthorizationUrlstringThe SAML IdP URL to redirect to.
OrganizationIdstringThe matched organization.
OrganizationNamestringOrganization name.
PrimaryDomainstringThe matched domain.

ExchangeCodeAsync (SSO)

Exchange a PKCE authorization code for tokens after the SAML SSO callback.

var tokens = await ssoService.ExchangeCodeAsync(
    new SqlOSPkceExchangeRequest(
        Code: code,
        ClientId: "my-app",
        RedirectUri: "https://example.com/callback",
        CodeVerifier: codeVerifier),
    httpContext);

Parameters

NameTypeDescription
request.CodestringThe authorization code.
request.ClientIdstringClient application ID.
request.RedirectUristringMust match the original redirect URI.
request.CodeVerifierstringThe PKCE code verifier.
httpContextHttpContextCurrent HTTP context.

Returns

Task<SqlOSTokenResponse>


SqlOSOidcAuthService

OIDC (social login) authorization flow — Google, Microsoft, Apple, or custom providers.


ListEnabledProvidersAsync

List all enabled OIDC providers available for login.

var providers = await oidcService.ListEnabledProvidersAsync();
// [{ ConnectionId, ProviderType, DisplayName, ... }]

Returns

Task<List<SqlOSOidcProviderInfo>>


StartAuthorizationAsync (OIDC)

Start an OIDC authorization flow. Returns the provider's authorization URL.

var result = await oidcService.StartAuthorizationAsync(
    new SqlOSStartOidcAuthorizationRequest(
        ConnectionId: connectionId,
        Email: request.Email,
        ClientId: "my-app",
        CallbackUri: "https://example.com/oidc/callback",
        State: state,
        Nonce: nonce,
        CodeChallenge: codeChallenge,
        CodeChallengeMethod: "S256"),
    ipAddress: httpContext.Connection.RemoteIpAddress?.ToString());

return Results.Redirect(result.AuthorizationUrl);

Parameters

NameTypeDescription
request.ConnectionIdstringThe OIDC connection to use.
request.EmailstringUser's email.
request.ClientIdstringClient application ID.
request.CallbackUristringOAuth callback URI.
request.StatestringCSRF state.
request.NoncestringToken replay prevention nonce.
request.CodeChallengestringPKCE code challenge.
request.CodeChallengeMethodstring"S256".
ipAddressstring?Client IP for audit logging.

Returns

Task<SqlOSStartOidcAuthorizationResult>

FieldTypeDescription
AuthorizationUrlstringProvider URL to redirect to.
ConnectionIdstringThe OIDC connection used.
ProviderTypeSqlOSOidcProviderTypeGoogle, Microsoft, Apple, or Custom.
DisplayNamestringProvider display name.

CompleteAuthorizationAsync

Complete the OIDC callback. Exchanges the authorization code with the provider, resolves the user, and returns session info.

var result = await oidcService.CompleteAuthorizationAsync(
    new SqlOSCompleteOidcAuthorizationRequest(
        ConnectionId: connectionId,
        ClientId: "my-app",
        CallbackUri: "https://example.com/oidc/callback",
        Code: code,
        CodeVerifier: codeVerifier,
        Nonce: nonce,
        UserPayloadJson: null),
    ipAddress: httpContext.Connection.RemoteIpAddress?.ToString());

// result.UserId, result.Email, result.OrganizationId
// Now create a session:
var tokens = await authService.CreateSessionTokensForUserAsync(
    user, client, result.OrganizationId,
    result.AuthenticationMethod, userAgent, ipAddress);

Parameters

NameTypeDescription
request.ConnectionIdstringThe OIDC connection.
request.ClientIdstringClient application ID.
request.CallbackUristringMust match the original callback URI.
request.CodestringThe authorization code from the provider.
request.CodeVerifierstringPKCE code verifier.
request.NoncestringMust match the original nonce.

Returns

Task<SqlOSCompleteOidcAuthorizationResult>

FieldTypeDescription
UserIdstringResolved or created user ID.
EmailstringUser's email from the provider.
DisplayNamestringUser's display name from the provider.
OrganizationIdstring?Matched organization (if any).
AuthenticationMethodstringe.g., "oidc_google".

SqlOSSettingsService

Manage runtime security settings.


GetResolvedSecuritySettingsAsync

Get the effective security settings (with defaults applied).

var settings = await settingsService.GetResolvedSecuritySettingsAsync();
// settings.RefreshTokenLifetime, settings.SessionIdleTimeout, etc.

Returns

Task<SqlOSResolvedSecuritySettings>

FieldTypeDescription
RefreshTokenLifetimeTimeSpanHow long refresh tokens are valid.
SessionIdleTimeoutTimeSpanSession expires after this idle period.
SessionAbsoluteLifetimeTimeSpanMaximum session lifetime regardless of activity.

UpdateSecuritySettingsAsync

Update the security settings.

await settingsService.UpdateSecuritySettingsAsync(
    new SqlOSUpdateSecuritySettingsRequest(
        RefreshTokenLifetimeMinutes: 1440,
        SessionIdleTimeoutMinutes: 60,
        SessionAbsoluteLifetimeMinutes: 10080));

Parameters

NameTypeDescription
request.RefreshTokenLifetimeMinutesintRefresh token lifetime in minutes.
request.SessionIdleTimeoutMinutesintIdle timeout in minutes.
request.SessionAbsoluteLifetimeMinutesintAbsolute lifetime in minutes.

Returns

Task


Key Contracts

SqlOSTokenResponse

Returned by all successful authentication flows.

public sealed record SqlOSTokenResponse(
    string AccessToken,
    string RefreshToken,
    string SessionId,
    string ClientId,
    string? OrganizationId,
    DateTime AccessTokenExpiresAt,
    DateTime RefreshTokenExpiresAt);

SqlOSLoginResult

Returned by LoginWithPasswordAsync and SignUpAsync.

public sealed record SqlOSLoginResult(
    bool RequiresOrganizationSelection,
    string? PendingAuthToken,
    IReadOnlyList<SqlOSOrganizationOption> Organizations,
    SqlOSTokenResponse? Tokens);

SqlOSValidatedToken

Returned by ValidateAccessTokenAsync.

public sealed record SqlOSValidatedToken(
    ClaimsPrincipal Principal,
    string SessionId,
    string? UserId,
    string? OrganizationId,
    string? ClientId);

SqlOSOrganizationOption

Used in multi-org selection flows.

public sealed record SqlOSOrganizationOption(
    string Id,
    string Slug,
    string Name,
    string Role);