1

Adding Anti Forgery to an Asp.Net Core MVC app is easily done by applying the ValidateAntiForgeryToken attribute to the action and using a sp-antiforgery=true in the form.

How can I secure a CRUD operation of Web API controller that uses individual authentication with the Authorize attribute and a Kendo MVC Grid in client side?

2
  • Hi Sean thanks for your valueable answer. I UPVOTED AND SET AS ANSWERED IT. Today I only found that link dotnetcurry.com/aspnet/890/… from 2013 and wanted to be sure that it still works with Asp.Net Core and Kendo UI for jQuery. THANKS AGAIN ! Commented Feb 14, 2017 at 21:20
  • any time sir . I have given a reference to that link as well as kendo based specific implementation Commented Feb 14, 2017 at 21:22

2 Answers 2

2

You can create a controller and inject IAntiforgery for getting the XsrfToken and then send this with request to validate.

[Route("api/[controller]")]
public class XsrfTokenController : Controller
{
    private readonly IAntiforgery _antiforgery;

    public XsrfTokenController(IAntiforgery antiforgery)
    {
        _antiforgery = antiforgery;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var tokens = _antiforgery.GetAndStoreTokens(HttpContext);

        return new ObjectResult(new {
            token = tokens.RequestToken,
            tokenName = tokens.HeaderName
        });
    }
}

You can read more about it on here

Sign up to request clarification or add additional context in comments.

2 Comments

How can I add that to the Kendo UI for jQuery Grid in the client side? Thanks.
@Ahmar: How can I refresh the token after a successful login?
2

A CSRF attack can only happen when cookies are shared on the client. By that I mean that the client has access to cookies from multiple domains (such as a web browser storing cookies for each site you visit). However, a web application API client typically only contacts a single domain (that of your API). Any cross site attack cannot use cookies within your API as the client is not shared (HTTP client in web application is separate than HTTP client in the mobile browser - or should be). Therefore your web application API should already be safe against CSRF if the API is for your mobile application only.

There is a generic guide for implementing anti forgery token in webapi discussed here.

Preventing CSRF Hacks in ASP.NET WebAPI

But since you are using kendo grid we have to look into something that work specifically for Kendo Grid.

1 :Using WEBAPI endpoint:

you can either do like using data : Send antiforgery token the regular way through the Data function of the Read transport

transport: {
    read: {
        url: url,
        type: "POST",
        data: {
            __RequestVerificationToken: $("input[name=__RequestVerificationToken]").val()
        }
    }

Or using a parameter map :

   @Html.AntiForgeryToken()

 <div id="grid"></div>
<script>
    $(document).ready(function () {
        $("#grid").kendoGrid({
            dataSource: {
                type: "json",
                transport: {
                    read: {
                        url: "/Home/GetProducts",
                        type: "POST"
                    },
                    update: {
                        url: "/Home/UpdateProduct",
                        type: "POST"
                    },
                    parameterMap: function (options, operation) {
                        options.__RequestVerificationToken = $("input[name=__RequestVerificationToken]").val();
                        return options;
                    }
                },
                schema: {
                    model: {
                        id: "ID",
                        fields: {
                            ID: { type: "number", editable: false },
                            Name: { type: "string" }
                        }
                    }
                },
                pageSize: 10
            },
            height: 250,
            filterable: true,
            sortable: true,
            pageable: true,
            editable: "inline",
            columns: ["ID", "Name", {command: "edit"}]
        });
    });
</script>

your webapi controller

        [ValidateAntiForgeryToken]
        public ActionResult GetProducts()
        {
            return Json(products);
        }

        [ValidateAntiForgeryToken]
        public void UpdateProduct(Product updatedProduct)
        {
            var product = products.FirstOrDefault(p => p.ID == updatedProduct.ID);
            UpdateModel(product);
        }

2 : Using Ajax based calls

we will make you of Data function in Datasource to send anti forgery token to CRUD ops

you will need to add this on page to generate the token

@Html.AntiForgeryToken()

Then in a kendo grid Datasource configuration do this

.DataSource(dataSource => dataSource
                .Ajax()
                .Model(model=>model.Id(m=>m.PersonID))
                    .Read(read => read.Action("GetPersons","Home").Data("sendAntiForgery"))
                    .Update(up => up.Action("UpdatePerson", "Home").Data("sendAntiForgery"))
            )

Here is the javascript method that will send the token to CRUD ops

<script type="text/javascript">
    function sendAntiForgery() {
        return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
    }
</script>

The controller on server side

        [ValidateAntiForgeryToken]
        public ActionResult GetPersons([DataSourceRequest] DataSourceRequest dsRequest)
        {
            var result = persons.ToDataSourceResult(dsRequest);
            return Json(result);
        }

        [ValidateAntiForgeryToken]
        public ActionResult UpdatePerson([DataSourceRequest] DataSourceRequest dsRequest, Person person)
        {
            if (person != null && ModelState.IsValid)
            {
                var toUpdate = persons.FirstOrDefault(p => p.PersonID == person.PersonID);
                TryUpdateModel(toUpdate);
            }


            return Json(ModelState.ToDataSourceResult());
        }

for more help look into these links on kendo documentation

http://www.telerik.com/forums/kendo-grid-antiforgerytoken#fPGvzDjUyEahRPNaTEo_TA http://www.telerik.com/forums/anti-forgery-tokens#VA3XA6lbT0WgeOwOQ3w_nQ

1 Comment

I get a 400 (Bad Request) with approach 1.) on the /api/Read endpoint. Can I email you ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.