Accounts, Sessions and Sign-in
Serenity.Extensions has a set of account services that the StartSharp template builds its membership pages on: policies that
decide who may sign in with a password, requirements that keep a user on a setup page until it is done, account events that
record and email the changes of an account, sessions that tie the sign-in cookies to records that can be ended, and
invitations. They are small abstractions in the Serenity.Extensions namespace, so an application can replace or extend
each of them; Serenity.Pro.Extensions provides the stores, the pages and the settings that the StartSharp template uses,
and the template registers them in Startup.cs.
The pages that change the security of an account are also the ones that are not available while a user is impersonated, see Impersonation.
Who Can Sign In With a Password
A sign-in with a password can be refused after the password is checked, for a reason that has nothing to do with the
password itself, e.g. an account that signs in with an external provider, whose password would get around the multi-factor
authentication of the provider. IPasswordSignInPolicy decides this:
public class MyPasswordSignInPolicy : IPasswordSignInPolicy
{
public string? GetDenial(IUserDefinition user)
{
return (user as UserDefinition)?.Source == "ldap" ? "This account signs in with the directory." : null;
}
}
// Startup.cs
services.TryAddEnumerable(ServiceDescriptor.Singleton<IPasswordSignInPolicy, MyPasswordSignInPolicy>());
A sign-in page asks the policies after the password is valid, with ValidatePasswordSignIn, which throws a ValidationError
with the PasswordSignInDeniedCode ("PasswordSignInDenied") code and the message of the first denial:
HttpContext.RequestServices.ValidatePasswordSignIn(username!);
GetPasswordSignInDenial(username) returns the message instead, for code that wants to show it in another way. Both live in
PasswordSignInPolicyExtensions.
The sign-in page of StartSharp and the password grant of its OpenID server call them. The sign-in page of Serene does not,
so a policy registered there has no effect until its Login action calls ValidatePasswordSignIn.
Token Endpoints
The password grant of a token endpoint can't ask for a two-factor code, nor send the user to a page that sets something up,
so a password alone should not get a token for such a user. IPasswordGrantPolicy refuses those; the sign-in policies are
asked first, as anything that refuses a sign-in with the password refuses a token too:
var denial = HttpContext.RequestServices.GetPasswordGrantDenial(username);
if (denial != null)
return new BadRequestResult(); // e.g. an invalid_grant with this error_description
GetPasswordGrantDenial
asks the IPasswordSignInPolicys, then the IPasswordGrantPolicys, and returns the first denial.
AddAccountSetup() registers AccountSetupPasswordGrantPolicy, and the two-factor feature of Pro registers
TwoFactorPasswordGrantPolicy, so AddAccountSetup() and AddTwoFactorAuth() are enough for the common cases.
A policy can check two-factor authentication without depending on its implementation, through
ITwoFactorStatus
(IsActiveFor(username)).
Account Setup
Some users must do something before they can use the application, e.g. change a password that an administrator set, or set up two-factor authentication. An IAccountSetupRequirement says what, and AccountSetupFilter keeps the user on the page that does it:
services.AddAccountSetup(); // the filter, PasswordChangeRequirement and the password grant policy
- A page redirects to the
SetupUrlof the first requirement the user must do, ordered byOrder. - A service fails with the
AccountSetupRequiredcode (AccountSetupFilter.SetupRequiredCode), whose error arguments are the path of that page, which a page handles by going there. - An action or a controller with AllowDuringAccountSetup can still be used, e.g. the password and two-factor pages, the confirmation of the password, and signing in and out.
- It is checked on each request, so a requirement applies at once, and ends when it is done.
An application adds its own requirements, e.g. to accept the terms of use:
public class AcceptTermsRequirement : IAccountSetupRequirement
{
public int Order => 30;
public string SetupUrl => "~/Account/AcceptTerms";
public bool IsRequired(ClaimsPrincipal user) => /* fast, e.g. from the cached user definition */;
public string GetMessage(ITextLocalizer localizer) => localizer.TryGet("Site.Account.AcceptTermsRequired")!;
}
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAccountSetupRequirement, AcceptTermsRequirement>());
AddAccountSetup() also registers PasswordChangeRequirement,
which requires a password change for the users whose definitions say so, for the sign-ins with the password (an external
provider has no password of the application to change). That means the user definition implements
IHasPasswordChangeRequired, and the
user row implements IPasswordChangeRequiredRow,
so the flag is cleared when the password is changed or reset, by AccountPasswordActionsPageBase. StartSharp adds a nullable
PasswordChangeRequired column to Users for this.
Account Events
An IAccountEventPublisher tells the IAccountEventHandlers about what happened to an account, so the user can be emailed about a change that the user did not make, and the changes can be logged:
services.AddAccountEvents(); // the publisher and the email handler
- An event has a kind (AccountEventKind), the
user, who did it (
ActorUserId,ActorUsername), when, and from where (IPAddress,UserAgent), plus what the kind needs:OldValue/NewValue(e.g. an old and a new email address),Method(e.g."Password"or the name of an external provider), andReason(e.g. why a sign-in failed). - The kind covers the changes (password, email, username, two-factor methods, reset of the two-factor authentication), the
sign-ins (
SignedIn,SignInFailed,SignedOut), the confirmations (Elevated,ElevationFailed),PasswordResetRequested,SessionsRevoked,ImpersonationStarted/ImpersonationEndedand the invitations. Publishfills what the event leaves out and tells the handlers when the unit of work is committed, so a change that rolls back is not announced. The user is read after the commit, as reading it inside the transaction can wait on the row lock of the change. An exception of a handler is logged and does not undo the change.
accountEvents.Publish(new AccountEvent { Kind = AccountEventKind.PasswordChanged, UserId = userId }, uow);
services.AddSingleton<IAccountEventHandler, MyAccountChangeLog>(); // an application adds its own handlers
The sign-in events have convenience methods in
SignInEventExtensions: PublishSignIn,
PublishSignInFailed (with a SignInFailureReasons reason, or a PasswordValidationResult) and PublishSignOut. A failed
sign-in with a username that no user has is published without it, as it may be a password typed in the wrong box.
Emails About the Changes
AddAccountEvents() also registers AccountEventEmailHandler,
which emails the user only about the changes of the account (IsEmailed), not about the sign-ins, and sends the email of
a changed address to the old one. The AccountEventEmails section turns it off or leaves some kinds out:
"AccountEventEmails": {
"Enabled": true,
"Skip": "UsernameChanged"
}
The email is the Membership/AccountEvents/AccountEventEmail.cshtml view of the Serenity.Extensions area, which an
application replaces with a view of the same path, and its texts are under Emails.AccountEvent.. A kind can have a view of
its own, e.g. AccountEventEmail.PasswordChanged.cshtml, which GetViewName prefers.
StartSharp stores the events in the acc_Events table with AddAccountEventLog(), with the AccountEventLog settings
(RetentionDays, ViewPermission), and lists them on the activity tabs of the user management page, see
Sign-in Log and Account Activity.
The Emails of the Account
The password reset, account change, activation, invitation and two-factor code emails share a layout,
~/Areas/Serenity.Extensions/Shared/_EmailLayout.cshtml, with the title of the site, the content in a box, a button for the
link (_EmailButton, EmailButtonModel) and the signature. It uses tables and inline styles, as email clients ignore style
sheets. An application changes the look of all of them with a view of the same path in its own project.
An email that code builds is an EmailMessageModel
(greeting, paragraphs, a code, a button, notes), rendered by an IEmailMessageRenderer. AddEmailSender() registers
RazorEmailMessageRenderer, which uses the EmailMessage view; without it, BasicEmailMessageRenderer renders simple HTML.
The texts are localizable (ResetPasswordEmailTexts, EmailLayoutTexts, AccountEventEmailTexts, the ActivateEmail* texts
of SignUpFormTexts), and AccountPasswordActionsPageBase.ResetPasswordTokenLifetime (3 hours), which a subclass of the
page overrides, decides how long a password reset link works, which the email tells.
Sessions
A sign-in cookie used to be valid until it expired, so a password change, a sign-out elsewhere, or a deactivated user could
not end it early. AddAccountSessions() ties the sign-in cookies of the default cookie scheme to sessions:
services.AddAccountSessions();
- A sign-in starts a session whose ID the cookie carries as a claim (AccountSessionClaimTypes.SessionId).
- The session is checked at most every
AccountSessions:ValidationMinutes(1), and a cookie of a session that ended, or of a user who is no longer active, is signed out. A cookie issued before the sessions adopts one on its next check, so nobody is signed out by the upgrade. - A sign-out ends the session, and a password change ends the other sessions of the user, or all of them when an administrator or a reset link sets the password. A reset of the two-factor authentication by an administrator ends all of them too (AccountSessionEventHandler).
- The sign-in cookie events do the work, so no sign-in code changes. An application that gives the cookie events as a type
(
EventsType) callsAccountSessionCookieValidatorfrom them instead.
The AccountSessionOptions come from the
AccountSessions section:
| Setting | Default | Meaning |
|---|---|---|
Enabled |
true |
Tracks and checks the sessions. |
ValidationMinutes |
1 |
How often a cookie's session is checked. |
IdleMinutes |
the cookie expiration | When a session that was not used is no longer listed as active. |
Concurrent |
Allow |
SignOutOthers lets a user have one session only: a new sign-in ends the others. |
RetentionDays |
90 |
How long the sessions that ended are kept. 0 keeps them forever. |
The sessions are stored by an IAccountSessionStore that the application registers; without one, nothing changes.
StartSharp registers the acc_Sessions table with AddAccountSessionStore(). The pages use
IAccountSessionManager to list the active
sessions of a user (ListActive) and end one (End) or all but one (EndAll), which records why on the session with an
AccountSessionEndReason and publishes AccountEventKind.SessionsRevoked. With an IAccountTokenRevoker, ending the
sessions for security also revokes the tokens of the user, e.g. the ones that the OpenID server gave to the apps.
Invitations and Sign-up
Instead of creating an account and choosing a password for someone, an administrator can invite the person by email.
IInvitationManager holds the invitation's email address, name and roles, and its link, whose token is stored only hashed;
the link works once, until it expires, or is sent again or revoked:
| Member | Purpose |
|---|---|
Invite(InvitationDraft) |
Sends an invitation, after the policies allow it. |
Resend(id) |
Sends it again with a new link, so the old one no longer works. |
Revoke(id) |
Makes its link stop working. |
Delete(ids) |
Deletes the accepted, revoked and expired invitations, revoking a pending one first; returns how many. |
FindPending(token) |
Gets the invitation of a link that can still be accepted. |
Accept(token, userId, uow) |
Accepts it for the user the application creates, and gives the roles the inviter can still give. |
Who can invite whom, with which roles, is decided by the IInvitationPolicys: a denial of any wins, else at least one must allow it, so nothing is invited unless a policy says so:
public class TeacherInvitationPolicy(IPermissionService permissions) : IInvitationPolicy
{
private const string StudentRoleId = "5";
public InvitationDecision Check(ClaimsPrincipal inviter, InvitationDraft invitation, out string? reason)
{
reason = null;
return permissions.HasPermission("School:InviteStudents") && invitation.RoleIds.All(x => x == StudentRoleId) ?
InvitationDecision.Allow : InvitationDecision.Abstain;
}
}
StartSharp registers the manager, its store and the default policy with AddInvitations() of Serenity.Pro.Extensions,
which also has the InvitationEndpoint (~/Services/Serenity.Pro.Invitation/...) that the user management page calls.
The default policy lets the holders of Invitations:Permission (Administration:Invite) invite with the roles whose
permissions they could grant
(IRoleGrantedPermissionsProvider).
Whichever policy allows an invitation, the manager asks for the password confirmation when one of its roles has a sensitive
permission. The invitation is accepted on the sign-up page, with a password or an external login of the same verified address.
"Invitations": {
"Enabled": true,
"Permission": "Administration:Invite",
"ExpirationDays": 7
}
Enabled: false turns the invitations off, and the links already sent stop working. An address that a user has, or that
has a pending invitation, can't be invited again (a validation error); the pending invitation can be sent again with
Resend instead, which the Invitations view of the user management page does.
MembershipSettings.SignUp
(Membership:SignUp) tells who can sign up with a password or an external login:
Open (anyone, the default), InvitationOnly (only the invited ones), or Closed (nobody). The sign-up page of
StartSharp, also for the external logins, and the sign-up link of its sign-in page follow it; the sign-up page of Serene
does not read it.
My Account (StartSharp)
The pages where the users manage how they sign in are collected on a My account page, which lists the links that the
features give through IMyAccountLinkProviders. The page (MyAccountPageBase) and AddMyAccount() come from
Serenity.Pro.Extensions; MyAccountLink and IMyAccountLinkProvider are in Serenity.Extensions, so a feature can add its
links without depending on Pro. Serene has no My account page.
services.AddMyAccount(); // the password link; the page is a controller of the template
A MyAccountLink has a title, a description, an
icon, a URL and an optional state (e.g. whether two-factor authentication is on, or required and not set up). StartSharp adds
the links of the two-factor authentication (AddTwoFactorAuth()) and of the external logins
(AddExternalAuthentication()), and lists the user's own recent activity on the page.
See Also
- Authentication & Authorization — users, permissions, elevation and impersonation
- Web Security — account rate limiting and data-protector tokens
- Account Elevation — the StartSharp elevation page
- Two Factor Authentication
- Login As User