Introduction
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 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 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; }
}
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<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 authenticate 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;
});
}
}
Now add the following controller class.



MarkPosted Aug 21, 2020, 2:50 PM
Is there a different approach if the web api is enabled for cors? because i was able to make this work if the client(html) and web api resides on the same server, but if not, im just getting 401 unauthorized, testing on my local iisexpress with 2 projects open.
Pankajkumar PatelPosted Aug 12, 2019, 11:30 PM
Nice article
Purushottam RathorePosted Mar 24, 2014, 3:14 AM
Thanks.