You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Hangfire Dashboard的身份验证登出功能?

Hangfire Dashboard 登出功能实现方案

你当前用的是Basic认证,浏览器会自动缓存凭证,默认Hangfire Dashboard没有登出选项,以下是具体实现步骤:

1. 新增登出端点

在Startup.cs的Configure方法中,添加专门处理登出的路由,通过返回401状态码让浏览器清除缓存的认证凭证:

app.Map("/hangfire/logout", app =>
{
    app.Run(async context =>
    {
        // 触发浏览器清除Basic Auth凭证
        context.Response.StatusCode = 401;
        context.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Hangfire Dashboard\"");
        
        // 重定向回Hangfire Dashboard,自动触发登录弹窗
        context.Response.Redirect("/hangfire");
    });
});

2. 自定义Dashboard导航菜单

创建导航提供者类,把登出按钮添加到Dashboard的导航栏:

public class LogoutNavigationProvider : INavigationMenuProvider
{
    public IEnumerable<MenuItem> GetMenuItems()
    {
        yield return new MenuItem
        {
            Text = "登出",
            Url = "/hangfire/logout",
            Icon = "fa fa-sign-out" // 复用Hangfire默认的Font Awesome图标
        };
    }
}

3. 更新Hangfire Dashboard配置

修改原有UseHangfireDashboard的配置,添加自定义导航,同时把AppPath改成相对路径(避免硬编码localhost地址,适配部署场景):

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
    IgnoreAntiforgeryToken = true,
    AppPath = "/swagger/index.html",
    DashboardTitle = "My Website",
    Authorization = new[]
    {
        new HangfireBasicAuthenticationFilter.HangfireCustomBasicAuthenticationFilter
        {
            User = "user",
            Pass = "passs"
        }
    },
    // 添加自定义导航提供者
    NavigationMenu = new List<INavigationMenuProvider>
    {
        new LogoutNavigationProvider()
    }
});

效果说明

点击Dashboard导航栏的「登出」按钮后,浏览器会清除缓存的Basic Auth凭证,自动重定向回Hangfire首页并弹出登录表单;此时点击浏览器的返回按钮,也会因为凭证已清除而重新触发登录验证。

内容的提问来源于stack exchange,提问作者Choy Roman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 08:02:41