Skip to content

Instantly share code, notes, and snippets.

@odinserj
Last active March 5, 2019 07:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odinserj/4d3e3c5fbcc6c3dc83488a5738591ad1 to your computer and use it in GitHub Desktop.
Save odinserj/4d3e3c5fbcc6c3dc83488a5738591ad1 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using Hangfire.Dashboard.Owin;
namespace WebApplication34
{
public class MvcAntiforgery : IOwinDashboardAntiforgery
{
protected string HeaderName = "X-CSRF-Token";
public string GetToken(IDictionary<string, object> environment)
{
AntiForgery.GetTokens(GetCookieToken(), out var cookie, out var formToken);
if (!String.IsNullOrEmpty(cookie))
{
HttpContext.Current.Response.SetCookie(new HttpCookie(
AntiForgeryConfig.CookieName,
cookie));
}
return formToken;
}
public bool ValidateRequest(IDictionary<string, object> environment)
{
try
{
if (HttpContext.Current.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
AntiForgery.Validate(GetCookieToken(), GetHeaderToken());
}
return true;
}
catch (HttpAntiForgeryException)
{
return false;
}
}
private string GetHeaderToken()
{
return HttpContext.Current.Request.Headers[HeaderName];
}
private string GetCookieToken()
{
var cookie = HttpContext.Current.Request.Cookies[AntiForgeryConfig.CookieName];
return cookie != null && !String.IsNullOrEmpty(cookie.Value) ? cookie.Value : null;
}
string IOwinDashboardAntiforgery.HeaderName => HeaderName;
}
}
@odinserj
Copy link
Author

odinserj commented Jul 31, 2018

To start using the class above, change your UseHangfireDashboard method call in the following way:

public void Configuration(IAppBuilder app)
{
    // ...
    app.UseHangfireDashboard("/hangfire", new DashboardOptions(), JobStorage.Current, new MvcAntiforgery());
}

@DaveA-W
Copy link

DaveA-W commented Aug 22, 2018

Is this Gist only appropriate if we are already using MVC on the site hosting the Hangfire dashboard?
For a standalone (OWIN) Hangfire dashboard installation - or one alongside WebApi only - the MVC AntiForgery dependency may not be available.
Can you suggest an OWIN-only means to mitigate?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment