Send Anti-Forgery Token with Grid Requests in ASP.NET Core and ASP.NET MVC Projects
Environment
Product | Progress Telerik UI for ASP.NET Core Grid |
Progress Telerik UI for ASP.NET Core version | Created with the 2022.1.119 version |
Description
How can I send an anti-forgery token with the requests of a Telerik UI for ASP.NET Core Grid in ASP.NET Core and ASP.NET MVC projects?
Solution
- To include an anti-forgery token within the requests of the Grid, add an anti-forgery token to the page which contains the Grid and send the token as a parameter by using the
Data
handler.
@Html.AntiForgeryToken()
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Groupable()
.Sortable()
.Editable()
.Scrollable()
.ToolBar(x => x.Excel())
.Columns(columns =>
{
columns.Bound(column => column.Freight);
columns.Bound(column => column.ShipName);
columns.Bound(column => column.ShipCity);
columns.Command(column =>
{
column.Edit();
column.Destroy();
});
})
.Excel(excel => excel
.FileName("Export.xlsx")
.Filterable(true)
.ProxyURL("/Index?handler=Save")
)
.DataSource(ds => ds.Ajax()
.Read(r => r.Url("/Index?handler=Read").Data("forgeryToken"))
.Update(u => u.Url("/Index?handler=Update").Data("forgeryToken"))
.Create(c => c.Url("/Index?handler=Create").Data("forgeryToken"))
.Destroy(d => d.Url("/Index?handler=Destroy").Data("forgeryToken"))
.Model(m => m.Id(id => id.OrderID))
.PageSize(10)
)
.Pageable()
)
<script>
function forgeryToken() {
return kendo.antiForgeryTokens();
}
</script>
- To include additional parameters including the anti-forgery token, add the
__RequestVerificationToken
generated hidden field inside theData
handler.
@Html.AntiForgeryToken()
@(Html.Kendo().Grid<OrderViewModel>()
.Name("grid")
.Groupable()
.Sortable()
.Editable()
.Scrollable()
.ToolBar(x => x.Excel())
.Columns(columns =>
{
columns.Bound(column => column.Freight);
columns.Bound(column => column.ShipName);
columns.Bound(column => column.ShipCity);
columns.Command(column =>
{
column.Edit();
column.Destroy();
});
})
.Excel(excel => excel
.FileName("Export.xlsx")
.Filterable(true)
.ProxyURL("/Index?handler=Save")
)
.DataSource(ds => ds.Ajax()
.Read(r => r.Url("/Index?handler=Read").Data("dataFunction"))
.Update(u => u.Url("/Index?handler=Update").Data("dataFunction"))
.Create(c => c.Url("/Index?handler=Create").Data("dataFunction"))
.Destroy(d => d.Url("/Index?handler=Destroy").Data("dataFunction"))
.Model(m => m.Id(id => id.OrderID))
.PageSize(10)
)
.Pageable()
)
<script>
function dataFunction() {
return {
__RequestVerificationToken: kendo.antiForgeryTokens().__RequestVerificationToken,
additionalParameter: "test"
};
}
</script>
The kendo.antiforgerytokens
method returns an object that contains common CSRF tokens which are found on the page.