Reputation: 115
I am using a .net 4.5 framework application which i am using as Endpoint i want to add apikey to protect it on environment basis. So In Dev, UAT and Prod Web.Config file (using transform thing to fetch values from primary Web.config file) i want to add a ApiKey and then authorize the controller by that key same way we do it in web api or .net core web api
[AuthorizeByApiKey]
. I checked documentation but in .Net 4.5 can't find a way of doing this. I checed OWIN
library but don't have any idea how i can apply it here
currently i am using following attribute
[System.Web.Http.RoutePrefix("api/address")]
same way i want to use Authorize Attribute and protect every controller by the key
i tried using following attribute but not getting how i can pass Key to this only properties i can add here are Users and Roles
[System.Web.Http.Authorize()]
Upvotes: 1
Views: 799
Reputation: 115
Here is the answer for this create a class with the name you want i named it ApiKeyMessageHandler which inheriting from Delegating Handler which will delegate the properties from request we want to validate. The logic is simple we are are first getting the api key from Web.Config file and then we are getting Api key from request header and then checking weather it is equal if it is then Status is 200 otherwise we are sending message that invalid api key so that execution stops there.
public class ApiKeyMessageHandler : DelegatingHandler
{
private static readonly string ApiKeyToValidate = ConfigurationManager.AppSettings["ApiKey"];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var isValidKey = false;
IEnumerable<string> requestHeaders;
var checkApiKeyExists = request.Headers.TryGetValues("ApiKey", out requestHeaders);
if (checkApiKeyExists)
{
if (requestHeaders.FirstOrDefault().Equals(ApiKeyToValidate))
{
isValidKey = true;
}
}
if (!isValidKey)
{
return request.CreateResponse();
}
var resposne = await base.SendAsync(request, cancellationToken);
return resposne;
}
}
After this we need to configure this message handler to Global.ascx.cs or WebApiConfig.cs i used it in global.ascx.cs i guess we can intitialize in config file as well.
GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiKeyMessageHandler());
Thats it Now this will validate api key from request. You can test with postman or any Api testing tool.
Upvotes: 0