How to validate https request in WebAPI
Application using dotnet
Steps:
· Create request handler
· Register requester handler
//Request Handler to be used for Https check: HttpsGuard.cs
//Supporting class used by Request Handler: IdentityStore.cs
FileName: HttpsGuard.cs
public class HttpsGuard: DelegatingHandler
{
private IIdentityStore _identityStore { get; set; }
public HttpsGuard(IIdentityStore identityStore)
{
_identityStore
= identityStore;
}
protected override Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return ValidateRequest(request,
cancellationToken);
}
public Task<HttpResponseMessage> ValidateRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!_identityStore.isHTTPSRequest(request))
{
var reply =
request.CreateErrorResponse(HttpStatusCode.BadRequest,
ErrorCodes.InvalidRequestProtocol);
return Task.FromResult(reply);
}
return base.SendAsync(request, cancellationToken);
}
}
FileName: IdentityStore.cs
public class IdentityStore : IIdentityStore
{
public bool isHTTPSRequest(HttpRequestMessage request)
{
return request.RequestUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
}
}
FileName: IIdentityStore.cs
public interface IIdentityStore
{
bool isHTTPSRequest(HttpRequestMessage request);
}
FileName: WebApiConfig.cs
//Register Request Handler in App_Start/WebAPIConfig.cs file
public static class WebApiConfig
{
public static void Register(HttpConfiguration
config)
{
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id
= RouteParameter.Optional });
config.MessageHandlers.Add(new HttpsGuard(new IdentityStore())); //Global handler - applicable to all the requests
}
}
No comments:
Post a Comment