I have a system that uses the built in Identity system to authenticate users for the admin section.
I want to let other users login through external web service but was wondering if I could create a different user class for them and still take advantage of built in functionality such as [Authorize] attribute.
Let's say the custom class looks like this:
public class CustomUser
{
public string Name { get; set; }
public string Ssn { get; set; }
}
I would add this user to a role, for example "customUser" so in a controller I would like to use the authorize attribute like this:
[Authorize(Roles="customUser")]
public ActionResult DoStuff()
{
// do stuff
}
Is this possible, have a custom user class and manually authenticate him?
Sure. Just inherit from ApplicationUser
(or whatever you named your IdentityUser
derived class):
public class CustomUser : ApplicationUser
{
public string Name { get; set; }
public string Ssn { get; set; }
}
However, you can't use it directly with Authorize
like your sample code suggests. You would either need to:
Do a custom check in your action to verify the user type.
Add a role to the user and authorize via that custom role.
Create a custom AuthorizeAttribute
that checks that the user is the right type
UPDATE
When you inherit from ApplicationUser
you won't get a separate table. EF will add a Discriminator
column to dbo.AspNetUsers
, which will have the value of either "ApplicationUser" or "CustomUser", depending on which was saved. EF will then use this column to instantiate the appropriate class when you query users from the database.
One thing to note is that UserManager
is actually an instance of UserManager<ApplicationUser>
. It's a generic class, so whatever user class is specified as the type argument when instantiate will be the class UserManager
operates on. As a result, if you want to work with CustomUser
, you will need an instance of UserManager<CustomUser>
.