Blazor Server如何使用Identity Server?
前面几篇都是基于Blazor WebAssembly 的,这次来尝试一下Blazor的Server模式。根据官方的介绍,Blazor Server的认证方式其实和MVC的认证方式是一样的,同时Identity Server 也有专门介绍MVC的集成:
https://identityserver4.readthedocs.io/en/latest/quickstarts/2_interactive_aspnetcore.html#creating-an-mvc-client
那么这里就以此为基础来开始我们的代码。
1. Blazor Server
首先当然是创建一个Blazor Server项目,使用默认模板就行,然后还要添加包:Microsoft.AspNetCore.Authentication.OpenIdConnect, 她将用来与Identity Server的交互。
1.1 修改Startup.cs
Startup文件,基本上就是根据Identity Server的官方指引来修改:
public void ConfigureServices(IServiceCollection services)
{
//...
//添加认证相关的服务
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
//Identity Server 的地址
options.Authority = "https://localhost:5001";
//Identity Server配置的Client 以及 Secret
options.ClientId = "blazorserver";
options.ClientSecret = "secret";
//认证模式
options.ResponseType = "code";
//保存token到本地
options.SaveTokens = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseRouting();
//添加认证与授权中间件
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute().RequireAuthorization();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
1.2 修改App.razor
其实跟WebAssembly是一样的,都用到了CascadingAuthenticationState和AuthorizeRouteView
<CascadingAuthenticationState>
<Router AppAssembly