Base solution for your next web application
Open Closed

Running a Hangfire background job with the permissions of the user that started it #10239


User avatar
0
Astech created

We are using Hangfire to run a long running job. When the job is finished we require it to update a column in the database:

public override void Execute(BuildLogJobArgs args)
{
    using (CurrentUnitOfWork.SetTenantId(args.TenantId))
    {
        var itemsCount = 100;
        for (int i = 0; i <= itemsCount; i++)
        {
            //Simulating work
            System.Threading.Thread.Sleep(100);
            SendProgress(i, itemsCount);
        }
        // Send notification to user.
        AsyncHelper.RunSync(() => _appNotifier.LogBuiltAsync(args));

        //Finish the job
        AsyncHelper.RunSync(() => _logsAppService.FinishBuildLog(args.LogId));
    }
}

_logsAppService.FinishBuildLog_logsAppService.FinishBuildLog is responsible for updating the database. However when run we are getting:

Abp.Authorization.AbpAuthorizationException: Current user did not login to the application!

The FinishBuildLog method is protected with [AbpAuthorize....] and we want this to continue to be the case for obvious security reasons.

In which case how can we allow the running job the same permissions to the app service that the user that started the job would have? We do have the User object available to us in the BuildLogJobArgs.

Or is there a better way to go about this?

Thanks,

Scott


2 Answer(s)
  • User Avatar
    0
    musa.demir created

    Hi @Astech

    Can you please try that. Pass current user's tenant and userid to background job as parameter than use AbpSession.Use method to override session https://aspnetboilerplate.com/Pages/Documents/Abp-Session#overriding-current-session-values

  • User Avatar
    0
    Astech created

    Perfect! Many thanks :)