Enabling and customizing security for ASP.net Web API services

Source: Internet
Author: User
Tags json csrf attack

For the most common scenario-web Web API services on the same site, it is almost superfluous to discuss the security of the ASP.net Web API. If the user is authenticated and authorized to access the WEB forms/views that contain JavaScript that uses the service, the service may already have all the security it needs. This is due to ASP.net, which sends the Cookie and authentication information that it uses to authenticate the page request as part of any client JavaScript request for the service method. But there is a very important exception: ASP.net cannot automatically defend against cross site request forgery (CSRF/XSRF) attacks (detailed later).

In addition to CSRF, there are two scenarios worth exploring for WEB API service protection. The first scenario is when the consumer of a service is a client, not a page that is on the same site as Apicontrollers. These clients may not have been audited for forms authentication, or they may not have obtained the cookies and tokens that ASP.net used to control service access.

The second scenario is when you need to add an authentication that exceeds the scope of the ASP.net security feature for the service. The default authentication provided by ASP.net is based on the identity assigned to the request during the authentication period asp.net. You may want to extend the identity to authorize access based on an identity name or a condition other than the role.

The Web API provides a variety of options to deal with both scenarios. In fact, I'm going to talk about accepting the Web API request context, but because Web APIs and Web Forms and MVC are all based on ASP.net, readers who understand Web Forms or MVC security will be very familiar with the tools described in this article.

It is important to note that although the WEB API provides multiple authentication and authorization options, security starts with the host (IIS or the host that was created from the time it was hosted). For example, if you need to ensure the confidentiality of communication between the Web API service and the client, you should at least turn on SSL. But this is the responsibility of the site administrator, not the developer. In this article, I'll ignore the host side and focus on the work that developers can/should do to ensure the safety of Web API services (whether SSL is turned on or not, the tools I'm talking about are working properly).

Protect against Cross-site request forgery attacks

When a user accesses an ASP.net Web site that uses forms authentication, ASP.net generates a Cookie indicating that the user has been authenticated. The browser sends the Cookie every time a subsequent request is made to the site, regardless of where the request came from. As long as any authentication scheme that causes the authentication information received before the browser automatically sends is present, your site can become a CSRF attack target. After the site provides a secure cookie to the browser, if a user visits a malicious site, the site can send a request to your service and use the authentication Cookie that was received before the browser to launch the attack.

To protect against CSRF attacks, you need to generate a security token on the server side and embed it in a page that you want to use in a client call. Microsoft provides a antiforgery class and a GetToken method that generates tokens that are specific to the requesting user, and, of course, the user can be an anonymous user. The following code generates two tokens and embeds them into the ASP.net MVC ViewBag that can be used in View:

          [Authorize (roles= "manager")]
Public ActionResult Index ()
{
  string cookietoken;
  string Formtoken;
  Antiforgery.gettokens (null, out Cookietoken, out formtoken);
  Viewbag.cookietoken = Cookietoken;
  Viewbag.formtoken = Formtoken;
  Return View ("Index");
}

Any JavaScript calls to the server require that the token be returned as part of the request (CSRF sites do not have such tokens and cannot return them). The following code (in View) dynamically generates a token to join the JAVASCRIPT call in the request header:

        $.ajax ("Http://phvis.com/api/Customers", {
type: "Get",
contentType: "Application/json",
headers: {
  ' Formtoken ': ' @ViewBag. Formtoken ', '
  cookietoken ': ' @ViewBag. Cookietoken '}});

A slightly more complex solution is to embed the token into the hidden field in View, making the JavaScript code less compelling. The first step in this process is to add the token to the ViewData dictionary:

          viewdata["Cookietoken"] = Cookietoken;
viewdata["Formtoken"] = Formtoken;
Next, embed the data into the hidden field in View. 

when using the HtmlHelper Hidden method, simply pass a key value from the viewdate to generate the correct input tag:
@Html. Hidden ("Formtoken")

The generated input tag uses the ViewData key as the name and ID attribute of the tag, and the data retrieved from the ViewData dictionary is placed in the tagged value attribute. The input tags generated by the previous code will look like the following:

<input id= "Formtoken" name= "Formtoken" type= "hidden" ... value= ... "token

You can then retrieve values from the input tags and use them in Ajax calls with JavaScript code (stored in separate files with View):

        $.ajax ("Http://localhost:49226/api/Customers", {
type: "Get",
contentType: "Application/json"
, Headers: {
  ' Formtoken ': $ ("#formToken"). Val (),
  ' Cookietoken ': $ ("#cookieToken"). Val ()});

In the ASP.net Web form, insert a JAVASC containing an embedded token by using the RegisterClientScriptBlock method of the ClientScriptManager object (which can be retrieved from the Page's ClientScript property) Ript code, you can also achieve the same purpose.

          String codestring = "function Callservice () {" +
  "$.ajax (' Http://phvis.com/api/Customers ', {" +
  "type: ' Get '), ContentType: ' Application/json ', ' +
  ' headers: {' Formtoken ': ' & Formtoken & ', ' + '
  ' cookietoken ': ' "& Amp Cookietoken & "'}});}"
This. Clientscript.registerclientscriptblock (
  typeOf (This), "Loadcustid", codestring, True);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.