Tuesday, May 5, 2020

Hangfire Dashboard Authentication and Authorization with .Net Framework and OWIN

Used the following the link as a guide

To run the sample solution. Everything is self-contained.
1. Unzip
2. Open solution
3. Clean Solution (Roslyn compiler issue)
4. run

Sample Solution Setup
Created a new project ASP.NET Web Application (.NET Framework)

Enter the name of the project

Choose Single Page Application

Install NuGet package Hangfire

Add local database under App_Data



 Set web.config connectionStrings section to


<connectionStrings>
  <add name="DefaultConnectionconnectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Hangfire.mdf;Initial Catalog=Hangfire;Integrated Security=TrueproviderName="System.Data.SqlClient" />
</connectionStrings>

Add new class HangfireAuthorizationFilter.cs

using Microsoft.Owin;
using Hangfire.Dashboard;
[assembly: OwinStartup(typeof(HangfireDashboardAuth.Startup))]

namespace HangfireDashboardAuth
{
    public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
    {
        public bool Authorize(DashboardContext context)
        {
            if(context == null)
            {
                //may need to add logging that this has happend.
                return false;
            }

            var owinContext = new OwinContext(context.GetOwinEnvironment());
           
            if(owinContext == null ||
                owinContext.Authentication == null ||
                owinContext.Authentication.User == null ||
                owinContext.Authentication.User.Identity == null)
            {
                //may need to add logging that this has happend.
                return false;
            }

            // Allow all authenticated users that have HangfireAdmin role
            return owinContext.Authentication.User.Identity.IsAuthenticated && owinContext.Authentication.User.IsInRole("HangfireAdmin");
        }
    }
}

**nore [assembly: OwinStartup(typeof(HangfireDashboardAuth.Startup))]  this will be different depending what the project name space is.

Change Startup.cs

using Microsoft.Owin;
using Owin;
using Hangfire;

[assembly: OwinStartup(typeof(HangfireDashboardAuth.Startup))]
namespace HangfireDashboardAuth
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
 

            app.UseHangfireDashboard("/hangfire"new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });
        }
    }
}

Configure Database
Double click on Hangfire.mdf, there are no tables.


Create Hangfire Tables
(Hangfire auto-creates the Hangfire tables when there are no Hangfire tables present)
To do this start the application (F5), should land on the default page

Navigate to https://localhost:44388/hangfire it will auto redirect back to the login page thanks to the HangfireAuthorizationFilter.
Back at the database, the Hangfire tables have been created.


Create ASP net tables
Try to login


The ASP net tables are now created


Register Users
Click Register

Add the following users for testing
admin@test.com
readonly@test.com

Should now see the new users.


Add Roles
Run the following script

INSERT INTO AspNetRoles (IdNameVALUES ('4f6e6a25-e532-423f-ba60-88bdae3ef6b8''HangfireAdmin')
INSERT INTO AspNetRoles (IdNameVALUES ('f222ed9b-354d-4621-bfaf-8e8d21276ac2''HangfireReadOnly')

Add to AspNetUserRoles association
Associate admin@test.com to the role HangfireAdmin


Test
1.       Not logged in, try to navigate to https://localhost:44388/hangfire will auto redirect to the login page
2.       Login as readonly@test.com, and try to navigate to https://localhost:44388/hangfire
403 Error returned because the user is not associated to HangfireAdmin role.

3.       Login as admin@test.com, and try to navigate to https://localhost:44388/hangfire