【问题标题】:Blazor WebAssembly Authentication and code meaningBlazor WebAssembly 认证及代码含义
【发布时间】:2023-01-07 19:33:53
【问题描述】:

我正在关注一篇关于 Blazor WebAssembly 身份验证的文章。

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

这是 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;
}

我在这部分迷路了。

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

我无法获取此代码。类型铸造?类型转换? 此代码调用方法 NotifyUserAuthentication。但是前面的部分是什么意思呢? 通常,我知道变量前面的 ( ) 是用于转换的。 但是我不明白这是为了什么,这段代码是什么意思?

以及为什么double使用同一个类AuthenticationStateProvider。

AuthStateProvider 继承自 AuthenticationStateProvider。 _authStateProvider 是 AuthenticationStateProvider 的一个实例。

任何帮助都可能对我有帮助。

【问题讨论】:

    标签: authentication blazor webassembly


    【解决方案1】:

    您的 AuthStateProvider DI 服务被注册为 AuthenticationStateProvider 对象,所以在 AuthenticationService 中就是被注入的

    private readonly AuthenticationStateProvider _authStateProvider; 
    
    public AuthenticationService(HttpClient client, AuthenticationStateProvider authStateProvider, ILocalStorageService localStorage)
    

    NotifyUserLogout 是一个AuthStateProvider 方法,它没有在AuthenticationStateProvider 中实现,因此您需要将对象实例(实际上是一个 AuthStateProvider 实例)转换为 AuthStateProvider 才能调用该方法。

    放置一个断点,看看你有什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-02
      • 1970-01-01
      • 2020-09-16
      • 2020-10-26
      • 2020-08-19
      • 2020-06-26
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多