[英].NET MAUI Blazor with a shared UI library and authentication
我正在尝试编写一个 .NET MAUI Blazor 应用程序,它与传统的 Blazor 应用程序共享 UI,如https://github.com/danroth27/BlazorWeather的 BlazorWeather 示例所示。
我对这个公式的看法是,我希望能够在我的应用程序中使用身份验证并尽可能多地共享代码。 理想情况下,我希望将所有应用程序逻辑放在共享 UI 中(当然,API 也将只适用于 Web 和 MAUI)。
我尝试创建一个非常基本的示例解决方案,以便您了解我的问题。 公共存储库应可在https://github.com/Dukenware/OneToRuleThemAll访问
我遵循的步骤:
GetAuthenticationStateAsync was called before SetAuthenticationState.
at Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider.GetAuthenticationStateAsync()
at Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState.OnInitialized()
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
如果有人能指出我可以用来构建我的应用程序的工作模板,我真的很感激。 欢迎任何反馈。
我也遇到了这个问题。
这是我发现的。 当我的 AuthenticationState 没有返回正确的结果时,我收到了该错误。 这是实现默认 AuthenticationStateProvider 的 CustomAuthenticationStateProvider 的实现:
public class CustomAuthenticationStateProvider :AuthenticationStateProvider
{
public async Task Login(string token)
{
await SecureStorage.SetAsync("accounttoken", token);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async Task Logout()
{
SecureStorage.Remove("accounttoken");
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public override async Task<AuthenticationState>GetAuthenticationStateAsync()
{
try
{
var userInfo = await SecureStorage.GetAsync("accounttoken");
if (userInfo != null)
{
var claims = new[] { new Claim(ClaimTypes.Name, "User") };
var identity = new ClaimsIdentity(claims, "Server authentication");
return new AuthenticationState(new ClaimsPrincipal(identity));
}
}
catch (HttpRequestException ex)
{
//This should be implemented better
Console.WriteLine("Request failed:" + ex.ToString());
}
return new AuthenticationState(new ClaimsPrincipal());
}
}
然后在我的 MauiProgram 我添加了:
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();
我返回 null 而不是
new AuthenticationState(new ClaimsPrincipal());
这导致了同样的错误:
GetAuthenticationStateAsync was called before SetAuthenticationState.
at Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider.GetAuthenticationStateAsync()
at Microsoft.AspNetCore.Components.Authorization.CascadingAuthenticationState.OnInitialized()
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.