Blazor与IdentityServer4的集成(六)

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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值