Home > Software engineering >  Blazor WebAssembly Authentication and code meaning
Blazor WebAssembly Authentication and code meaning

Time:01-07

I am following one article about Blazor WebAssembly Authentication.

https://code-maze.com/blazor-webassembly-authentication-aspnetcore-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.

CodePudding user response:

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.

  • Related