Taladan
Taladan

Reputation: 479

How to get authentificated user from database in Blazor

i want do display the Emailadress of the current logged in user. But i don't know, how to get it. I searched many hours and i found nothing. I found some snippet to get the name, but no snippet to get the other fields like email or phonenumber. The user in this snippet don't have a Id to get it from database.

@page "/"
@inject AuthenticationStateProvider AuthenticationStateProvider

<button @onclick="@LogUsername">Write user info to console</button>
<br />
<br />
@Message

@code {
    string Message = "";

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

        if (user.Identity.IsAuthenticated)
        {
            Message = ($"{user.Identity.Name} is authenticated.");
        }
        else
        {
            Message = ("The user is NOT authenticated.");
        }
    }
}

Upvotes: 2

Views: 7950

Answers (2)

Edward
Edward

Reputation: 29976

For Asp.Net Core Blazor with Identity, the Claims will not contains email claim.

For getting user, you could try UserManager.GetUserAsync(ClaimsPrincipal principal) like below:

@page "/"
@inject AuthenticationStateProvider AuthenticationStateProvider
@using Microsoft.AspNetCore.Identity;
@inject UserManager<IdentityUser> UserManager;

<button @onclick="@LogUsername">Write user info to console</button>
<br />
<br />
@Message

@code {
    string Message = "";

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

        if (user.Identity.IsAuthenticated)
        {
            var currentUser = await UserManager.GetUserAsync(user);
            Message = ($"{user.Identity.Name} is authenticated. Email is { currentUser.Email }");
        }
        else
        {
            Message = ("The user is NOT authenticated.");
        }
    }
}

Upvotes: 12

PeculiarJoe
PeculiarJoe

Reputation: 41

It sounds to me like you're not passing the email address as part of the claim back from the authentication mechanism. Not sure which provider you're using (Identity Server, etc), having a look at the following link, specifically the section that talks about Claims and Procedural Logic might be the answer to your question: here

Again, I believe the issue is with the Claim. Once you have the email coming through in the claim, you should, in theory have access to it via the common principal in code.

Upvotes: 1

Related Questions