Jump to content

MindAttic.Authentication/ORGANIZATIONS

From MindAttic Docs

Organizations and memberships (opt-in)

Added in 8.0.0 (M.AUTH-T34). Multi-tenant apps give users memberships in organizations, each with an app-defined role string. The feature is opt-in: an app that does not call AddMindAtticOrganizations is unchanged (no tables, no services, no claims).

Wiring

  1. Your DbContext implements IOrganizationDataContext (it already implements IAuthDataContext):
    public DbSet<AuthOrganization> AuthOrganizations => Set<AuthOrganization>(); public DbSet<AuthMembership> AuthMemberships => Set<AuthMembership>(); public DbSet<AuthOrganizationAudit> AuthOrganizationAudit => Set<AuthOrganizationAudit>();
  2. In OnModelCreating: b.ApplyMindAtticAuthConfiguration(organizations: true); (or call ApplyMindAtticOrganizationConfiguration() yourself), then add a migration. Tables (schema auth): AuthOrganizations, AuthMemberships (unique on organization + user; FK to the organization and, cascading, to AuthUsers), AuthOrganizationAudit. AuthModel.OrganizationModelFingerprint is "auth-org-v1".
  3. In Program.cs, after AddMindAtticAuthentication:
    builder.Services.AddMindAtticOrganizations<MyDbContext>(builder.Configuration, o => {     o.OwnerRole = "Owner";     o.Roles = ["Owner", "Admin", "Instructor", "Student"];     o.MfaRequiredRoles = ["Owner", "Admin", "Instructor"];     o.MembershipClaimType = "myapp:org";   // optional; default "ma:org" });

IOrganizationService

The caller's own authorization decides who may manage an organization; the service enforces invariants. Pass actingRole (the caller's role in the organization) when an organization member is acting, and null for platform staff and system code.

Method Notes
CreateAsync(name, createdBy?, ownerUserId?) Unique slug; optional first owner.
AddMemberAsync / SetRoleAsync Add, restore, or change role. Only an owner grants the owner role or changes an owner's role. A role change signs the user out everywhere.
RemoveMemberAsync / RestoreMemberAsync Deactivates or restores; the last active owner cannot be removed. Removal signs the user out everywhere.
SetOrganizationActiveAsync Deactivating ends every member's sessions.
MembershipsOfAsync(userId) Active memberships of active organizations.
MembersAsync(organizationId) Memberships with user name and email.

Every change writes an AuthOrganizationAudit row (action such as member.role, actor, subject, short detail) in the same save as the change. No tokens, passwords or full emails are recorded.

Claims

At sign-in the library adds one claim per active membership of an active organization, type AuthOrganizationOptions.MembershipClaimType (default ma:org), value {organizationId:N}|{role}. Claims are baked into the cookie once, so a membership change rotates the user's SecurityStamp; the existing revalidation then signs the old session out and the next sign-in carries the current memberships. Choosing which organization is "active" for a request is the host's concern (Gadfly uses a cookie).

Per-role MFA

Roles in MfaRequiredRoles require MFA. Granting one to a user without MFA sets MustEnrollMfa; and if any held role requires MFA, the sign-in carries ma:omfa=1, so a session without amr=mfa is redirected to /account/mfa/setup by the library's forced-step middleware, independent of MfaOptions.RequireForAdmin.

Email invitations (M.AUTH-T35, 9.0.0)

An organization admin invites people by email; the invitee sets a password through the library's own page, the way a password reset works. The same AddMindAtticOrganizations call registers it, and AuthInvitations joins the opt-in model (ApplyMindAtticOrganizationConfiguration; OrganizationModelFingerprint is "auth-org-v2", so add a migration).

Use

  1. Your accept page renders <MaAcceptInvitation Token="@token" Error="@error" /> (default path /account/accept-invite, configurable as Invitations:AcceptPath; keep it under /account so the library's CSP nonce and forced-step exclusions apply). ?token= and ?error=1 are the query parameters.
  2. Set an absolute Organizations:Invitations:PublicBaseUrl (falls back to Reset:PublicBaseUrl). Links are never derived from the request host; with no absolute base URL invitations are refused.
  3. Call IInvitationService: InviteAsync(org, email, role, invitedBy, actingRole), InviteBulkCsvAsync (rows of email[,role], optional header, blank and # lines skipped, MaxBulkRows default 200), ResendAsync, RevokeAsync, ListAsync. Delivery goes through IAuthEmailSender.SendInvitationAsync (default implemented on top of SendSecurityAlertAsync, so an existing host sender keeps compiling; the SMTP and logging senders override it, and the logging sender prints the link in development).

Security properties

  • Token: 256-bit CSPRNG, base64url in the link, stored only as HMAC-SHA256 under the existing reset-token-key Vault secret with an invite: domain prefix (no new secret). Single-use: acceptance claims the row with one conditional UPDATE ... WHERE ConsumedUtc IS NULL (rows-affected check), so concurrent redemptions yield one winner. Expiry (TtlHours, default 72) runs from each send; resending issues a fresh token and the old link stops working.
  • Anti-enumeration: creating or re-sending an invitation gives the inviter the same outcome whether or not the address already has an account. On the accept side every failure (unknown, used, revoked, expired, wrong account, policy-rejected username) returns one generic message and the endpoint applies the uniform timing floor.
  • Caps: per invitation MaxSendsPerInvitation (5) and MinResendIntervalSeconds (60); per organization MaxInvitationsPerOrganizationPerHour (500); bulk MaxBulkRows.
  • No auto-login: like reset, the invitee signs in fresh. The new account is created with the chosen password and EmailVerified; if the role requires MFA (MfaRequiredRoles) MustEnrollMfa is set, so the first sign-in is routed to MFA setup.
  • Existing accounts: an address that already has an account is never given a second one or a password. The page asks the holder to sign in; AcceptExistingAsync (endpoint /_ma-auth/invite/accept-existing, requires sign-in) accepts only for the account whose email matches the invitation, adds the membership, rotates the stamp, and signs the session out so the new membership is on the next cookie.
  • Audit: AuthOrganizationAudit rows (invite.create, invite.resend, invite.revoke, invite.accept) hold a masked address and the role; AuthAuditLog gets AuthEventType.Invitation success and failure rows with IP and user agent.

Endpoints

POST /_ma-auth/invite/accept (token, optional userName, newPassword) redirects to /login?invite=ok, or back to the accept page with ?error=1. POST /_ma-auth/invite/accept-existing (token) requires authorization. Both validate antiforgery.

From MindAttic.Authentication/docs/ORGANIZATIONS.md via MindAttic.Docs; synced automatically, so edit the repo, not this page.