Role Provider / Membership? How to in asp.net web api?

chobo2 picture chobo2 · May 21, 2013 · Viewed 9.2k times · Source

I am building an asp.net mvc web api application and not sure how to do the membership stuff.

In my current project I have this

My own Users Table and Role Table I am not using asp.net membership as it brings too much baggage and does not fit how I want to design my database(sure I can to it but it just seems like to much work)

A user can have many roles and a role can have many users.

I am using EF to do almost all my calls to the database.

In past projects I made my own Authorize Attribute what did my own call to my database and checked to see if the user was in the correct role as what was allowed on that controller/action method.

By not doing any membership providers I lost out on some of the built in functions such as User.IsInRole. I was still able to use User.Identity.Name but I think that was because of the cookie that I set.

What is the best practice way to do it now in asp.net mvc 4/web api?

While googling I found "SimpleMembership" but have not read much into it yet.

On a side note can I use User.Identity.Name with my webapi if I authenticated a user?

Answer

Kevin Junghans picture Kevin Junghans · May 22, 2013

Here is an article that describes how to create a custom authorize attribute for Web API's using SimpleMembership. You do not have to use SimpleMembership, although it very flexible and easy to use. You could take the same concepts in this article and use your membership service instead, as long as your service can verify that a specific user is in a role, log a user in and out, and verify that they are authenticated.

If your service does not verify that they are authenticated you can use User.Identity.IsAuthenticated and you can use User.Identity.Name to get the currently logged in usersname; assuming that your service correctly sets Thread.CurrentPrincipal when a user logs in. It is also a recommended practice to set HttpContext.Current.User. Of course you do not have to worry about any of this if you use SimpleMembership.

This custom authorize attribute support both forms authentication and basic authentication in case you expose your API's to the public. It is different from an authorize attribute used on a controller in that it returns an HTTP status code of Forbidden if the are not authorized and Unauthorized if they are not authenticated; instead of redirecting to a log-on page.