如何在Hangfire中配置承载令牌授权/身份验证?
我有一个自定义身份验证过滤器,在初始请求中读取身份验证令牌,但所有其他请求(Hangfire调用)返回401.
如何将Auth Token附加到Hangfire的每个请求的标头?
如何在令牌过期时刷新令牌?
答案 0 :(得分:1)
也许有点晚,但这是一个可能的解决方案。 这个想法来自这篇文章:https://discuss.hangfire.io/t/using-bearer-auth-token/2166
基本思想是将jwt添加为查询参数,然后将其收集到JwtBearerOptions.Events中,并将MessageReceivedContext.Token设置为与之相等。 这将对第一个请求有效,但随后的请求将不附加查询参数,因此我们需要在获得cookie时将jwt添加到cookie。 因此,现在我们在查询参数中检查jwt。如果找到它,则将其添加到Cookie中。如果没有,请在Cookie中进行检查。 在ConfigureServices中:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer((Action<JwtBearerOptions>)(options =>
{
options.TokenValidationParameters =
new TokenValidationParameters
{
LifetimeValidator = (before, expires, token, param) =>
{
return expires > DateTime.UtcNow;
},
IssuerSigningKey = JwtSettings.SecurityKey,
ValidIssuer = JwtSettings.TOKEN_ISSUER,
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = false,
NameClaimType = GGClaimTypes.NAME
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = mrCtx =>
{
// Look for HangFire stuff
var path = mrCtx.Request.Path.HasValue ? mrCtx.Request.Path.Value : "";
var pathBase = mrCtx.Request.PathBase.HasValue ? mrCtx.Request.PathBase.Value : path;
var isFromHangFire = path.StartsWith(WebsiteConstants.HANG_FIRE_URL) || pathBase.StartsWith(WebsiteConstants.HANG_FIRE_URL);
//If it's HangFire look for token.
if (isFromHangFire)
{
if (mrCtx.Request.Query.ContainsKey("tkn"))
{
//If we find token add it to the response cookies
mrCtx.Token = mrCtx.Request.Query["tkn"];
mrCtx.HttpContext.Response.Cookies
.Append("HangFireCookie",
mrCtx.Token,
new CookieOptions()
{
Expires = DateTime.Now.AddMinutes(10)
});
}
else
{
//Check if we have a cookie from the previous request.
var cookies = mrCtx.Request.Cookies;
if (cookies.ContainsKey("HangFireCookie"))
mrCtx.Token = cookies["HangFireCookie"];
}//Else
}//If
return Task.CompletedTask;
}
};
}));
HangFire身份验证过滤器:
public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize(DashboardContext context)
{
var httpCtx = context.GetHttpContext();
// Allow all authenticated users to see the Dashboard.
return httpCtx.User.Identity.IsAuthenticated;
}//Authorize
}//Cls