Search code examples
hangfire

How to restrict allowed methods in Hangfire Server


I'd like to restrict which jobs are processed by Hangfire server to a certain set of whitelisted methods or classes. For example, if client A queues a Hangfire job that uses a non-whitelisted method, then server B should not execute it.

I thought of using Job Filters for this purpose

    class AllowedJobFilter : JobFilterAttribute
    {
        var getMethodInfo(Action a)
        {
            return a.Method;
        }

        void OnPerforming(PerformingContext context) {
            // Only allow jobs which run Console.WriteLine()
            var allowedMethods = new List<MethodInfo>() {
                getMethodInfo(Console.WriteLine),
            };
            if (!allowedMethods.Contains(context.BackgroundJob.Job.Method)
            {
               throw Exception("Method is not allowed");
            }
    }

...
        GlobalConfiguration.Configuration
            .UseFilter(new AllowedJobFilter())

I'm not sure this approach will work as expected (since there's nothing that says Hangfire can't catch and ignore exceptions from the JobFilterAttribute), and this approach will fail the job instead of skipping it, which may not be desirable. Is there a better way to restrict which jobs can run on a server?


Solution

  • Per the response on the Github issue I submitted:

    https://github.com/HangfireIO/Hangfire/issues/1403

    burningice2866 commented 14 days ago

    You can implement the OnCreating method in your JobFilter and set context.Canceled to true. As you can see here jobs can be ignored during creation using this approach.

    Hangfire/src/Hangfire.Core/Client/BackgroundJobFactory.cs
    
    Line 112 in 23d81f5
    if (preContext.Canceled)
    {
             return new CreatedContext(preContext, null, true, null);
    }
    

    @burningice2866 Contributor burningice2866 commented 14 days ago

    You should be able to set Canceled as well in the OnPerforming as stated here

    Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs
    
    Line 147 in 23d81f5
    
     if (preContext.Canceled)
     {
             return new PerformedContext(
                 preContext, null, true, null);
     }