Authorization Using Web API

Introduction
 
According to Wikipedia
 
"Authorization or authorisation is the function of specifying access rights to resources related to information security and computer security in general and to access control in particular. More formally, "to authorize" is to define access policy. For example, human resources staff are normally authorized to access employee records and this policy is usually formalized as access control rules in a computer system. During operation, the system uses the access control rules to decide whether access requests from (authenticated) consumers shall be approved (granted) or disapproved (rejected). Resources include individual files or an item's data, computer programs, computer devices and functionality provided by computer applications. Examples of consumers are computer users, computer programs and other devices on the computer."
 
In this context, authorization means determination of which user has access to what functionality and data in a web application or website.
 
In this article, you will learn how to use authorization in the 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.

Getting Started  
  • 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 thelocation.
  • Click"OK".
In this sample I will use Knockout to display data at the client side.

First add a model class as in the following:

public class Employee

{

      public int EmployeeID getset; }

      public string LastName getset; }

      public string FirstName getset; }

      public string City getset; }

      public string Region getset; }

      public string PostalCode getset; }

      public string Country getset; }

}

Now add a class as in the following:

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<stringsampleApiKeyHeaderValues = 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, cancellationTokenInvalidToken);

                    }

                }

                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<HttpResponseMessagerequestCancel(HttpRequestMessage 
request, System.Threading.
CancellationToken cancellationTokenstring 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;

            });

      }

}


Now add the following controller class:

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;

}


Add the following view to display data:

<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 = {

            employeeCollectionko.observableArray()

        };

        $.ajax({           

            type"GET",

            url"http://localhost:28357/api/values",

            contentType"application/json; charset=utf-8",

            headers'X-SampleAppApiKey''SampleAppX123:YesAppKeyIsPersist' },

            dataType"json",

            successfunction (response) {

                if (response !"") {

                    $(response).each(function (index, element) {

                        viewModel.employeeCollection.push(element);

                    });

                    ko.applyBindings(viewModel);

                }

            },

            errorfunction (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="foreachemployeeCollection">

        <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()

{

}


Now run again.


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);

    }

}


You can set permission for a specific user like this.

[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

{

}


Conclusion

In this article we learned how to use authorization in the Web API.

Up Next
    Ebook Download
    View all
    Learn
    View all