Hangfire实战--添加DashBoard登录权限
概述
Hangfire Dashboard为我们提供了可视化的对后台任务进行管理的界面,我们可以直接在这个页面上对定时任务进行删除、立即执行等操作,如下图所示:
引用安装
1、项目地址:https://github.com/HangfireIO/Hangfire.Dashboard.Authorization
2、在已经安装Hangfire基本组件的项目中,通过Nuget程序包管理器添加Hangfire.Dashboard.Authorizaiton或Nuget控制台添加。通过Nuget程序包管理控制台安装的命令:
- Install-Package Hangfire.Dashboard.Authorization
使用
在Startup.cs中的Configuration方法中添加以下代码:
在代码中的Login和Password后面写登录的用户名和密码,这样在下次打开Hangfire的Dashboard时,就会弹出需要输入用户名和密码的窗口了,输入之后就可了打开Dashboard了
var filter = new BasicAuthAuthorizationFilter(
new BasicAuthAuthorizationFilterOptions
{
SslRedirect = false,
// Require secure connection for dashboard
RequireSsl = false,
// Case sensitive login checking
LoginCaseSensitive = false,
// Users
Users = new[]
{
//new BasicAuthAuthorizationUser
//{
// Login = "Administrator-1",
// // Password as plain text
// PasswordClear = "test"
//},
new BasicAuthAuthorizationUser
{
Login = "×××",//用户名
// Password as SHA1 hash
Password = new byte[]{ 0x54, ..., 0xa8 }//密码
}
}
});
var options = new DashboardOptions
{
AuthorizationFilters = new[] {
filter
}
};
app.UseHangfireDashboard("/TaskManager", options); //可以改变Dashboard的url
登录密码的生成
string password = "<your password here>";
using (var cryptoProvider = System.Security.Cryptography.SHA1.Create())
{
byte[] passwordHash = cryptoProvider.ComputeHash(Encoding.UTF8.GetBytes(password));
string result = "new byte[] { " +
String.Join(",", passwordHash.Select(x => "0x" + x.ToString("x2")).ToArray())
+ " } ";
}