The following example shows how to apply antiforgery request validation to the ASP.NET MVC Dashboard control.
Follow the steps below to apply antiforgery request validation.
- Create a custom dashboard controller. If you already have a custom controller, you can skip this step.
namespace MVCxDashboardPreventCrossSiteRequestForgery.Controllers {
public class CustomDashboardController : DashboardController {
}
}
- Change the default dashboard route to use the created controller.
routes.MapDashboardRoute("dashboardControl", "CustomDashboard", new string[] { "MVCxDashboardPreventCrossSiteRequestForgery.Controllers" });
- Specify the controller name in the Web Dashboard settings.
@Html.DevExpress().Dashboard(settings => {
...
settings.ControllerName = "CustomDashboard";
}).GetHtml()
- Add
@Html.AntiForgeryToken()
if you do not have this token on the page.
@Html.AntiForgeryToken()
@Html.DevExpress().Dashboard(settings => { .... }).GetHtml()
- Implement the
DashboardValidateAntiForgeryTokenAttribute
attribute.
public sealed class DashboardValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter {
public void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException(nameof(filterContext));
}
HttpContextBase httpContext = filterContext.HttpContext;
HttpRequestBase request = httpContext.Request;
HttpCookie cookie = request.Cookies[AntiForgeryConfig.CookieName];
string token = request.Headers["__RequestVerificationToken"];
if (string.IsNullOrEmpty(token)) {
token = request.Form["__RequestVerificationToken"];
}
AntiForgery.Validate(cookie?.Value, token);
}
}
- Add the
DashboardValidateAntiForgeryTokenAttribute
attribute to the custom controller.
[DashboardValidateAntiForgeryTokenAttribute]
public class CustomDashboardController : DashboardController {
}
- Handle the
BeforeRender
event and configure the Web Dashboard control's backend options.
<script type="text/javascript">
function onBeforeRender(sender) {
var control = sender.GetDashboardControl();
control.option('ajaxRemoteService.headers', { "__RequestVerificationToken": document.querySelector('input[name=__RequestVerificationToken]').value })
}
</script>
...
@Html.DevExpress().Dashboard(settings => {
...
settings.ClientSideEvents.BeforeRender = "onBeforeRender";
}).GetHtml()
- Web Dashboard - Security Considerations
- CA3147: Mark verb handlers with ValidateAntiForgeryToken
- ASP.NET MVC Security Best Practices - Preventing Cross-Site Request Forgery (CSRF)
(you will be redirected to DevExpress.com to submit your response)