I'm using MVC5 Identity 2.0 for users to log into my website, where the authentication details are stored in an SQL database. Asp.net Identity has been implemented in a standard way as can be found in many online tutorials.
The ApplicationUser class in IdentityModels has been extended to include some custom properties, such as an integer OrganizationId. The idea is that many users can be created and assigned to a common Organization for database relationship purposes.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extended Properties
public DateTime? BirthDate { get; set; }
public long? OrganizationId { get; set; }
//Key Mappings
[ForeignKey("OrganizationId")]
public virtual Organization Organization { get; set; }
}
How can I retrieve the OrganizationId property of the currently logged in user from within a controller? Is this available via a method once a user is logged in or do I always have the retrieve the OrganizationId from the database, based on the UserId, every time a controller method executes?
Reading around on the web I have seen I need to use the following to get the logged in UserId etc.
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
However, OrganizationId is not a property available in User.Identity. Do I need to extend User.Identity to include the OrganizationId property? If so, how do I go about this.
The reason I need the OrganizationId so often is that many table queries are reliant on the OrganizationId to retrieve data relevant to the Organization that's associated to the logged in user.
I was looking for the same solution and Pawel gave me 99% of the answer. The only thing that was missing that I needed for the Extension to display was adding the following Razor Code into the cshtml(view) page:
@using programname.Models.Extensions
I was looking for the FirstName, to display in the top right of my NavBar after the user logged in.
I thought I would post this incase it helps someone else, So here is my code:
I created a new folder called Extensions(Under my Models Folder) and created the new class as Pawel specified above:
IdentityExtensions.cs
IdentityModels.cs
:Then in my
_LoginPartial.cshtml
(UnderViews/Shared
Folders) I added@using.ProgramName.Models.Extensions
I then added the change to the folling line of code that was going to use the Users First name after Logging in :
@Html.ActionLink("Hello " + User.Identity.GetUserFirstname() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
Perhaps this helps someone else down the line.
For anyone that finds this question looking for how to access custom properties in ASP.NET Core 2.1 - it's much easier: You'll have a UserManager, e.g. in _LoginPartial.cshtml, and then you can simply do (assuming "ScreenName" is a property that you have added to your own AppUser which inherits from IdentityUser):
I also had added on or extended additional columns into my AspNetUsers table. When I wanted to simply view this data I found many examples like the code above with "Extensions" etc... This really amazed me that you had to write all those lines of code just to get a couple values from the current users.
It turns out that you can query the AspNetUsers table like any other table:
Check out this great blog post by John Atten: ASP.NET Identity 2.0: Customizing Users and Roles
It has great step-by-step info on the whole process. Go read it : )
Here are some of the basics.
Extend the default ApplicationUser class by adding new properties (i.e.- Address, City, State, etc.):
Then you add your new properties to your RegisterViewModel.
Then update the Register View to include the new properties.
Then update the Register() method on AccountController with the new properties.
Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:
Then what you need is to create an extension method like so (I create mine in an new Extensions folder):
When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:
Once you added the claim and have your extension method in place, to make it available as a property on your User.Identity, add a using statement on the page/file you want to access it:
in my case:
using App.Extensions;
within a Controller and@using. App.Extensions
withing a .cshtml View file.EDIT:
What you can also do to avoid adding a using statement in every View is to go to the Views folder, and locate the Web.config file in there. Now look for the
<namespaces>
tag and add your extension namespace there like so:Save your file and you're done. Now every View will know of your extensions.
You can access the Extension Method:
Hope that helps anyone :)
Dhaust gives a good way to add the property to the ApplicationUser class. Looking at the OP code it appears they may have done this or were on track to do that. The question asks
Pawel gives a way to add an extension method that requires using statements or adding the namespace to the web.config file.
However, the question asks if you "need to" extend User.Identity to include the new property. There is an alternative way to access the property without extending User.Identity. If you followed Dhaust method you can then use the following code in your controller to access the new property.