【发布时间】:2019-09-09 08:45:35
【问题描述】:
在我们的 Blazor 应用程序中,我们将覆盖 AuthenticationStateProvider 的默认实现以允许使用 out Jwt。
由于升级到Preview 9,现在需要将AthenticationResponse 响应包装在Task 中。
我有以下代码;
public class JwtAuthenticationStateProvider : AuthenticationStateProvider
{
private bool _isUserLoggedIn = false;
private readonly HttpClient _httpClient;
private readonly IAuthService _authService;
private readonly ILogger<JwtAuthenticationStateProvider> _logger;
public JwtAuthenticationStateProvider(HttpClient httpClient, IAuthService authService, ILogger<JwtAuthenticationStateProvider> logger)
{
_httpClient = httpClient;
_authService = authService;
_logger = logger;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
if(!_isUserLoggedIn)
{
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity())));
}
else
{
var tokenResponse = await _authService.GetCurrentAuthTokenAsync();
if (tokenResponse.HasError)
{
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
return await Task.FromResult(new AuthenticationState(anonymousUser));
}
var claimsResponse = await _authService.GetCurrentUserClaimsAsync();
if(claimsResponse.HasError)
{
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
return await Task.FromResult(new AuthenticationState(anonymousUser));
}
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", tokenResponse.Result);
return await Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claimsResponse.Result, "apiAuth"))));
}
}
public async Task MarkUserAsAuthenticated()
{
if(!_isUserLoggedIn)
_ = KeepSessionAsync();
var claimsResponse = await _authService.GetCurrentUserClaimsAsync();
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claimsResponse.Result, "apiAuth"));
NotifyAuthenticationStateChanged(await Task.FromResult(new AuthenticationState(authenticatedUser)));
}
public void MarkUserAsLoggedOut()
{
_isUserLoggedIn = false;
_httpClient.DefaultRequestHeaders.Authorization = null;
var anonymousUser = new ClaimsPrincipal(new ClaimsIdentity());
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(anonymousUser)));
}
}
但是我在GetAuthenticationStateAsync() 上收到以下错误;
'JwtAuthenticationStateProvider.GetAuthenticationStateAsync()':返回类型必须是 'Task' 以匹配被覆盖的成员 'AuthenticationStateProvider.GetAuthenticationStateAsync()'
谁能解释一下这里发生了什么?
【问题讨论】:
-
也许您正在混合您引用的程序集,并且您使用的任务与基类中的任务不同,即。不同的程序集实现Task?
-
不是我不认为我在引用
System.Threading.Tasks.Task并且AuthenticationStateProvider类的元数据也是如此? -
如果您删除
await并只保留return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claimsResponse.Result, "apiAuth"))));会发生什么? -
@HenkHolterman 不,它不是直接从 AuthenticationStateProvider 扩展而来的
标签: c# blazor .net-core-3.0 blazor-client-side