Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up JWT Bearer Token Authorization/Authentication in Hangfire

How can you configure Bearer Token Authorization/Authentication in Hangfire?

I have a custom authentication filter that read the Authentication Token on the initial request but all other requests (Hangfire calls) it return 401.

How can I attach Auth Token to the header of every request that Hangfire does?

How can I refresh the token when it is expired?

like image 227
Valter Avatar asked Sep 06 '16 14:09

Valter


People also ask

Can I use JWT as bearer token?

JSON Web Token (JWT, RFC 7519) is a way to encode claims in a JSON document that is then signed. JWTs can be used as OAuth 2.0 Bearer Tokens to encode all relevant parts of an access token into the access token itself instead of having to store them in a database.

How do I send a JWT in Authorization header?

We can send this token to other endpoints. This can be done easily. We have to add an authorization header in our request and this will be a Bearer TOKEN. To avoid any manual copy-pasting of JWT token, we can use variables to add a script in the Tests tab of API request which is generating token.

Can JWT be used for authentication or authorization?

Both API key and JWT are used for authentication and authorization, but they do it differently. Authentication allows the user or application to use one or more methods of the API. Authorization defines how they can use those methods.


1 Answers

Maybe a bit late but here's a possible solution. The idea comes from this post: https://discuss.hangfire.io/t/using-bearer-auth-token/2166

The basic idea is to add your jwt as a query param then collect it in JwtBearerOptions.Events and set your MessageReceivedContext.Token equal to it. This will work for the first request but the requests that follow from it won't have the query param attached so we need to add the jwt to a cookie when we get it. So now we check for the jwt in the query param. If we find it then add it to a cookie. If not check for it in the cookies. In 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 Auth Filter:

 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
like image 104
ShanieMoonlight Avatar answered Sep 19 '22 10:09

ShanieMoonlight