Timing issue calling SecurityService when doing role based filtering in the database service

I want to return only data from my database service that was filtered according to the current user's role.

My DevDbServices.Custom.cs file contains the constructor that takes the SecurityService:

public DevDbService(DevDbContext context, NavigationManager navigationManager, SecurityService security)
  : this(context, navigationManager)
{
    this.security = security;
}

partial void OnProjectsRead(ref IQueryable<Models.DevDb.Project> items) {
    if (!security.IsInRole("Administrator")) // Problem: This returns false, even if the SecurityService later returns true for the pages
    {
        // Filter the projects by the current user's id
        // note: this line is not exactly what I do, but a filter is applied that works
        items = items.Where(item => item.Project_User == security.User.id);
    }
}

If I call security.IsInRole("Administrator") it returns false, but the user has that role. I can confirm that in pages, it is working.

How to make sure that Security.InitializeAsync(AuthenticationStateProvider); has run before I call the IsInRole() method from it?

Shall I add await security.InitializeAsync(AuthenticationStateProvider) to the constructor of DevDbService? It complains that The 'await' operator can only be used within an async method
Or can I add this somehow into the Startup.cs where I call services.AddScoped<DevDbService>()?

Thank you for any feedback.

Hi @rene,

You cannot initialize the SecurityService in Startup as there is no user that is logged in. You should use the IsInRole method only after InitializeAsync is called. This is done automatically in the Load event of every page generated by Radzen.

1 Like

Thank you, that was exactly where I should have been looking for the cause of the problem!
If anyone else gets stuck in debugging timing issues: Any database query is always executed after Security.InitializeAsync() has run (and awaited to be completed, because the pages will not load before). So, if my security data based filtering in the database service is not working properly, the error must have been in the Security.InitializeAsync(). And indeed, restructuring the way I prepared the role data within this method, caused that the roles were always available later in the database service. Thanks again for the quick response.