Let's suppose we have a web-site where there are:
- Admin section
- Client section
- Guest(visitor) section
Obviously, the last one (Guest section) can be accessed by everyone while admin part - only by administrations and client part - only by registered clients. Admins and clients have different model classes (Admin and User correspondingly), are stored in the different databases and we would like to use different authentication cookies for each of them. Is it possible to do with ASP.NET Core Identity?
We tried to use CookieName property during AddIdentity initialization but it appears that ApplicationCookie accessible there - is the same object, so the second definition simply rewrites the first one:
services
.AddIdentity<User, UserRole>(opts => {
opts.Cookies.ApplicationCookie.CookieName = "Client";
opts.Cookies.ApplicationCookie.LoginPath = new PathString("/login");
. . . . . .
});
services
.AddIdentity<Admin, AdminRole>(opts => {
//the following lines rewrite cookie options from client's to admin's
opts.Cookies.ApplicationCookie.CookieName = "Admin";
opts.Cookies.ApplicationCookie.LoginPath = new PathString("/admin/login");
. . . . . .
});
Possible? Yes. You would need to create your own identity middleware to handle different cookies but it can be done.
Recommended? NO
There are 2 separate issues with security: authentication and authorization. Cookies work well for authentication (who someone is) and but you should use roles and claims for authorization (what someone can do and has access to), which is what you're trying to solve here.
ASP.NET's Identity framework already has great support for both Roles and Claims so you can use a standard user model for everyone, add an "admin" role for some users, and then add even more specific claims as needed.
The documentation for handling authorization is very detailed and gives you a great walkthrough of options. Both Roles and Claims can easily be enforced by adding them to a user profile and then using [Attributes] on your controller route methods, as shown below:
Roles:
Claims: