我已经设置了创建示例的必要性。这是我的代码。
启动文件
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>
给出代码,索引页面仅显示“未登录”。我是否错过了一件太简单的事情以至于我忽略了它?我是新来的。
答案 0 :(得分:1)
您忘记在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>
答案 1 :(得分:0)
您可以使用默认模板。它有一个有效的例子。
答案 2 :(得分:0)
您应该致电
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)));
}