Assuming you want to prepare some JSON API in your ASP.NET MVC with authorization.
To share the same authorization logics for our Controller Action, what we should probably do is to implement our own FilterAttributes.
It can be as simple as:
|
Note we are using property injection here for the IAuthTokenService
here, check out Inject Properties Into FilterAttributes for more information.
HTTP status codes
In order to add our HTTP status codes, we can simple add the following line:
|
Problem: The default ASP.NET forms authentication redirect behaviour
The default ASP.NET forms authentication behaviour will convert HTTP 401 status codes to 302 in order to redirect to the login page. This probably not we want here as we are expecting a JSON for our API result.
Solution
If you are using .Net 4.5, you can apply the new HttpResponse.SuppressFormsAuthenticationRedirect property.
If you are using .Net 4.0 or lower version, it seems it cannot be done at the moment, but we may try to use different HTTP status code like 403