简体   繁体   中英

Blazor - How to call method to set user data after successful log in

I have a hosted Blazor WebAssembly app that I'm forcing users to sign in at start up. I have put this logic in the MainLayout.razor page like so:

protected override async Task OnInitializedAsync()
    {
        var user = (await AuthenticationStateTask).User;
        if (user.Identity.IsAuthenticated)
        {
            await SetUserInfo(user);
        }
        else
        {
            AuthMessage = "User is NOT authenticated";
            NavigationManager.NavigateTo($"authentication/login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}");
        }
    }

What I want to do is call the SetUserInfo method after the user has logged in successfully (at the moment it will always navigate to the log in page when starting the app), but can't figure out how to do it. It seems that the OnInitializedAsync method only runs once, unless you manually refresh the page. Any ideas? Thanks in advance.

Figured it out. Need to use OnParametersSetAsync() in the component.

[CascadingParameter] protected Task<AuthenticationState> AuthenticationStateTask { get; set; }

protected override async Task OnParametersSetAsync()
        {
            var user = (await AuthenticationStateTask).User;
            if (user.Identity.IsAuthenticated)
            {
                await SetUserInfo(user);                
            }
        }

Use OnAfterRenderAsync

 protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var authenticationState = await authenticationStateTask;
            if (authenticationState.User.Identity.IsAuthenticated)
            {
            
            }
        }
    }

on LoginDisplay component

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

    private string _authMessage;

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

        if (user.Identity.IsAuthenticated)
        {
            _authMessage = $"{user.Identity.Name} is authenticated.";
            wait SetUserInfo(user);
        }
       
    }
}

I think the cleanest solution is this:

Add a Blazor Component, eg "CallMe" (shortened Code)

@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IDataService DataService
...

@code{
    [CascadingParameter] protected Task<AuthenticationState> AuthState { get; set; } = null!;

    protected override async Task OnInitializedAsync()
    {
        var user = (await AuthState).User;
        if (user.Identity.IsAuthenticated)
        {
          var email = user.FindFirst("preferred_username").Value;
          var user = await DataService.GetUserAsync(email);
        }
    }
}

and 'call' it in LoginDisplay.razor -> Authorized Context.

<AuthorizeView>
    <Authorized>
        @context.User.Identity?.Name!
        <CallMe></CallMe>
        <button class="nav-link btn btn-link" @onclick="BeginLogout">Log out</button>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/login">Log in</a>
    </NotAuthorized>
</AuthorizeView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM