IdentityUser vs my custom user table - c#

I have a PHP/MySQL-system that I'm porting to ASP.NET MVC5 with Azure SQL. I have a problem with grasping the concept of the new Identity solution that Microsoft has introduced. Becuase the database structure exists from the previous system, I have transfered the old MySQL database to Azure SQL. So far so good. There I have a user table with all user related data, such as username, email password etc. Becuase I wanted to continue using this table, I created the extra database fields that exists in the Identity user table. I have also created custom UserManager and other classes (MyUser, MyClaim etc.) so I am able to log in. Everything works.
Since I have a database first approach, not a code first approach, I wanted to use the User class to interact with the user table. But my UserManager returns the MyUser class (that inherits from IdentityUser), not the User class in my model. Even my dbcontext returns the MyUser class when I ask for the all the users in the User table.
Do I really need to manually update the MyUser class to replicate the User table, so if I do a change in the User table and updates my model, I have to manually update the MyUser class because the system can't/woun't use the models user class?

IdentityUser represents a default EntityFramework IUser implementation. Since you have your own existing schema, you're going to have to hand roll some classes to implement ASP.NET Identity to use your own tables.
In order to use your User class with ASP.NET Identity, you'll need to make sure it inherits from Microsoft.AspNet.Identity.IUser. After implementing IUser, update all references to MyUser with a reference to your User class. Note: You'll probably want to update your User class to something like MyAppNameUser for clarity.
After doing the above, you'll probably need to implement IUserStore so that the UserManager class can interact with your database schema.
You may want to take a look at https://github.com/raquelsa/AspNet.Identity.MySQL to get some ideas on implementing some of the ASP.NET Identity interfaces.

Related

Asp.Net Core Identity + Clean Architecture

My solution is based on Clean Architecture.
The Domain project should be completely ignorant about the Infrasctrure layer.
The Infrastructure contains a Data Project and an Identity Project.
The Data Project is supposed to implement my repositories. It contains a class called ApplicationDbContext that inherits from DbContext;
The Identity Project is supposed to implement the AspNet Core Identity and all its needs. It contains a class called PortalUser that inherits from IdentityUser and also contains a class called ApplicationIdentityDbContext that inherits from IdentityDbContext;
In the Domain, I have an Entity called User.
User is referenced by several other Entities, like Company (A company has several users).
I'd like to have only one table for both my entities User and the PortalUser.
When I try to apply the migrations, I have several problems referencing User.
What I tried so far:
Create an owned Property called User in PortalUser. But I can't map User in Company entity to an Owned Entity;
Map both User and Portal User to the same table called User, using different DbContexts. But when I apply the migrations to the Database, the migration fails and says that "A table User already exists";
Implement all properties from User in the PortalUser. But when adding a migration it fails and says that other entities like Company can't refer to User.
Make ApplicationDbUser inherit from ApplicationIdentityDbUser but two problems: 1st, it's conceptually wrong to the Clean Architecture; 2nd, The same issues related to having only the PortalUser being created and all other entities referencing User.
I'm stuck on this problem and the project is not going far. All examples that I found so far are raw and don't show what happens when I have navigation properties referencing the User.
The better solution I could think of so far is to have two different tables, one for Identity and another for user needs and references. However, I'm migrating this solution from a messy solution to a more well-organized one, using Clean Architecture. The old version uses only one table for both situations and I can't have a new table and migrate the data.
PLEASE, anyone knows how to solve this problem?

Is it possible to have multiple Identity-Instances in the same DBContext?

We have an existing ASP.net Core 2.1 Application which has UserAccounts associated with the Identity-System.
Now we would like to add Admin-Users which shall not share the UserAccountsTable which is already used by the UserAccounts. (Yeah i know, we could simply add a bool column like isAdmin but we opted for seperated tables).
So my thinking was, that i need to create a new Identity-Instance which is using our AdminUser and AdminRole classes (Both deriving from IdentityUser and IdentityRole accordingly).
In the DBContext i can now change the Table-Names via the Fluent-API of AdminUser and AdminRole. But how would i now change the names of the needed "infrastructure" tables created by Identity automatically?
I've found this documentation by Microsoft. But they are only using "generic" types to rename the tables for e.G. the Link-Table between Users and Roles (IdentityUserRole). This type would probably "conflict" with my already configured UserAccounts-Identity, therefore "renaming" both tables, making troubles again, or not?
An obvious solution could be to create a new AdminUserContext, which would not share the UserAccounts-Information. But then we would lose the Links to the Entities we actually would want to administrate? And linking DBContexts doesn't feel "right" to me.
Anybody got some ideas to this?

Implement inheritence in ASP.Net MVC6 Identity framework

I am currently working on a ASP.Net 5 / ASP.Net MVC 6 application. I am using EntityFramework 7 as ORM framework, and the Code-first approach.
In my model, I have the following:
An AppUser class, which inherits from IdentityUser<int>. IdentityUser is provided through Microsoft.AspNet.Identity.EntityFramework package, and allows one to inherit from the provided class, by specifying the data type from primary keys, and, of course, add custom fields to it. Everything is working fine with it (database schema, inserts, ...)
A Person class, which inherits from the previous, and adds some app-specific fields and logic. Basically, my idea is that every Person in my app is a potential user, but not every user needs to be a Person.
For all my model objects, I implemented a generic repository approach, which basically implements generic CRUD operations for every model class, and allows one to override generic methods for specific domain classes.
But for the AppUser class, ASP.Net Identity framework comes with its own repository, which basically allows one to add a user, add roles to user, checks unicity of logins, etc...
My question is : how can I use these two repositories together, so that when I add a Person, it creates a AppUser through the Identity framework repository, and then stores the field of my custom Person within the same database record ?
Notice that inheritence of Person on AppUser has been resolved by code-first as single table inheritance : the same table stores AppUser and Persons, and a discriminant field was generated.
You create a custom manager class which extends the usermanger class provided by Identity framework. This new CustomUserManager class will have all the functions of UserManager class, plus the new ones which you want to implement for adding a Person

Integrating asp.net mvc identity with other custom tables to build one edmx diagram

I want to ask a question regarding asp.net identity and integrating custom tables. I understand that using asp.net identity system for user login and registration and other actions that relates to user membership and account management issues is easier and faster. If for example i want to build a blog and as it is known that in a blog users have to register and also a user is associated with many posts and many comments. with the default identity system, i dont know how i can include other tables i have in the database to the existing tables that has to deal with membership so that i can have one edmx diagram that maps all relationships between the identity tables and other tables in the blog.
To make it more clearer ive started with my own custom implementation of a membership system which has served me well so far, but i noticed i'm missing a lot by not using the default identity system of asp.net. Lets say i have these tables below
In instances where i mention userId, AuthorId are the same and only refers to the id of the user in the Users table (if there is anything like that in asp.net identity). I
How can i have something like this and instead of my own dbo.Userprofile, i want that of the asp.net identity and then generate a model from this. I hope my question makes sense.
The central class you have to use in this scenario is IdentityUser. Based on this you can create your user class where you extend the IdentityUser class with your specific propertiers which are not part of the base class (such as Gender). It could look something like this:
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public string Gender { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager 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;
}
}
Because you're using an integer as the type of the keys you have to do some customization. The answer provided by James in this thread shows you how to do it. The last thing to do is to link your existing tables to your new user table. This can be done through simply setting the foreign key.
UPDATE
Of course you should follow the hint mentioned by Chris. Missed to mention that.
Now is as good a time as any to stop using EDMX. It's deprecated and going away completely in EF7. Identity uses Code First, so any models you want to include in the same context should also be Code First. For more information about the upcoming change and what you should do going forward see the announcement on the ADO.NET blog.

Inheriting from the MembershipUser class in EF

I am using the built in .net authentication in my project and am creating class entities in entity framework 4.0.
My classes are a Student, University and Company class. My question is can I inherit the System.Web.Security.MembershipUser class for these classes? The ef class already inherit the EntityObject class so I don't know how to do it?
thanks
Your question is a little lacking in detail but I have a go at answering.
To start you won't want to inherit from the MembershipUser class. You can (because its abstract) but you would only inherit from it if you were going to use your own logic and db tables to store the validation fields.
You wouldn't put Membership onto a University or Company class but on the members of those Entities e.g. a Student is a member of a University, as there are Employees to a Company.
Neither of the Student or Employee would have Membership information on them (within their db tables) but would more likely have information relating directly to them (e.g. an Employee has a Payroll number)
Student and Employee are both of type Person (e.g they both have Name, Address, etc.)
A Student or an Employee maybe a User of your Application (web site, desktop, etc.) but then they maybe not also, or they may be deactivated as a User but you want to keep their Person and Student/Employee information for your records.
A User will have the usual info like... UserId, Username and Password, etc. but you don't want to use this entity if you were going to put a DisplayName on the App. For security reasons, I also do not put Session information onto the User but use the UserId (encrypted MD5 one way encryption) and SessionId to validate my users Session, this means that if some how I did have a breach of security (SQL injection) the hacker would not be able to access Usernames and Password details. Anyway, I digress.
So, what is the MembershipUser class? It gets used mainly in your Authentication object which will have methods like... Login, ChangePassword, Logout, etc. These methods would call
if (!Membership.ValidateUser('username', 'password')) return false; etc.
If you wanted to use your own db tables and entityframework calls for the membership then you would look to implement a Custom Membership Provider, overriding all the standard methods and put you entity DAO requests (hopefully using Design Patterns e.g. Repositories etc.). This can be risky and difficult, but with experience not too big a deal.
Otherwise, just stick with the standard Membership (User) Provider, stick what it needs in the web.config file and have it deal with the security and you can get on with developing you Application...
a good book is Pro Asp.Net MVC Framework ... it goes through everything including unit-testing, design patterns, etc. Also a great way to spend some money is on the GOF (Gang of Four) design patterns source code... get the full works, best £60 spend ever.
I hope this helped.
Hugh
There is no EF provider, but you can write your own provider.
Write a mapper class for your MembershipUser derived class.
I found a nice example over here:
efmembership.codeplex.com

Categories