Ends in:
7 DAYS
22 HRS
30 MIN
49 SEC
Ends in:
7 D
22 H
30 M
49 S
Open Closed

Background Jobs & Saas Module - Authorisation Issues #6848


User avatar
0
auxo-devsu created
  • ABP Framework version: v8.0.0
  • Database System: EF Core (SQL Server)
  • Tiered (for MVC) or Auth Server Separated (for Angular): Tiered
  • Exception message and full stack trace:
  • Steps to reproduce the issue:

I'm using background jobs to perform certain tasks. One of them is to create tenants based on our requirements.

The issue I'm dealing with is authorising my processes to use **IEditionAppService **and ITenantAppService, which require certain policies ("Saas.Editions" and "Saas.Tenants")

Given that my process is initiated in the background, obviously it is not authenticated when trying to call those endpoints resulting in Abp Auth Exception.

Question: What's the best way for me to bypass the need for authorisation on those services or for me to call them as if they could "allow anonymous"? Using context.Services.AddAlwaysAllowAuthorization(); is not an option unless we could do it just in the context of the background jobs.

If possible, provide me with examples on how I can elevate the privileges of my background processes to run as 'admin'.

Thanks!


2 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    You can create a bot user for the Background Job:

    public class MyBackgroundJob : AsyncBackgroundJob<MyBackgroundJobArgs>
    {
        private readonly ICurrentPrincipalAccessor _principalAccessor;
        private readonly IdentityUserManager _identityUserManager;
    
        public MyBackgroundJob(ICurrentPrincipalAccessor principalAccessor, IdentityUserManager identityUserManager)
        {
            _principalAccessor = principalAccessor;
            _identityUserManager = identityUserManager;
        }
    
        public override async Task ExecuteAsync(MyBackgroundJobArgs args)
        {
            using (_principalAccessor.Change(await CreateBotUserClaimsPrincipalAsync()))
            {
                //....
            }
        }
    
        private async Task<ClaimsPrincipal> CreateBotUserClaimsPrincipalAsync()
        {
            var user = await  _identityUserManager.FindByNameAsync("Bot User name");
            var roles = await _identityUserManager.GetRolesAsync(user);
            var claims = new List<Claim>
            {
                new Claim(AbpClaimTypes.UserId, user.Id.ToString()),
                new Claim(AbpClaimTypes.UserName, user.UserName),
                new Claim(AbpClaimTypes.Email,user.Email)
            };
            claims.AddRange(roles.Select(x => new Claim(AbpClaimTypes.Role, x)));
            return new ClaimsPrincipal(new ClaimsIdentity(claims));
        }
    }
    
  • User Avatar
    0
    auxo-devsu created

    Amazing! That works! Thanks.

Made with ❤️ on ABP v9.1.0-preview. Updated on November 20, 2024, 13:06