MvcOverWebApi
MvcOverWebApi copied to clipboard
How to get username in mvc?
Hi, first of all, thanks for putting this exampple solution on github. I implemented it in my own project because I want to have the same architecture... WEB.API with all the main logic and then MVC as UI for this, with possible alternative UI apps like native mobile apps which also communicate with WEB.API.
But to be honest the MS Identity system, owin and these thinks are kind of new and confusing to me... I am not sure I understand the magic completely how you authorize user in mvc, keep him authorized and also in WEB API...
Anyway my main question is.. how can I get user's email (=login) in MVC application, when the User.Identity.Name is the token...
Hello Urza,
Following would work.
public static string GetUserName() { string userName = string.Empty;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var cookie = HttpContext.Current.Request.Cookies.Get("YetAnotherTodo.WebApi.Auth").Value;
var decodedData = TextEncodings.Base64Url.Decode(cookie);
// byte[] protectedData = MachineKey.Protect(userData, new[] { "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware", DefaultAuthenticationTypes.ApplicationCookie, "v1" });
var unprotectedData = MachineKey.Unprotect(decodedData, new[] { "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware",
DefaultAuthenticationTypes.ApplicationCookie, "v1" });
var deserializedData = DataSerializers.Ticket.Deserialize(unprotectedData);
userName = deserializedData.Identity.Claims.FirstOrDefault(item => item.Type == ClaimTypes.Name).Value;
}
return userName;
}
But I am not sure whether this is the right way of doing it or not.
Thanks.
You could add a custom ActionFilter in the MVC project which would fetch additional user data from the API when a user is authenticated and replace the User with another ClaimsPrincipal. But because you don't want to fetch that data on each web request, you could cache it in the session store. Just keep in mind that you need to refresh or clear that cached data again when a user changes his/her profile.
A better way is to reimplement the authentication and add more claims when creating the authentication cookie (and to use a different method, say JWT tokens). But rather than implementing this yourself, take a look at https://identityserver.github.io/Documentation/docsv2/overview/mvcGettingStarted.html