Authorization allows a website user to grant and restrict permissions on Web pages, functionality, and data. In this article, you will learn how to implement authorization in a Web API. Authorization checks whether a user is allowed to perform an action or has access to some functionality. For example, having the permission to get data and post data is a part of authorization.
Web API uses authorization filters to implement authorization. The Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
Web API provides a built-in authorization filter, Authorize Attribute. This filter checks whether the user is authenticated. If not then it returns the HTTP status code 401 (Unauthorized), without invoking the action.
- Create a new Project. Open Visual Studio 2012.
- Go to "File" -> "New" -> "Project...".
- Select "Web" in the installed templates.
- Select "ASP.NET MVC 4 Web Application".
- Select Web API, View engine should remain Razor.
- Enter the Name and choose the location.
- Click"OK".
In this sample, I will use Knockout to display data on the client-side.
First, add a model class as in the following:- public class Employee
- {
- public int EmployeeID { get; set; }
- public string LastName { get; set; }
- public string FirstName { get; set; }
- public string City { get; set; }
- public string Region { get; set; }
- public string PostalCode { get; set; }
- public string Country { get; set; }
- }
- public class ApplicationAuthenticationHandler : DelegatingHandler
- {
- // Http Response Messages
- private const string InvalidToken = "Invalid Authorization-Token";
- private const string MissingToken = "Missing Authorization-Token";
- protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage
- request, System.Threading.CancellationToken cancellationToken)
- {
- IEnumerable<string> sampleApiKeyHeaderValues = null;
- // Checking the Header values
- if (request.Headers.TryGetValues("X-SampleAppApiKey", out sampleApiKeyHeaderValues))
- {
- string[] apiKeyHeaderValue = sampleApiKeyHeaderValues.First().Split(':');
- // Validating header value must have both APP ID & APP key
- if (apiKeyHeaderValue.Length == 2)
- {
- // Code logic after authenciate the application.
- var appID = apiKeyHeaderValue[0];
- var AppKey = apiKeyHeaderValue[1];
- if (appID.Equals("SampleAppX123") && AppKey.Equals("YesAppKeyIsPersist"))
- {
- var userNameClaim = new Claim(ClaimTypes.Name, appID);
- var identity = new ClaimsIdentity(new[] { userNameClaim }, "SampleAppApiKey");
- var principal = new ClaimsPrincipal(identity);
- Thread.CurrentPrincipal = principal;
- if (System.Web.HttpContext.Current != null)
- {
- System.Web.HttpContext.Current.User = principal;
- }
- }
- else
- {
- // Web request cancel reason APP key is NULL
- return requestCancel(request, cancellationToken, InvalidToken);
- }
- }
- else
- {
- // Web request cancel reason missing APP key or APP ID
- return requestCancel(request, cancellationToken, MissingToken);
- }
- }
- else
- {
- // Web request cancel reason APP key missing all parameters
- return requestCancel(request, cancellationToken, MissingToken);
- }
- return base.SendAsync(request, cancellationToken);
- }
- private System.Threading.Tasks.Task<HttpResponseMessage> requestCancel(HttpRequestMessage
- request, System.Threading.CancellationToken cancellationToken, string message)
- {
- CancellationTokenSource _tokenSource = new CancellationTokenSource();
- cancellationToken = _tokenSource.Token;
- _tokenSource.Cancel();
- HttpResponseMessage response = new HttpResponseMessage();
- response = request.CreateResponse(HttpStatusCode.BadRequest);
- response.Content = new StringContent(message);
- return base.SendAsync(request, cancellationToken).ContinueWith(task =>
- {
- return response;
- });
- }
- }
- public class ValuesController : ApiController
- {
- private List<Employee> EmpList = new List<Employee>();
- // GET api/values
- public IEnumerable<Employee> Get()
- {
- EmpList.Add(new Employee { EmployeeID = 1, FirstName = "Nancy", LastName = "Davolio",
- City = "Seattle", Region = "WA", PostalCode = "98122", Country = "USA" });
- EmpList.Add(new Employee { EmployeeID = 2, FirstName = "Andrew", LastName = "Fuller",
- City = "Tacoma", Region = "WA", PostalCode = "98401", Country = "USA" });
- EmpList.Add(new Employee { EmployeeID = 3, FirstName = "Janet", LastName = "Leverling",
- City = "Kirkland", Region = "WA", PostalCode = "98033", Country = "USA" });
- EmpList.Add(new Employee { EmployeeID = 4, FirstName = "Margaret", LastName = "Peacock",
- City = "Redmond", Region = "WA", PostalCode = "98052", Country = "USA" });
- EmpList.Add(new Employee { EmployeeID = 5, FirstName = "Steven", LastName = "Buchanan",
- City = "London", Region = "WA", PostalCode = "SW1 8JR", Country = "UK" });
- EmpList.Add(new Employee { EmployeeID = 6, FirstName = "Michael", LastName = "Suyama",
- City = "London", Region = "WA", PostalCode = "EC2 7JR", Country = "UK" });
- EmpList.Add(new Employee { EmployeeID = 7, FirstName = "Robert", LastName = "King",
- City = "London", Region = "WA", PostalCode = "RG1 9SP", Country = "UK" });
- EmpList.Add(new Employee { EmployeeID = 8, FirstName = "Laura", LastName = "Callahan",
- City = "Seattle", Region = "WA", PostalCode = "98105", Country = "USA" });
- EmpList.Add(new Employee { EmployeeID = 9, FirstName = "Anne", LastName = "Dodsworth",
- City = "London", Region = "WA", PostalCode = "WG2 7LT", Country = "UK" });
- return EmpList;
- }
- <script src="~/Scripts/jquery-1.8.2.min.js"></script>
- <script src="~/Scripts/knockout-2.2.0.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- FetchEmployees();
- });
- function FetchEmployees() {
- viewModel = {
- employeeCollection: ko.observableArray()
- };
- $.ajax({
- type: "GET",
- url: "http://localhost:28357/api/values",
- contentType: "application/json; charset=utf-8",
- headers: { 'X-SampleAppApiKey': 'SampleAppX123:YesAppKeyIsPersist' },
- dataType: "json",
- success: function (response) {
- if (response != "") {
- $(response).each(function (index, element) {
- viewModel.employeeCollection.push(element);
- });
- ko.applyBindings(viewModel);
- }
- },
- error: function (event) {
- //If any errors occurred - detail them here
- alert("Transmission Failed. (An error has occurred)");
- }
- });
- }
- </script>
- <h3>Employees List</h3>
- <table id="empl" data-bind="visible: employeeCollection().length > 0">
- <thead>
- <tr>
- <th>Employee ID
- </th>
- <th>First Name
- </th>
- <th>Last Name
- </th>
- <th>City
- </th>
- <th>Region
- </th>
- <th>Postal Code
- </th>
- <th>Country
- </th>
- </tr>
- </thead>
- <tbody data-bind="foreach: employeeCollection">
- <tr>
- <td data-bind="text: EmployeeID"></td>
- <td data-bind="text: FirstName"></td>
- <td data-bind="text: LastName"></td>
- <td data-bind="text: City"></td>
- <td data-bind="text: Region"></td>
- <td data-bind="text: PostalCode"></td>
- <td data-bind="text: Country"></td>
- <td>
- <button data-bind="click: $root.edit">
- Edit</button>
- <button data-bind="click: $root.delete">
- Delete</button>
- </td>
- </tr>
- </tbody>
- </table>
Now run without authorization. Let's see what we get.
Now add the Authorize attribute to the Get method.
- [Authorize]
- public IEnumerable<Employee> Get()
- {
- }
If you want authorization on all the actions of a controller then put Authorize above the controller class as in the following:
- [Authorize]
- public class ValuesController : ApiController
- {
- private List<Employee> EmpList = new List<Employee>();
- // GET api/values
- [HttpGet]
- [Authorize]
- public IEnumerable<Employee> Get()
- {
- }
- // GET api/values/5
- [AllowAnonymous]
- public Employee Get(int id)
- {
- return EmpList.Find(e => e.EmployeeID == id);
- }
- }
- [Authorize(Users = "Raj,Sam")]
- public class ValuesController : ApiController
- {
- }
You can provide authorization for a specific user role also.
- [Authorize(Roles = "Administrators")]
- public class ValuesController : ApiController
- {
- }
No comments:
Post a Comment