hangfire進階設定
##權限設定
hangfire的儀錶板會顯示目前執行的method與參數,為了不要讓有心人士拿來應用,hangfire提供IDashboardAuthorizationFilter
來實作自訂的權限控管機制
public class MyAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var owinContext = new OwinContext(context.GetOwinEnvironment());
return owinContext.Authentication.User.Identity.IsAuthenticated;
}
}
這邊使用的是owin的驗證機制 完整的實作可以參考我的範例程式
var authentication = HttpContext.GetOwinContext().Authentication;
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "admin"));
claims.Add(new Claim(ClaimTypes.Role, "admin"));
var identity = new ClaimsIdentity(claims, "HangfireLogin");
authentication.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
return Redirect("hangfire");
startup.cs
設定,這邊要注意的是順序,UseCookieAuthentication
一定要放在UseHangfireDashboard
之前,否則會發生exception
app.UseCookieAuthentication(
new CookieAuthenticationOptions()
{
AuthenticationType = "HangfireLogin",
LoginPath = new PathString("/Login/Index"),
});
app.UseHangfireDashboard(
"/hangfire",
new DashboardOptions() { Authorization = new[] { new MyAuthorizationFilter() } });
app.UseHangfireServer();
修改路徑
修改儀表板預設路徑
預設是/hangfire
可以修改成自訂的路徑
app.UseHangfireDashboard("/jobs");
修改返回的預設路徑
儀錶板右上角的連結 在DashboardOptions
設定AppPath
var options = new DashboardOptions { AppPath = VirtualPathUtility.ToAbsolute("~") };
最後附上我的實作範例程式碼