Search code examples
asp.net-mvcasp.net-web-api2simplemembership

Add Existing Membership/Role Provider to new WebAPI with Basic Authenication


Ok apparently there's nothing "Basic" about "Basic Authentication" when it comes to a WebAPI project and an existing database...but I digress.

Situation:

Existing asp.net Website App (WSP) with older .net membership providing user role and forms authentication.

Using this database with a new WebAPI 2.2 application with code first migrations, MVC5 goodness, etc. and I want to use things such as [Authorize] and role based attributes to control access to the various methods our integration partners will call.

Question:

Should I import a IdentityModel class from one of my other greenfield MVC apps, then import those existing users/roles into those "simple membership" tables, or would you recommend just adding the existing membership tables/models with perhaps a custom membership provider?

If it's the latter, can someone maybe point me to an article or answer where they've done this? I think my head is just spinning and even if I did manage to google the right thing I don't think I'd see it.

Thanks in advance.


Solution

  • I do not recommend using Basic authentication for Web API, you will end up sending username/password with each request in the Authorization header, this will force the client applications which will consume your API to store the username/password locally in order to fulfill your API needs, and you do not have control on those application and do not know how they going to store those credentials

    My recommendation is to check Bearer Token Based Authentication which is the right way you should follow, if you are looking for something simple and can be considered as a replacement for basic authentication then you need to implement just one flow of OAuth 2.0 which is named "Resource owner credentials flow". The idea for this flow is pretty simple, all you need to do is to exchange the username/password with a bearer token (Encrypted and signed string) which expires after certain period, then you keep sending this string (token) in the Authorization header for each request. I've compiled detailed blog post about this named "Token Based Authentication using ASP.NET Web API 2". Hope it will be useful for your case.

    Now regarding your membership provider, I'm using ASP.NET Identity 2.0 in the post, you are not required to do this, you can keep your custom DB tables or use the old membership provider. The nice thing that you can use the Roles in token based authentication with any DB store you prefer.

    It will be way easier if you are using ASP.NET Identity, but it will work if you do not want to migrate your data to the new membership system. You will end writing extra line of codes to achieve this. Hope this answers your question and let me know if you need further help.