Search code examples
c#asp.nethangfire

Authentication with session when using Hangfire dashboard


I'd like to use the Session property (Session["isAdmin"]) to determine whether or not a user should be able to view the Hangfire Dashboard.

The problem is that when i'm using

HttpContext.Current.Session

this is null - eventhough i'm using this property on my other pages where is has data in it.
I'm struggling in following code snippet.
I want to let the admin role view the page.

public class AuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            var session = HttpContext.Current.Session;

            if (session == null || 
                session["username"] == null ||
                FindUserRole(session["username"].ToString()) != 
                 "ADMIN")
            {
                return false;
            }
            return true;
        }
    }

Are there any other way I can do this easier?


Solution

  • To get the context you should be using the parameter provided. Something like this should be what you are after:

        public class HangfireAuthorization : IDashboardAuthorizationFilter
        {
            public bool Authorize([NotNull] DashboardContext currentContext)
            {
               return Boolean.Parse(currentContext.GetHttpContext().Session.GetString("isAdmin"));
            }
        }