简体   繁体   中英

Encrypt a web api request body content and decrypt on server

I am looking to create a simple security solution for which web API body content is not simply displayed to all whom wishes to see via intercepting the request with Fiddler or something. I am restricted in that I cannot use a SSL. I have already implemented a HMAC type of authentication and am wanting to take it a step further by creating a encrytpion of the body content on the client and sending that request to server were the server will then decrypt the body and forward to action as expected but decrypted. I used a filter for the server side HMAC and a delagatingHandler on the client.

I am not very familiar with working with http requests and do not fully understand how I might intercept all body content then encrypt it and put it back into the httpcontent.

Any ideas or help would be greatly appreciated.

In order to decrypt data before Model Mapping occurs in WEB API you can Hijack the AuthorizeAttribute because ActionFilterAttribute occurs after model mapping.

I know that the AuthorizeAttribute is meant for another reason , but hijacking it worked perfectly for me (I wanted to decompress zip content).

    public class DecryptAttribute : AuthorizeAttribute
    {
      public override void OnAuthorization(HttpActionContext actionContext)
      {
              actionContext.Request.Content =  DecryptContect(actionContext.Request.Content);
      }
    }

Then Decorate all your WebAPI controllers with this attribute.

In order to compress and embed to body i used a Delegating Handler

    public class EncryptHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) =>
        {
            HttpResponseMessage response = responseToCompleteTask.Result;
                response.Content = new EncryptContent(response.Content);

            return response;
        },
        TaskContinuationOptions.OnlyOnRanToCompletion);
    }
}

Then just register it

GlobalConfiguration.Configuration.MessageHandlers.Add(new EncryptHandler());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM