MindAttic.Authentication/ORGANIZATIONS
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
- Your
DbContextimplementsIOrganizationDataContext(it already implementsIAuthDataContext):public DbSet<AuthOrganization> AuthOrganizations => Set<AuthOrganization>(); public DbSet<AuthMembership> AuthMemberships => Set<AuthMembership>(); public DbSet<AuthOrganizationAudit> AuthOrganizationAudit => Set<AuthOrganizationAudit>();
- In
OnModelCreating:b.ApplyMindAtticAuthConfiguration(organizations: true);(or callApplyMindAtticOrganizationConfiguration()yourself), then add a migration. Tables (schemaauth):AuthOrganizations,AuthMemberships(unique on organization + user; FK to the organization and, cascading, toAuthUsers),AuthOrganizationAudit.AuthModel.OrganizationModelFingerprintis"auth-org-v1". - In
Program.cs, afterAddMindAtticAuthentication: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
- Your accept page renders
<MaAcceptInvitation Token="@token" Error="@error" />(default path/account/accept-invite, configurable asInvitations:AcceptPath; keep it under/accountso the library's CSP nonce and forced-step exclusions apply).?token=and?error=1are the query parameters. - Set an absolute
Organizations:Invitations:PublicBaseUrl(falls back toReset:PublicBaseUrl). Links are never derived from the request host; with no absolute base URL invitations are refused. - Call
IInvitationService:InviteAsync(org, email, role, invitedBy, actingRole),InviteBulkCsvAsync(rows ofemail[,role], optional header, blank and#lines skipped,MaxBulkRowsdefault 200),ResendAsync,RevokeAsync,ListAsync. Delivery goes throughIAuthEmailSender.SendInvitationAsync(default implemented on top ofSendSecurityAlertAsync, 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-keyVault secret with aninvite:domain prefix (no new secret). Single-use: acceptance claims the row with one conditionalUPDATE ... 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) andMinResendIntervalSeconds(60); per organizationMaxInvitationsPerOrganizationPerHour(500); bulkMaxBulkRows. - 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)MustEnrollMfais 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:
AuthOrganizationAuditrows (invite.create,invite.resend,invite.revoke,invite.accept) hold a masked address and the role;AuthAuditLoggetsAuthEventType.Invitationsuccess 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.