Get User name in Blazor Webassembly

Hello team,

I am not sure if this is specific to Blazor, but anyhow i need help in this.

When the user launches the Blazor Webassembly app from a browser, is there any way to get the windows logged in user name? I tried  injecting the  AuthenticationStateProvider in my razor component code behind file.

Next in the Program.cs file added the below to the service collection.


 builder.Services.AddOptions();

 builder.Services.AddAuthorizationCore();

 builder.Services.AddScoped<AuthenticationStateProvider, TestAuthStateProvider>();


The TestAuthStateProvider class code is implemented as below.

 public class TestAuthStateProvider: AuthenticationStateProvider

    {

        public async override Task<AuthenticationState> GetAuthenticationStateAsync()

        {

            await Task.Delay(1500);

            var anonymous = new ClaimsIdentity();

            return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(anonymous)));

        }

    }


In the code behind file of razor component the code is written as below. I always get a null value for the Name .


 var state=await AuthenticationStateProvider.GetAuthenticationStateAsync();

 var user = state.User.Identity.Name;



Any help is highly appreciated.


Thanks

Baba


4 Replies

RR Rajendran R Syncfusion Team February 22, 2022 10:50 PM UTC

Hi Baba,


Generally, the Blazor WebAssembly (WASM) App allows users to get usernames through Web API services. We couldn’t make a successful sample based on a share code snippet.


Could you please try the solution which suggested in below links?


https://stackoverflow.com/questions/63104080/getting-userid-of-current-user-blazor-webassembly

https://docs.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/?view=aspnetcore-6.0


Meanwhile, we will try to create a sample and share here if we meet your requirements.


Regards,

Rajendran R



BG Baba Goud Gadiga replied to Rajendran R February 23, 2022 09:36 AM UTC

Hello Rajendran,


Thank you for looking at the issue and posting some of the hints. Our client application calls the Web API hosted on IIS to get the data from DB. So I did add a API method to return the user name using the below code.

The API returns the valid windows user id name when run on the local machine for debugging purpose, the issue is when the API is hosted on the IIS on a different server.

The API returns the Identity of the Application Pool. We set the Identity of the application pool with a custom account(service account) as the API needs to access the database located on the remote server.


public string GetUserName()

{

//return Environment.UserName;

return System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

}


Thanks



BG Baba Goud Gadiga replied to Baba Goud Gadiga February 24, 2022 07:47 AM UTC

I was able to get the username from the Web API when hosted on IIS. 

1) In the launchsettings.json file changed the following attributes.

"windowsAuthentication": true,

 "anonymousAuthentication": false,


2) Enabled Windows and disabled Anonymous authentication in the IIS where my Web API is hosted.

3) In the Startup.cs file of the WebAPI configured the below

           services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

4) In the controller method, added a property 

 private readonly IHttpContextAccessor _httpContextAccessor;

and initialized it in the constructor as below.


 public UsersController(IUsersRepository usersRepository,

            IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)

        {            _usersRepository = usersRepository;

                _webHostEnvironment = webHostEnvironment;

                _httpContextAccessor = httpContextAccessor;

        }

   

5) Finally in the API method 

 public string GetUserByName()

        {

                var principal=_httpContextAccessor.HttpContext.User;

                return  principal.Identity.Name;

       }



Everything looks good so far, the actual issue is with the Blazor Webassembly project which invokes the above Web API method, i get a null value upon invoking. I made the same changes to launchsettings.json file and in IIS( Enabled Windows and disabled Anonymous authentication in the IIS )..


Any thoughts what could be wrong? 


Thanks,

Baba      



JL Joshna Lingala Uthama Reddy Lingala Syncfusion Team March 9, 2022 08:56 AM UTC

Hi Baba, 
 
Sorry for the delay. 
 
We have validated the reported issue at our end. When we are using “HttpContextAccessor” in the WebAssembly project the errors are thrown. We have raised the issue in the GitHub. Requesting to follow up the ticket for more details. Please find the GitHub ticket below 
 
Please get back to us if you need further assistance. 
 
Regards, 
Joshna L 


Loader.
Up arrow icon