【问题标题】:Set up JWT Bearer Token Authorization/Authentication in Hangfire在 Hangfire 中设置 JWT Bearer Token 授权/认证
【发布时间】:2017-01-14 00:40:06
【问题描述】:

如何在 Hangfire 中配置 Bearer Token Authorization/Authentication?

我有一个自定义身份验证过滤器,它在初始请求中读取身份验证令牌,但所有其他请求(Hangfire 调用)它返回 401。

如何将 Auth Token 附加到 Hangfire 执行的每个请求的标头?

令牌过期如何刷新?

【问题讨论】:

  • 你找到解决这个问题的办法了吗?
  • @MateuszMigała 不...

标签: c# authentication jwt hangfire bearer-token


【解决方案1】:

可能有点晚了,但这里有一个可能的解决方案。 这个想法来自这个帖子:https://discuss.hangfire.io/t/using-bearer-auth-token/2166

基本思想是将您的 jwt 添加为查询参数,然后在 JwtBearerOptions.Events 中收集它并将您的 MessageReceivedContext.Token 设置为等于它。 这将适用于第一个请求,但随后的请求不会附加查询参数,因此我们需要在获取 jwt 时将其添加到 cookie。 所以现在我们检查查询参数中的 jwt。如果我们找到它,则将其添加到 cookie 中。如果不在 cookie 中检查。 在配置服务中:

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

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 2014-09-24
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2021-11-08
    • 2017-09-11
    相关资源
    最近更新 更多