1

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()]
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84
Pratex
  • 11
  • 2
  • 2
    The oldest supported .NET Framework version is 4.6.2. 4.5 went out of support *7 years ago*. Most likely you aren't using 4.5 at all, as 4.x versions are in-place binary upgrades and you *can't* downgrade them. – Panagiotis Kanavos Jul 19 '23 at 16:44
  • @PanagiotisKanavosi know but we have a project with that and language version is 7.3 – Pratex Jul 19 '23 at 16:46
  • @PanagiotisKanavos That's the runtime, not the asp.net – Aluan Haddad Jul 19 '23 at 16:46
  • @AluanHaddad there's no difference. The versions match. – Panagiotis Kanavos Jul 19 '23 at 16:47
  • @Pratex `but we have a project with that` but do you have *any* server with that? You can't downgrade 4.x versions which means unless you use unsupported servers too, you're running on newer versions already. That goes for dev, testing and staging environments. The language setting can change. – Panagiotis Kanavos Jul 19 '23 at 16:48
  • What kind of application is this? Web API 1 an 2 run on .NET Framework 4.x but the question gives the impression this is something else. MVC? Which version? You'll have to use that version's authentication and authorization features to implement API key authentication. – Panagiotis Kanavos Jul 19 '23 at 16:51
  • @PanagiotisKanavos servers support is there the whole system is not migrated to latest .net environment yet – Pratex Jul 19 '23 at 16:51
  • @PanagiotisKanavos is Web Api 1 – Pratex Jul 19 '23 at 16:54
  • That's not what I said. It's not about the latest but the *oldest* version that can run on a server. If a server has 4.6 or 4.5.2 installed, you can't downgrade to 4.5. In any case `AuthorizeByApiKey` isn't part of ASP.NET Core. Is that a custom Authorization filter perhaps? If your application is a Web API app, you can create authorization filters too – Panagiotis Kanavos Jul 19 '23 at 16:54
  • `is Web Api 1` perhaps you can rewrite your custom `AuthorizeByApiKey` filter to work with Web API 1 too? Although Web API isn't just unsupported - it was actually the Proof-Of-Concept version. [Web API 2 security](https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/) docs are up to date but Web API 1 has only a couple of [tutorial pages](https://learn.microsoft.com/en-us/aspnet/web-api/overview/older-versions/) – Panagiotis Kanavos Jul 19 '23 at 16:57
  • @PanagiotisKanavos i want to apply with Authorize attribute but don't know how the logic be considering that key must be environment specific – Pratex Jul 19 '23 at 16:59
  • @PanagiotisKanavos I thought we were talking about running an ASP.NET application targeting v 4.5 of the .net framework against a higher version of the framework such as .net framework 4.8. My mistake – Aluan Haddad Jul 19 '23 at 17:13

1 Answers1

0

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.

Pratex
  • 11
  • 2