Session object. On each request, I check which permissions are necessary and if the user has those permissions. If not, I return a 403 Forbidden. To do this, you simply extend the AuthorizeAttribute and perform the necessary checks in IsAuthorized. Peace of cake, how hard can it be?
Turns out, pretty hard…
Click on the links if you don’t believe me. There are two classes with the same name but different namespace:
When you are working with Web API, you want to use System.Web.Http.AuthorizeAttribute instead of the one in the Mvc namespace.
2. Where is my Session?
This was probably the hardest part. Turns out, when an API Controller is launched, the session is not accessible. However, there is a workaround to this, which I’ve found here: https://soabubblog.wordpress.com/2013/07/10/web-api-sessions/
These few lines will save you your sanity when you’ll be looking for the session object everywhere.
3. I want to return 403 instead of 401
… In summary, a 401 Unauthorized response should be used for missing or bad authentication, and a 403 Forbidden response should be used afterwards, when the user is authenticated but isn’t authorized to perform the requested operation on the given resource.
To do this, you need to override
HandleUnauthorizedRequest and set the response.
The final solution:
However, turns out, this solution doesn’t work in mono. There is a new post about that particular problem: Request Authorization in ASP.NET Web API in Mono