Umbraco users and members support a two-factor authentication (2FA) abstraction for implementing a 2FA provider of your choice.
Two-factor authentication (2FA) for Umbraco members is activated by implementing an ITwoFactorProvider interface and registering the implementation. The implementation can use third-party packages to archive for example support for authentication apps like Microsoft- or Google Authentication App.
Since Umbraco does not control how the UI is for member login and profile edit, the UI for 2FA is shipped as part of the snippets for macros. These can be used as a starting point, before styling the page as you would like.
Example implementation for Authenticator Apps for Members
In the following example, we will use the GoogleAuthenticator NuGet Package. Despite the name, this package works for both Google and Microsoft authenticator apps and can be used to generate the QR code needed to activate the app for the website.
usingSystem;usingSystem.Threading.Tasks;usingGoogle.Authenticator;usingUmbraco.Cms.Core.Security;usingUmbraco.Cms.Core.Services;namespaceMy.Website;/// <summary>/// Model with the required data to setup the authentication app./// </summary>publicclassQrCodeSetupData{ /// <summary> /// The secret unique code for the user and this ITwoFactorProvider. /// </summary>publicstring Secret { get; init; } /// <summary> /// The SetupCode from the GoogleAuthenticator code. /// </summary>publicSetupCode SetupCode { get; init; }}/// <summary>/// App Authenticator implementation of the ITwoFactorProvider/// </summary>publicclassUmbracoAppAuthenticator:ITwoFactorProvider{ /// <summary> /// The unique name of the ITwoFactorProvider. This is saved in a constant for reusability. /// </summary>publicconststring Name ="UmbracoAppAuthenticator";privatereadonlyIMemberService _memberService; /// <summary> /// Initializes a new instance of the <seecref="UmbracoAppAuthenticator"/> class. /// </summary>publicUmbracoAppAuthenticator(IMemberService memberService) { _memberService = memberService; } /// <summary> /// The unique provider name of ITwoFactorProvider implementation. /// </summary> /// <remarks> /// This value will be saved in the database to connect the member with this ITwoFactorProvider. /// </remarks>publicstring ProviderName => Name; /// <summary> /// Returns the required data to setup this specific ITwoFactorProvider implementation. In this case it will contain the url to the QR-Code and the secret.
/// </summary> /// <paramname="userOrMemberKey">The key of the user or member</param> /// <paramname="secret">The secret that ensures only this user can connect to the authenticator app</param> /// <returns>The required data to setup the authenticator app</returns>publicTask<object> GetSetupDataAsync(Guid userOrMemberKey,string secret) {var member =_memberService.GetByKey(userOrMemberKey);var twoFactorAuthenticator =newTwoFactorAuthenticator(); SetupCode setupInfo = twoFactorAuthenticator.GenerateSetupCode("My application name", member.Username, secret, false);
returnTask.FromResult<object>(newQrCodeSetupData() { SetupCode = setupInfo, Secret = secret }); } /// <summary> /// Validated the code and the secret of the user. /// </summary>publicboolValidateTwoFactorPIN(string secret,string code) {var twoFactorAuthenticator =newTwoFactorAuthenticator();returntwoFactorAuthenticator.ValidateTwoFactorPIN(secret, code); } /// <summary> /// Validated the two factor setup /// </summary> /// <remarks>Called to confirm the setup of two factor on the user. In this case we confirm in the same way as we login by validating the PIN.</remarks>
publicboolValidateTwoFactorSetup(string secret,string token) =>ValidateTwoFactorPIN(secret, token);}
First, we create a model with the information required to set up the 2FA provider and then we implement the ITwoFactorProvider with the use of the TwoFactorAuthenticator from the GoogleAuthenticator NuGet package.
Now we need to register the UmbracoAppAuthenticator implementation. This can be done on the IUmbracoBuilder in your startup or a composer.
At this point, the 2FA is active, but no members have set up 2FA yet. The setup of 2FA depends on the type. In the case of App Authenticator, we will add the following to our view showing the edit profile of the member.
@using Umbraco.Cms.Core.Services@using Umbraco.Cms.Web.Website.Controllers@using Umbraco.Cms.Web.Website.Models@using My.Website @* Or whatever your namespacewiththeQrCodeSetupDatamodelis *@@injectMemberModelBuilderFactorymemberModelBuilderFactory@injectITwoFactorLoginServicetwoFactorLoginService@{ // Build a profile model to edit var profileModel = await memberModelBuilderFactory .CreateProfileModel() .BuildForCurrentMemberAsync(); // Show all two factor providers var providerNames = twoFactorLoginService.GetAllProviderNames(); if (providerNames.Any()) { <div asp-validation-summary="All" class="text-danger"></div> foreach (var providerName in providerNames) {var setupData =awaittwoFactorLoginService.GetSetupInfoAsync(profileModel.Key, providerName);if (setupData is null) { @using (Html.BeginUmbracoForm<UmbTwoFactorLoginController>(nameof(UmbTwoFactorLoginController.Disable)))
{<input type="hidden" name="providerName" value="@providerName"/><button type="submit">Disable @providerName</button> } }elseif(setupData is QrCodeSetupData qrCodeSetupData) { @using (Html.BeginUmbracoForm<UmbTwoFactorLoginController>(nameof(UmbTwoFactorLoginController.ValidateAndSaveSetup)))
{<h3>Setup @providerName</h3><img src="@qrCodeSetupData.SetupCode.QrCodeSetupImageUrl"/> <p>Scan the code above with your authenticator app <br /> and enter the resulting code here to validate:</p>
<input type="hidden" name="providerName" value="@providerName"/><input type="hidden" name="secret" value="@qrCodeSetupData.Secret"/><input type="text" name="code"/><button type="submit">Validate & save</button> } } } }}
In this razor-code sample, we get the current member's unique key and list all registered ITwoFactorProvider implementations.
If the setupData is null for the specified providerName it means the provider is already set up. In this case, we show a disable button. Otherwise, we check the type and show the UI for how to set up the App Authenticator, by showing the QR Code and an input field to validate the code from the App Authenticator.
The last part required is to use the Login Partial Macro snippet.
Notification when 2FA is requested for a member
When a 2FA login is requested for a member, the MemberTwoFactorRequestedNotification is published. This notification can also be used to send the member a one-time password via e-mail or phone. Even though these 2FA types are not considered secure as App Authentication, it is still a massive improvement compared to no 2FA.
Two-factor authentication for Users
Umbraco controls how the UI is for user login and user edits, but will still need a view for configuring each 2FA provider.
Example implementation for Authenticator Apps for Users
In the following example, we will use the GoogleAuthenticator NuGet Package. Despite the name, this package works for both Google and Microsoft authenticator apps and can be used to generate the QR code needed to activate the app for the website.
usingSystem.Runtime.Serialization;usingGoogle.Authenticator;usingUmbraco.Cms.Core.Models.Membership;usingUmbraco.Cms.Core.Security;usingUmbraco.Cms.Core.Services;namespaceMy.Website;[DataContract]publicclassTwoFactorAuthInfo{ [DataMember(Name ="qrCodeSetupImageUrl")]publicstring? QrCodeSetupImageUrl { get; set; } [DataMember(Name ="secret")]publicstring? Secret { get; set; }}/// <summary>/// App Authenticator implementation of the ITwoFactorProvider/// </summary>publicclassUmbracoUserAppAuthenticator:ITwoFactorProvider{privatereadonlyIUserService _userService; /// <summary> /// The unique name of the ITwoFactorProvider. This is saved in a constant for reusability. /// </summary>publicconststring Name ="UmbracoUserAppAuthenticator"; /// <summary> /// Initializes a new instance of the <seecref="UmbracoUserAppAuthenticator"/> class. /// </summary>publicUmbracoUserAppAuthenticator(IUserService userService) { _userService = userService; } /// <summary> /// The unique provider name of ITwoFactorProvider implementation. /// </summary> /// <remarks> /// This value will be saved in the database to connect the member with this ITwoFactorProvider. /// </remarks>publicstring ProviderName => Name; /// <summary> /// Returns the required data to setup this specific ITwoFactorProvider implementation. In this case it will contain the url to the QR-Code and the secret.
/// </summary> /// <paramname="userOrMemberKey">The key of the user or member</param> /// <paramname="secret">The secret that ensures only this user can connect to the authenticator app</param> /// <returns>The required data to setup the authenticator app</returns>publicTask<object> GetSetupDataAsync(Guid userOrMemberKey,string secret) {IUser? user =_userService.GetByKey(userOrMemberKey);ArgumentNullException.ThrowIfNull(user);var twoFactorAuthenticator =newTwoFactorAuthenticator(); SetupCode setupInfo = twoFactorAuthenticator.GenerateSetupCode("My application name", user.Username, secret, false);
returnTask.FromResult<object>(newTwoFactorAuthInfo() { QrCodeSetupImageUrl =setupInfo.QrCodeSetupImageUrl, Secret = secret }); } /// <summary> /// Validated the code and the secret of the user. /// </summary>publicboolValidateTwoFactorPIN(string secret,string code) {var twoFactorAuthenticator =newTwoFactorAuthenticator();returntwoFactorAuthenticator.ValidateTwoFactorPIN(secret, code); } /// <summary> /// Validated the two factor setup /// </summary> /// <remarks>Called to confirm the setup of two factor on the user. In this case we confirm in the same way as we login by validating the PIN.</remarks>
publicboolValidateTwoFactorSetup(string secret,string token) =>ValidateTwoFactorPIN(secret, token);}
First, we create a model with the information required to set up the 2FA provider and then we implement the ITwoFactorProvider with the use of the TwoFactorAuthenticator from the GoogleAuthenticator NuGet package.
Now we need to register the UmbracoUserAppAuthenticator implementation and the view to show to set up this provider. This can be done on the IUmbracoBuilder in your startup or a composer.
!(function () {"use strict";constgoogleTwoFactorProviderCtrl= ['$scope','twoFactorLoginResource','notificationsService',function ($scope, twoFactorLoginResource, notificationsService) {constvm=this;vm.title ="Setup Google Authenticator on "+$scope.model?.user?.name;vm.providerName =$scope.model?.providerName;vm.qrCodeImageUrl ="";vm.secret ="";vm.code ="";vm.authForm = {};vm.buttonState ="init";vm.close = close;vm.validateAndSave = validateAndSave;functioninit() {vm.buttonState ="init";twoFactorLoginResource.setupInfo(vm.providerName).then(function (response) {// This response is the model I defined to be returned from ITwoFactorProvider.GetSetupDataAsyncvm.qrCodeImageUrl =response.qrCodeSetupImageUrl;vm.secret =response.secret; }).catch(function () {notificationsService.error("Could not fetch login info"); }); }functionvalidateAndSave() {vm.authForm.token.$setValidity("token",true);vm.buttonState ="busy";twoFactorLoginResource.validateAndSave(vm.providerName,vm.secret,vm.code).then(function (successful) {if (successful) {notificationsService.success("Two-factor authentication has successfully been enabled");vm.buttonState ="success";close(); } else {vm.authForm.token.$setValidity("token",false);vm.buttonState ="error"; } }).catch(function (error) {notificationsService.error(error);vm.buttonState ="error"; }); }functionclose() {if ($scope.model.close) {$scope.model.close(); } }init(); } ];angular.module("umbraco").controller("CustomCode.TwoFactorProviderGoogleAuthenticator", googleTwoFactorProviderCtrl);})();
At this point, the 2FA is active, but no users have set up 2FA yet.
Each user can now enable the configured 2fa providers on their user. This can be done from the user panel by clicking the user avatar.
User panel
When clicking the Configure Two-Factor button, a new panel is shown, listing all enabled two-factor providers.
Configure 2fa
When clicking Enable on one of these, the configured view for the specific provider will be shown
Enable 2fa
When the authenticator is enabled correctly, a disable button is shown instead.
Disable 2fa
To disable the two-factor authentication on your user, it is required to enter the verification code, otherwise, admins are allowed to disable providers on other users.
Verify disable
While the 2FA is enabled, the user will be presented with this screen after entering the username and password.
Notification when 2FA is requested for a user
When a 2FA login is requested for a user, the UserTwoFactorRequestedNotification is published. This notification can also be used to send the user a one-time password via e-mail or phone, even though these 2FA types are not considered secure as App Authentication, it is still a massive improvement compared to no 2FA.