Last active
March 5, 2019 07:23
-
-
Save odinserj/4d3e3c5fbcc6c3dc83488a5738591ad1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
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
To start using the class above, change your
UseHangfireDashboard
method call in the following way: