Validating HTTPS Request URL Using AuthorizationFilter

Introduction 

In this article, we will see the example of how to validate HTTPS request in WebAPI2, using AuthorizationFilter. The AuthorizationFilter validation is to enforce the incoming request to be transferred HTTP to  HTTPS protocol. This attribute can be achieved by using authorization filter attribute for all the controllers (Global) methods or for a particular API exposed inside the Service.
 
How to manage request and response in Web API: See the image below -



In this image, you can see, if you are using Authorization filter, it will apply according to your logic. In this case, I am going to create a logic to check any HTTP and HTTPS request inside AuthorizationfilterAttribute class. I think this image is helpful to understand the flow of Filter in MVC.

Before going on to the next step, I am just listing some important links to learn related content, which are given below- 
What is HTTP and HTTPS ?
 
"The Hypertext Transfer Protocol (HTTP) is an Application convention for dispersed, community, hypermedia data frameworks. HTTP is the establishment of information correspondence for the World Wide Web. Hypertext is an organized content, which utilizes sensible connections (hyperlinks) between the hubs containing content.

 
 
"Hyper Text Transfer Protocol Secure (HTTPS) is the protected variant of HTTP, the convention over which information is sent between your program and the site, that you are associated with. The "S" toward the end of HTTPS stands for 'Secure'. It implies all correspondences between your program and the site are scrambled.

Follow some steps to validate HTTPS request, which are-

Step 1 - Create a MVC WebAPI Application "HTTPSValidation". Inside this, i am not using any third party package or the library.
 
Step 2 - Create a Class "ValidateRequest" inside "App_start" folder . See the code, given below-
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Net.Http.Headers;  
  7. using System.Web;  
  8. using System.Web.Http.Controllers;  
  9. using System.Web.Http.Filters;  
  10.   
  11. namespace HTTPSValidation.App_Start  
  12. {  
  13.     public class ValidateRequest:AuthorizationFilterAttribute  
  14.     {  
  15.         ///  <summary>  
  16.         ///  Validate HTTPS or HTTP request URI  
  17.         ///  </summary>  
  18.         ///  <param name="_Context">HttpActionContext value</param>  
  19.         public override void OnAuthorization(HttpActionContext _Context)  
  20.             {  
  21.             //To check request coming from HTTPS or HTTP  
  22.             if (_Context != null && _Context.Request != null &&  
  23.             !_Context.Request.RequestUri.Scheme.Equals(Uri.UriSchemeHttps))  
  24.             {  
  25.                 var controllerFilters = _Context.ControllerContext.ControllerDescriptor.GetFilters();  
  26.                 var actionFilters = _Context.ActionDescriptor.GetFilters();  
  27.   
  28.                 if ((controllerFilters != null && controllerFilters.Select  
  29.                 (t => t.GetType() == typeof(ValidateRequest)).Count() > 0) ||  
  30.                     (actionFilters != null && actionFilters.Select(t =>  
  31.                     t.GetType() == typeof(ValidateRequest)).Count() > 0))  
  32.                 {  
  33.                     _Context.Response = _Context.Request.CreateResponse(HttpStatusCode.Forbidden,  
  34.                             new HttpResponseMessage { ReasonPhrase = "Needs HTTPS,SSL certificate" },  
  35.                             new MediaTypeHeaderValue("text/json"));  
  36.                 }  
  37.             }  
  38.             else  
  39.             {  
  40.                 base.OnAuthorization(_Context);  
  41.             }  
  42.             }  
  43.         }  
  44.     }  
In this class, I have inherited "AuthorizationFilterAttribute", which allows us to call this class before calling the action. Also, you can see, I have checked Request (HTTP or HTTPS). Afterwards, if request is coming from HTTPS, it will be working fine, but if the request will come from HTTP, it throws message "Needs HTTPS,SSL certificate". 
 
Step 3 - Create a new Apicontroller "TestController" in your Application. See the code, given below-
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using HTTPSValidation.App_Start;  
  8.   
  9. namespace HTTPSValidation.Controllers  
  10. {  
  11.     [ValidateRequest]  
  12.     [RoutePrefix("api/Test")]  
  13.     public class TestController : ApiController  
  14.     {  
  15.         [Route("testMethod")]  
  16.         [HttpGet]  
  17.         public string testMethod()  
  18.         {  
  19.             return "hello";  
  20.   
  21.         }  
  22.     }  
  23. }  
You can see in the code, I have used an attribute "ValidateRequest". It will call before calling the controller.

Apart from it, you can use this attribute on the specific controller, action. If you have registered this class in webapi.config file, you don't need to use with any controller or action. By default, it will work for the whole Application. 

Step 4 - Now go in webapi.config file.register "ValidateRequest" class to use global.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web.Http;  
  6. using Microsoft.Owin.Security.OAuth;  
  7. using Newtonsoft.Json.Serialization;  
  8. using HTTPSValidation.App_Start;  
  9.   
  10. namespace HTTPSValidation  
  11. {  
  12.     public static class WebApiConfig  
  13.     {  
  14.         public static void Register(HttpConfiguration config)  
  15.         {  
  16.             // Web API configuration and services  
  17.             // Configure Web API to use only bearer token authentication.  
  18.             config.SuppressDefaultHostAuthentication();  
  19.             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));  
  20.   
  21.             config.Filters.Add(new ValidateRequest()); //Register class here,if you create any filter.  
  22.   
  23.             // Web API routes  
  24.             config.MapHttpAttributeRoutes();  
  25.   
  26.             config.Routes.MapHttpRoute(  
  27.                 name: "DefaultApi",  
  28.                 routeTemplate: "api/{controller}/{id}",  
  29.                 defaults: new { id = RouteParameter.Optional }  
  30.             );  
  31.         }  
  32.     }  
  33. }  
In this code, I have registered "config.Filters.Add (new ValidateRequest()); " line.

Finally, we are ready to run the Application. By default, your Application will be run on HTTP, but according to this code Filter will validate HTTPS request and throw message "Needs HTTPS,SSL certificate". See the output, given below-

 
According to this image, I am using endpoint "http://localhost:52824/api/Test/testMethod" via HTTP, so in that case, I found a message.
 
Now, I am going to enable SSL in my project. See the image of how to enable-

Go to Application=>click F4.

 

Now, change "SSL enabled" property FALSE to TRUE. By default, it's false. Once you will change the property to true, HTTPS port will be open to run. You can see there are two endpoints, which are-

HTTP-http://localhost:52824/api/Test/testMethod
HTTPS- https://localhost:44330/api/Test/testMethod
 
Now, I am going to run API via HTTPS " https://localhost:44330/api/Test/testMethod" endpoint. See the output, given below-.
 
 

In this image, you can see HTTPS validation completes and returns the output. I hope, you enjoyed this article and learned lots of things. If you have any doubt, you can download the project.

Up Next
    Ebook Download
    View all
    Learn
    View all