Posted by Anuraj on Sunday, November 3, 2013 Reading time :2 minutes
In this post I am going to show how to implement Basic HTTP authentication in a Web API project by customizing AuthotrizeAttribute. HTTP authentication is a standard protocol and can be easily handled by most popular client and mobile platforms.
Basic authentication works as follows: - If a request requires authentication, the server returns 401 (Unauthorized). The response includes a WWW-Authenticate header, indicating the server supports Basic authentication. The client sends another request, with the client credentials in the Authorization header. The credentials are formatted as the string â€œname:passwordâ€, base64-encoded. The credentials are not encrypted. Basic authentication is performed within the context of a â€œrealm.â€ The server includes the name of the realm in the WWW-Authenticate header. The userâ€™s credentials are valid within that realm. The exact scope of a realm is defined by the server.
Because the credentials are sent unencrypted, Basic authentication is only secure over HTTPS. Basic authentication is also vulnerable to CSRF attacks. After the user enters credentials, the browser automatically sends them on subsequent requests to the same domain, for the duration of the session. This includes AJAX requests.
Basic Authentication built into IIS uses Windows credentials, which means you need to create accounts for your users on the hosting server. But for an internet application, it may not be feasible, normally user accounts are typically stored in an external database.
Here is the implementation.
And you can decorate the API controller / actions using this attribute.
And you can access the controller method(s) using JQuery like this.
The beforeSend function will help to set the Authorization header for the request.