I am implementing 2FA for users in Umbraco 8 and after logging in but before entering a code, I need to do some check ups. For this check up I need to know which user is logged in and I cannot figure out how I can get to know which user is logged in.
After a user is logged in in the backoffice, I show a html template, which is made possible by this line of code:
public string GetTwoFactorView(IOwinContext owinContext, UmbracoContext umbracoContext, string username) =>
PackageConstants.PathToMfaHtmlTemplate;
The template is linked to an angularjs controller:
<div ng-controller="mfaLoginController" class="umb-login-container">
//...
</div>
In my controller I got access to the services:
userService
authResource
but both doesn't seem to have the user data in it. Is there another service I can inject here which can provide me the user data?
From this controller I need to make API calls to an Umbraco API:
[IsBackOffice, PluginController("LoginMfa")]
public class MfaLoginApiController : UmbracoApiController
{
//...
}
In an endpoint I have managed to retrieve the OWIN TwoFactorCookie with the next line of code:
var mfaCookie = Request.Headers.GetCookies(".AspNet.UmbracoTwoFactorCookie").FirstOrDefault()
.Cookies.FirstOrDefault(cookie => cookie.Name == ".AspNet.UmbracoTwoFactorCookie").Value;
This returns a what looks like encrypted string. Is there a way to decrypt this string and get the user data (user Id is enough) from this cookie, if it is stored in this cookie at all?
Or is there a better way to retrieve the user at this point?
I figured it out. While investigating a possible different solution for my problem, I saw the next code in AuthenticatorController of Umbraco (very nice it is open source):
private BackOfficeSignInManager _signInManager;
private BackOfficeSignInManager SignInManager => _signInManager ?? (_signInManager = TryGetOwinContext().Result.GetBackOfficeSignInManager());
Fortunately, I am able to use this code too in my API controller and this line of code gave me what I need.
var userId = await SignInManager.GetVerifiedUserIdAsync();