I need to create a Web API C# application for an existing MySQL database. I've managed to use Entity Framework 6 to bind every database table to a RESTful API (that allows CRUD operations).
I want to implement a login/registration system (so that I can implement roles and permissions in the future, and restrict certain API requests).
The MySQL database I have to use has a table for users (called user
) that has the following self-explanatory columns:
id
email
username
password_hash
It seems that the de-facto standard for authentication is ASP.Net Identity. I have spent the last hour trying to figure out how to make Identity work with an existing DB-First Entity Framework setup.
If I try to construct ApplicationUser
instances storing user
instances (entities from the MySQL database) to retrieve user data, I get the following error:
The entity type ApplicationUser is not part of the model for the current context.
I assume I need to store Identity data in my MySQL database, but couldn't find any resource on how to do that. I've tried completely removing the ApplicationUser
class and making my user
entity class derive from IdentityUser
, but calling UserManager.CreateAsync
resulted in LINQ to Entities conversion errors.
How do I setup authentication in a Web API 2 application, having an existing user
entity?
Since your DB schema are not compatible with default
UserStore
You must implement your ownUserStore
andUserPasswordStore
classes then inject them toUserManager
. Consider this simple example:First write your custom user class and implement
IUser
interface:Now author your custom
UserStore
andIUserPasswordStore
class like this:Now you have very own user store simply inject it to the user manager:
Also please note you must directly inherit your DB Context class from
DbContext
notIdentityDbContext
since you have implemented own user store.You say:
It definitely means that you DO NOT need ASP.NET Identity. ASP.NET Identity is a technology to handle all users stuffs. It actually does not "make" the authentication mechanism. ASP.NET Identity uses OWIN Authentication mechanism, which is another thing.
What you are looking for is not "how to use ASP.NET Identity with my existing Users table", but "How to configure OWIN Authentication using my existing Users table"
To use OWIN Auth follow these steps:
Install the packages:
Create
Startup.cs
file inside the root folder (example):make sure that [assembly: OwinStartup] is correctly configured
Use the
[Authorize]
attribute to authorize the actions.Call
api/security/token
withGrantType
,UserName
, andPassword
to get the bearer token. Like this:Send the token within the
HttpHeader Authorization
asBearer "YOURTOKENHERE"
. Like this:Hope it helps!