.NetCore blazor身份验证不起作用



我已经设置了创建一个示例的必要条件。这是我的密码。

启动文件

public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
services.AddSingleton<DoggoDataServices>();
services.AddSingleton<AddDoggoServices>();
services.AddSingleton<EventServices>();
services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();

App.razor

<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>

customAuth

public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "john.smith@gmail.com"),
},   "apiauth_type");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));

}
}
}

索引

<AuthorizeView>
<Authorized>
<p>Welcome, @context.User.Identity.Name</p>
</Authorized>
<NotAuthorized>
<p>Not Logged In</p>
</NotAuthorized>
</AuthorizeView>

给定代码,索引页仅显示";未登录";。我是不是错过了一些简单的东西,以至于忽略了它?我是blazor的新手。

您忘记在app.razor 中添加CascadingAuthenticationState

<CascadingAuthenticationState>
<UserSession>
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</UserSession>
</CascadingAuthenticationState>

您可以使用默认模板。它有一个行之有效的例子。

您应该调用

NotifyAuthenticationStateChanged

使用自定义提供程序时,应在用户经过身份验证时通知它。示例:您可以将此方法添加到您的自定义提供商:

public void MarkUserAsAuthenticated(Users u)
{
// add your claims here. This is just an example.
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, u.UserName)
});
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
}

请注意,当用户注销时,您应该创建并调用类似的方法:

public void LogoutUser()
{
// reset identities and other related info (localstorage data if you have, etc).
var identity = new ClaimsIdentity();
var user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(user)));
}

相关内容

  • 没有找到相关文章

最新更新