0

I am trying to grab the user that is logged in the Blazor app on .NET Core 5.0 by doing just the cmd @context.User.Identity.Name, but when I run the program it just shows "Welcome, "

enter image description here

So I then saw a potential work around for this which is to Inject a AuthenticationStateProvider property, call GetAuthenticationStateAsync and get User from it.

Attempting to do so:

Index.razor:

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

@code{

    protected override async Task OnInitializedAsync()
    {
        var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
        var user = authstate.User;
        var name = user.Identity.Name;
    }
}

The issue is, whenever I do @name in the <h3> it says the name 'name' does not exist in the current context. I even tried moving the @code {} before the <AuthorizeView> but it still says the same thing. Is there a reason why I cannot call the @name?

FOLLOW UP

I attempted to do the following inside of my Index.razor and doing it this way did not work, still displayed as in the screenshot. Any help would be greatly appreciated!

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@GetAuthenticationStateAsync.GetAuthenticationStateAsync().Result.User.Identity.Name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

DEBUG ATTEMPT

enter image description here

SECOND ATTEMPT, I still get the same result as in the screenshot when doing this when I attempt to use Rene's suggestion

@page "/"
@inject AuthenticationStateProvider GetAuthenticationStateAsync

<AuthorizeView>
    <Authorized>
        <h3>Welcome, <b>@Name</b></h3>
    </Authorized>
    <NotAuthorized>
        <h3>You are signed out!!</h3>
    </NotAuthorized>
</AuthorizeView>

@code{

    private string Name;

    protected override async Task OnInitializedAsync()
    {
        var authstate = await GetAuthenticationStateAsync.GetAuthenticationStateAsync();
        var user = authstate.User;
        var name = user.Identity.Name;
        Name = name;
    }
}
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
NoviceCoder
  • 249
  • 4
  • 13
  • 1
    The issue is not with the current code you use. The issue is that no authentication state is created for your app. I've been following your series of questions...let me suggest that you start here: Search Google for the string "stackoverflow enet blazor openid connect", inspect my answers and related answers, and try to improve on your app – enet Jun 30 '21 at 18:49
  • 1
    Thank you for your suggestion! I have authorization implemented in my blazor project. When I run the blazor program, I click on login in the nav menu which will redirect me to my identityserver project which then I login after I login it redirects me back into the blazor project home page. @enet – NoviceCoder Jun 30 '21 at 19:31

3 Answers3

2

Your name variable is declared within the scope of the method. Just declare a Name property above the method override just as you would in a class. Then you can Set its value in the method and read it in razor.

René
  • 2,968
  • 1
  • 18
  • 30
  • I attempted this and I still am not getting anything returned. Please see the updated post where I attempt to do this. – NoviceCoder Jun 30 '21 at 18:05
1

It looks like your issue might be that there is no data stored in "@GetAuthenticationStateAsync.GetAuthenticationStateAsync().Result.User.Identity.Name". Try running in debug with a breakpoint at that location and see if there's any value stored in Name.

M. Dave
  • 36
  • 3
  • Hmm, I am thinking that could possibly be the case now that you mention it. I attempted to debug it, however when I set a breakpoint on that line it says The breakpoint will not currently be hit. No executable code on the debugger's target code type is associated with this line. Is there a way to debug a razor component? I will upload the full message on the original post. Please see it. – NoviceCoder Jun 30 '21 at 18:02
  • @M. Dave, the link you provided should be removed from your answer. The guys in Syncfusion are so confused that they have never heard that HttpContext is not available in Blazor. There are good answers in Stackoverflow you can link to. – enet Jun 30 '21 at 18:34
  • @enet Edited out. – M. Dave Jun 30 '21 at 19:41
  • @M.Dave After getting Debug to work, name is null. Not sure how that is if I logged in through the identityserver and became authorized. – NoviceCoder Jun 30 '21 at 20:15
0

Edit: UserManager<TUser> isn't supported in Razor Components. https://docs.microsoft.com/en-us/aspnet/core/blazor/security/?view=aspnetcore-5.0


In order to identify and manipulate the currently authenticated user, I am using UserManager (Microsoft.AspNetCore.Identity.UserManager) to get the authenticated user assigned to my ApplicationUser object (my Blazor Server App uses ASP.NET Core Identity), which I can then manipulate further along with my other entities.

1st, I inject UserManager: Inject UserManager

2nd, I expose the authentication state as a cascading parameter, and declare a ClaimsPrincipal (which describes the current user). Cascading Parameter

3rd, In my OnInitializedAsync() Method, I get the ClaimsPrincipal from my authentication state, and use UserManager's GetUserAsync() to get the ApplicationUser object returned (I also redirect to Login if the user is not Authenticated): OnInitializedAsync

Daniël Hoffman
  • 805
  • 5
  • 13
  • 2
    Daniël Hoffman, the question here is about authenticating a user with the IdentityServer. In your app, the infra-structure and pipeline is created for you by default. This include creating an authentication state object which is made available through the AuthenticationStateProvider object and the CascadingAuthenticationState component. – enet Jun 30 '21 at 21:13
  • 1
    Daniël Hoffman, SignInManager and UserManager aren't supported in Razor components. You've been warned... What do you call StateHasChanged for ? – enet Jun 30 '21 at 21:23
  • 1
    @enet, well noted Apologies, StateHasChanged() was initially called before another Task that was removed - Indeed OnInitializedAsync automatically refreshes the component. I saw in MS Docs that UserManager isn't supported - However I have no errors or issues. I'd appreciate if anyone can enlighten me to the drawbacks/problem of using this Other users also used this approach: https://stackoverflow.com/a/63828699/13678817 – Daniël Hoffman Jul 02 '21 at 06:12
  • 1
    "However I have no errors or issues." But you will... Have you already published your app ? That others used it and it `worked` for them does not mean that you should follow suit. SignInManager and UserManager were created for Identity where HttpContext is available, not for Blazor. You should learn the Blazor's way to do things. That most users inject IHttpContextAccessor into their Razor component, and then access the HttpContext does not mean that you have to do the same. I've been warning, again and again, that the HttpContext object is not available in Blazor, – enet Jul 02 '21 at 06:59
  • 1
    but only few manage to take it seriously, until they publish their web apps, and realize that their apps fail. That almost all developers mutate their component parameter properties does not mean that one should do so. Component parameter properties should only be changed by the parent component, not the child component who gets it. But folks are not aware of that and code like that. Most of the time they'll face no issues, but when it happens it is so subtle that those developers can never realize what is the problem. I hope that by now you've realized the point I'm trying to do. – enet Jul 02 '21 at 07:00
  • 1
    You can inspect my answers to get valuable information. I'm really generous in providing know-how... sorry, but I won't be able to continue with this discussion here... You may email me, if you you like. See it in my profile. – enet Jul 02 '21 at 07:00
  • 1
    @enet - Many thanks for the thorough responses. I completely agree - Even though this solution does currently work in my published app as well, my uneasy concience and you have convinced me to re-engineer these components into something I can be proud of Excellent point regarding the child components changing enherited parameters - I wasn't aware of this at first, and only realised this when I ran into issues much later. Awesome I'll reach out if I get stuck. Cheers! – Daniël Hoffman Jul 03 '21 at 09:07