Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current (logged) user in ASP.NET Core 3.0 .razor page

I'm testing the waters with a blazer server-side app and trying to get the logged user in a .razor page. This

UserManager.GetUserAsync(User)

works in .cshtml view, but I cannot find a way to get it to work in .razor page. There is no "User" property to access. I use the IdentityUser with my ApplicationUser model that extends IdentityUser. I'm using AspNetCore 3.0 Preview 6.

like image 410
Lucho Gizdov Avatar asked Jul 10 '19 12:07

Lucho Gizdov


People also ask

How can we get logged in user details in asp net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How do I get current user in .NET core?

In ASP.NET Framework, you'd do this by accessing HttpContext. Current. User and its properties (see below for an example), in . NET Core this is handled via dependency injection.

What is HttpContext current user identity?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.


2 Answers

If you surround your code with the AuthorizeView component you can get access to a context object that supplies the current user.

<AuthorizeView>
    <Authorized>
        <h1>Hello, @context.User.Identity.Name!</h1>
        <p>You can only see this content if you're authenticated.</p>
    </Authorized>
    <NotAuthorized>
        <h1>Authentication Failure!</h1>
        <p>You're not signed in.</p>
    </NotAuthorized>
</AuthorizeView>

If you don't want to use that approach you can request a cascading parameter called authenticationStateTask, which is provided by the CascadingAuthenticationState.

@page "/"

<button @onclick="@LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            Console.WriteLine($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Console.WriteLine("The user is NOT authenticated.");
        }
    }
}
like image 126
Chris Sainty Avatar answered Oct 24 '22 09:10

Chris Sainty


What I did:

  1. added this to Startup.ConfigureServices
services.AddHttpContextAccessor();
  1. used this to get the username in my .razor page, these 2 lines first
@inject UserManager<WebPageUser> UserManager
@inject IHttpContextAccessor HttpContextAccessor
  1. then the call to show the username like this:
<p>Hello @UserManager.GetUserName(HttpContextAccessor.HttpContext.User)</p>
like image 29
W. Flores Avatar answered Oct 24 '22 10:10

W. Flores