In my blog, `Security in Web API – Part 1’, we discussed how to create APIKeyHandler and AuthHandler. In this blog, we will see how to implement Authorization and execute Basic Authentication.
Authorization is verifying whether the authenticated user can perform a particular action or consume a particular resource. This happens after the authentication and before the controller action is executed.
ASP.NET MVC Web API provides an authorization filter called Authorize Attribute which verifies the request’s I Principal, checks its Identity.IsAuthenticated property, and returns a 401 Unauthorized HTTP status if the value is false and the requested action method will not be executed. The filter can be applied in different levels like the controller level or action level, and can be easily applied using the [Authorize] syntax on top of controllers or actions.
[Authorize] public class EmployeeController : ApiController
Once the attribute is added, it will prevent all action methods in the controller from being accessed by unauthorized users.
The Basic Authentication handler will set the current user’s identity I Principal object, then before the request reaches the controller, Authorize Attribute verifies access to the particular controller/action for the current user.
Let’s create an HTTP request without proper credentials.
The access will be denied by the Authorize Attribute.
Now, let’s create another request with Authorization header key/value as follows.
Authorization : Basic dXNlcm5hbWU6cGFzc3dvcmQ=
The value dXNlcm5hbWU6cGFzc3dvcmQ= represents “username:password” in Base64 encoded form.
The request gets access rights to the controller/action as expected.
Action Level Authorization
We can also restrict access to only few actions in the controller by mentioning AuthorizeAttribute at the action level instead which allows to have both protected and unprotected actions in the same controller.
When we set the [Authorize] attribute at the controller level and want to have unprotected action then we can set Allow Anonymous attribute for the action, this will make the [Authorize] attribute skipped for that action.
Custom Authorization Attribute
We can create our own custom authorization attribute depending on our needs. We can achieve this by extending Authorize Attribute (i.e) derive a class with Authorize Attribute and override Is Authorized method .
In the below example we want to restrict access to our API Service to users who are within the particular range of IP address.
Once we derive the attribute we ca define the same at controller/action level as shown below.
To summarize, we have discussed the ways in which we can secure our Web API’s with Basic Authentication and Authorization.