简体   繁体   中英

Blazor WebAssembly Authentication and code meaning

I am following one article about Blazor WebAssembly Authentication.

https://code-maze.com/blazor-webassembly-authentication-as.netcore-identity/

This is AuthenticationService.cs.

public async Task<AuthResponseDto> Login(UserForAuthenticationDto userForAuthentication)
{
    var content = JsonSerializer.Serialize(userForAuthentication);
    var bodyContent = new StringContent(content, Encoding.UTF8, "application/json");

    var authResult = await _client.PostAsync("accounts/login", bodyContent);
    var authContent = await authResult.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<AuthResponseDto>(authContent, _options);

    if (!authResult.IsSuccessStatusCode)
        return result;

    await _localStorage.SetItemAsync("authToken", result.Token);
    ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.Email);
    _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token);

    return new AuthResponseDto { IsAuthSuccessful = true };
}

public async Task Logout()
{
    await _localStorage.RemoveItemAsync("authToken");
    ((AuthStateProvider)_authStateProvider).NotifyUserLogout();
    _client.DefaultRequestHeaders.Authorization = null;
}

I lost my way in this part.

    ((AuthStateProvider)_authStateProvider).NotifyUserAuthentication(userForAuthentication.Email);

I can't get this code. Type casting? Type converting? This code calls a method, NotifyUserAuthentication. But what is the front part's meaning? Generally, I know ( ) in front of the variable is for casting. But I don't get this what is this for, and what is this code meaning?

And why double used the same class AuthenticationStateProvider.

AuthStateProvider is inherited from AuthenticationStateProvider. _authStateProvider is an instance of AuthenticationStateProvider.

Any help could be helpful for me.

Your AuthStateProvider DI service is registered as a AuthenticationStateProvider object, so in AuthenticationService that's what gets injected

private readonly AuthenticationStateProvider _authStateProvider; 

public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider, ILocalStorageService localStorage)

NotifyUserLogout is an AuthStateProvider method, it's not implemented in it's parent AuthenticationStateProvider so you need to cast the object instance (which is actually a AuthStateProvider instance) to AuthStateProvider to be able to call the method.

Put in a break point and see what you have.

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