Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4840

How to customize Default Windows AutheticationStateProvider in Blazor server app?

$
0
0

I have a Blazor Server app that uses Windows authentication to identify users.The app "detects" the user currently browsing the app and can display domain/username correctly.

I wrote a class that checks logged in username and fetches roles from a database, then updates the current principal so that the UI can properly take advantage of the given roles for the user.

I am avoiding EntityFramework and core identity scaffolding code for reasons I can't share here.

Here is the class I wrote

public class CompanyAuthentication{    public CompanyAuthentication(AuthenticationStateProvider auth)    {        var result = auth.GetAuthenticationStateAsync().Result;        // here I have access to the current username:        string username = result.User.Identity.Name;        // now I can fetch roles from file, but for simplicity, I will use the following:        if(username.BeginsWith("admin"))        {            var claims = new ClaimsIdentity(new Claim[] {new Claim(ClaimType.Role, "admin")});            result.User.AddIdentity(claims);  // this will have an effect on UI        }    }}

I also added the above class as a service in Startup.cs

services.AddScoped<CompanyAuthentication>();

Now, in any razor page, I simply do:

@page "/counter"@inject CompanyAuthentication auth<AuthorizeView Roles="admin"><Authorized> Welcome admin </Authorized><NotAuthorized> You are not authorized </NotAuthorized></AuthorizeView>

That all works fine, as long as I don't forget to inject CompanyAuthentication in each page I intend to use.

Is there a way to automatically inject my class into every page without having to do @inject ?I am aware that I can write a custom authentication class that inherits AuthenticationStateProvider and then add it as service, but if I do that, I lose access to the currently logged in username, and thus, I can't fetch roles from the database.

I tried to use HttpContext.Current.User.Identity.Name but that is not in the scope of any part in a Balzor server app.

How can I take advantage of Windows AuthenticationStateProvider and at the same time, customize its roles, without having to inject the customization everywhere ?


Viewing all articles
Browse latest Browse all 4840

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>