Get servicestack roles from http context

Viewed 41

I have been using the following authorization filter for hangfire to link it to ServiceStack auth:

    public class HangFireAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                return true;
            }

            var coreContext = context.GetHttpContext();
            var httpContext = coreContext.ToRequest();
            var session = httpContext.GetSession();

            if (session != null && session.IsAuthenticated && session.Roles != null && session.Roles.Contains("Admin"))
            {
                return true;
            }

            return false;
        }
    }

context.GetHttpContext() returns DefaultHttpContext. The session has the correct username and ID but it doesn't contain the users roles.

I am using credentials login with the ServiceStack built in login.html on this project. On my other projects I am using JWT auth so I think that's maybe why this doesn't work now.

How can I get the user roles from the context when using credential auth?

Edit:

Looking in database at the saved session I can also see it has no roles "roles":[]. I am using distinct roles table and can confirm there is an entry for this user with Admin role. I tried manually adding roles to user auth table column but that didn't change anything.

1 Answers

Use HasRole() to validate whether a User is in a Role, e.g:

return session.HasRole(role, httpContext.TryResolve<IAuthRepository>());
Related