Using SSL in ASP.NET Web API

来源:互联网 发布:淘宝茶叶 编辑:程序博客网 时间:2024/05/21 05:06

原文:http://www.codeguru.com/csharp/.net/using-ssl-in-asp.net-web-api.htm

Introduction

While developing websites that need to deal with sensitive data, developers use authentication schemes such as ASP.NET forms authentication. Although  these authentication schemes prohibit unauthorized access to web pages, the user credentials as well as data involved in the communication is sent as plain text. Since the data is being sent in unencrypted form it can be easily intercepted by malicious parties and can pose a security threat to your web application. To secure such communication the data must be encrypted and then sent over the wire. An industry standard method to achieve such a secure communication is Secure Sockets Layer or SSL. This article explains how SSL can be used in ASP.NET Web API to achieve secure data transfer.

Overview of SSL

Before we go into the details of using SSL with Web API, it would be nice to know some basics of Secure Sockets Layer (SSL). Simply put SSL is an industry standard for establishing an encrypted communication channel between a web server and a client browser. Any communication and data involved in the communication done over SSL is kept private between the two parties, viz. the server and client browser.

SSL works on the public-private key encryption and requires an SSL Certificate on the server. SSL certificates come in different flavors and normally some third party agency issues them to you. Once obtained you need to enable and install the certificate on your web server. For the sake of testing you can create a test certificate in IIS or you can also use IIS Express SSL URL for the communication. Let's quickly see how both of these options can be used.

Using SSL in IIS

Let's first see how to create a test certificate in IIS. Open IIS manager and select the server under the connections pane. Locate Server Certificates in the Features view and double click on it.

Server Certificates
Server Certificates

Then click on the "Create Self-signed Certificate" link from the actions page to open a dialog as shown below:

Create Self-Signed Certificate
Create Self-Signed Certificate

Enter some friendly name for the certificate and click on OK. You should now have an entry for this new certificate under Server Certificates.

Your New Certificate
Your New Certificate

Notice that in addition to your newly created certificated there is already an entry for IIS Express Development Certificate.

Next, select the website where you wish to install the certificate and click on the Bindings option under the Edit site section of the Action pane. Add HTTPS binding using the newly created certificated as shown below:

Add Site Binding
Add Site Binding

Keep the default port number unchanged, select your certificate name in the SSL certificate dropdownlist. Click OK to close the dialog.

Using SSL in IIS Express

If you are using IIS Express as the development server, things are quite easy. Just select the project in the Solution Explorer and press F4 to open its Properties window.

Project Properties
Project Properties

Set the SSL Enabled property to True. Setting SSL Enabled to True will reveal the SSL URL. In this case it is https://localhost:44300/. You should use this URL while making Web API calls.

Forcing Requests to Use SSL

In many cases you will have both HTTP and HTTPS bindings to your website and you may want to ensure that Web API is called only over HTTPS. To accomplish this task you need to create a custom authorization filter. So, add a class in the Web API project, name it as UseSSLAttribute. Inherit UseSSLAttribute class from AuthorizationFilterAttribute class. The following code shows the completed UseSSLAttribute class:

public class UseSSLAttribute:AuthorizationFilterAttribute{  public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)  {    if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)    {      HttpResponseMessage msg = new HttpResponseMessage();      msg.StatusCode = HttpStatusCode.Forbidden;      msg.ReasonPhrase = "SSL Needed!";      actionContext.Response = msg;    }    else    {      base.OnAuthorization(actionContext);    }  }}

As you can see the UseSSLAttribute class overrides the OnAuthorization() method of the AuthorizationFilterAttribute. Inside the OnAuthorization() method the current scheme of the incoming request is checked using the RequestUrl.Scheme property. If the scheme is anything other than Uri.UriSchemeHttps a new HttpResponseMessage is constructed. The StatusCode property of the response message is set to Forbidden indicating that the server refused to process the request. The ReasonPhrase includes a short phrase describing the reason for refusal. This text will be displayed to the end user via jQuery code in case HTTPS is not used to access the Web API. Finally, the Response property of the actionContext parameter is set to the newly constructed message.

Now you can decorate the Web API action methods using the UseSSL attribute. The following  code shows a GetColors() method that has [UseSSL] attribute applied.

public class ColorController : ApiController{  [UseSSL]  public IEnumerable<string> GetColors()  {    return new string[] { "Blue", "Red", "Yellow" };  }}
To call the GetColors() method you can use the following jQuery code from a view.
$(document).ready(function () {  $("#button1").click(function () {    var options = {};    options.url = "/api/color";    options.type = "GET";    options.contentType = "application/json";    options.success = function (result) { alert(result); };    options.error = function (err) { alert(err.statusText); };    $.ajax(options);  });});

The above code assumes that the Index view has a button with ID button1 and clicking on the button will invoke the Web API. As you can see the URL is set to /api/color. The type is GET. The success function simply displays the return value of GetColors() method using an alert dialog. Similarly the error function displays the statusText of the err object using an alert dialog. If you run the application and try to invoke the above code over HTTP you will get an error as shown below:

Error Message
Error Message

Now switch to the HTTPS URL - https://localhost:44300/ - as mentioned earlier and try invoking the same code again. While using SSL your browser may give you a warning as shown below:

Warning Message
Warning Message

This warning is issued since you are using a test certificate. Click on the Continue to this website option and invoke the code. This time you should get the color values successfully.

Color Values
Color Values

Summary

If your website deals with sensitive data it is recommended to use Secure Sockets Layer or SSL. SSL establishes an encrypted channel of communication between the server and client browser. To use SSL you must install a server side certificate. For the sake of testing you can create a test certificate using IIS or use an inbuilt mechanism of IIS Express. To enforce SSL on Web API you can create a custom authorization filter that checks the request scheme. If the scheme is HTTPS only then the call is processed, otherwise an error is sent to the client.





0 0
原创粉丝点击