Accessinging an authenticated user outside of a view in Blazor

懵懂的女人 提交于 2020-03-02 19:33:49

问题


In my server side Blazor app, the authentication is being handled in a very unconventional way. Essentially, when a user visits the page they are authenticated using their windows credentials. At that point, a custom policy is created to look up that username in an external database (Informix) in which the authorization for that user in the application is found. Specifically for each level of authorization in the app (can update, go to this page, etc.), I am creating a new claim to add to the current user based on permissions stored in the database.

Normally in the view, I just use the AuthenticationStateProvider to get this information and it works with no issues. However, when I need to access the user information in my service classes that are handling the updates/business logic I can't seem to access the claims/User at all. For example, one use case is getting the username stored in the database for the current Windows account based on a claim added during the initial authentication to log their activities/track. Another would be grabbing the current logged in users full name from the database.

I have tried DI in the service classes w/ the authentication state providers and HTTPContext but neither of them work. I know the overall structure isn't ideal but it's what I have to work with. Any insights in how to go about this would be much appreciated!


回答1:


The authentication state provider I was injecting was not working because my service class was a singleton whereas the authentication state provider is scoped. In short, you cannot use a scoped class in a singleton (details found here: Cannot consume scoped service IMongoDbContext from singleton IActiveUsersService after upgrade to ASP.NET Core 2.0)

I changed my service classes that were depending on the authentication state provider to be scoped in the startup and it worked without issues.

TLDR; inject the AuthenticationStateProvider into your service class and make that class and any that depend on it Scoped in startup.

services.AddScoped<ServiceClass>();

Then your service class would look like the following:

private readonly _authenticationStateProvider;

public ServiceClass(AuthenticationStateProvider authenticationStateProvider)
{
     _authenticationStateProvider = authenticationStateProvider;
}

//Use authenticationStateProvider same as you do in view in class

Any classes that depend on this service class also need to be scoped instead of singletons.



来源:https://stackoverflow.com/questions/59744356/accessinging-an-authenticated-user-outside-of-a-view-in-blazor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!