.NET 5 Blazor ServerSide 和 WebAssembly(混合)与 WebAPI 身份验证?

时间:2021-03-05 18:27:45

标签: c# authentication blazor-server-side blazor-webassembly

有没有办法以混合方式将默认身份验证(.NET 5 / Identity-Server)与 Blazor ServerSide Blazor WebAssembly 结合使用? 我想要一个 Blazor 项目,它可以在 ClientSide (WebAssembly) 和 ServerSide 之间切换,以保持 Client 相同,我想在 ClientSide ServerSide 上使用 WebAPI。我从 ServerSide 开始(更好的调试和更好的表性能 *),稍后可能会切换到 ClientSide(如果性能会更好)。

*请不要开始讨论什么更好,或者如果您使用 WebAssembly 可能有良好的性能,那么您就没有很多嵌套组件,例如基于组件的表。

我确实测试了很多组合,但无法使其正常工作,但让我们从基本开始:

  • 创建 Blazor WebAssembly 项目(ASP.Net Core 托管)
  • 使用 .NET 5 进行身份验证(帐户)
  • 编辑服务器 startup.cs(如下所示)
  • 编辑客户端程序.cs(如下所示)
  • 将“_Host.cshtml”添加到“\Server\Pages”(如下所示)

Startup.cs(服务器)

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddDatabaseDeveloperPageExceptionFilter();
    services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true).AddEntityFrameworkStores<ApplicationDbContext>();
    services.AddIdentityServer().AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    services.AddAuthentication().AddIdentityServerJwt();
    
    // SERVER SIDE SUPPORT
    services.AddServerSideBlazor();
    services.AddApiAuthorization();
    if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
    {
        services.AddScoped(s =>
        {
            var uriHelper = s.GetRequiredService<NavigationManager>();
            return new HttpClient
            {
                BaseAddress = new System.Uri(uriHelper.BaseUri)
            };
        });
    }
    // --

    services.AddControllersWithViews();
    services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseMigrationsEndPoint();
        app.UseWebAssemblyDebugging();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseBlazorFrameworkFiles();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseIdentityServer();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
        
        // SERVER-SIDE SUPPORT
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host"); //endpoints.MapFallbackToFile("index.html");
        // --
    });
}

Program.cs(客户端)

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    //builder.RootComponents.Add<App>("#app");

    builder.Services.AddHttpClient("BlazorSwitchWithSec2.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
        .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

    // Supply HttpClient instances that include access tokens when making requests to the server project
    builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorSwitchWithSec2.ServerAPI"));

    builder.Services.AddApiAuthorization();

    await builder.Build().RunAsync();
}

_Host.cshtml(服务器)

@page "/"
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        @if (Request.QueryString.Value.ToLower().Contains("mode=client"))
        {
            <title>WebApp (CE)</title>
        }
        else
        {
            <title>WebApp (SE)</title>
        }
        <base href="~/" />
        <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
        <link href="css/app.css" rel="stylesheet" />
    </head>

    <body>
        @if (Request.QueryString.Value.ToLower().Contains("mode=client"))
        {
            <component type="typeof(BlazorSwitchWithSec2.Client.App)" render-mode="WebAssemblyPrerendered" />
            <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
            <script src="_framework/blazor.webassembly.js"></script>
            <script>navigator.serviceWorker.register('service-worker.js');</script>
        }
        else
        {
            <component type="typeof(BlazorSwitchWithSec2.Client.App)" render-mode="Server" />
            <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
            <script src="_framework/blazor.server.js"></script>
        }
    </body>
</html>

如果我尝试通过 WebAssembly 或服务器注册或登录,我会收到此错误: Unable to cast object of type 'Microsoft.AspNetCore.Components.Server.ServerAuthenticationStateProvider' to type 'Microsoft.AspNetCore.Components.WebAssembly.Authentication.IRemoteAuthenticationService`1[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState]'

也许这也有帮助:我尝试了一些不同的方法,例如使用来自客户端的服务,一种组合似乎可以与没有 [Authorize] 属性的控制器一起使用,但是使用它,我得到了类似 Unable to parse ... 的错误 - 结果是一个登录网址(这就是解析不起作用的原因)。我无法发布代码,因为我测试了太多并且项目不再工作了。

没有任何身份验证,一切正常,我可以向 WebAPI 发送令牌以创建我自己的登录系统。但我想试试默认的。

2 个答案:

答案 0 :(得分:1)

这些来自 Carl Franklin 的 Blazor Train 视频可能对您有所帮助。

Blazor 同步性;同时开发服务器和 WASM 应用

https://www.youtube.com/watch?v=SkYQDPXw__c

Blazor Synchronicity 5.0

https://www.youtube.com/watch?v=fHzIWOfmqzg

答案 1 :(得分:1)

我不喜欢 BlazorServer 引用 BlazorWasm 的方法。我更喜欢让 BlazorServer 和 BlazorWasm 项目都引用包含应用程序的 dll(rdl),这使得两者都使用共享代码库更加清楚,并避免 BlazorServer 从 BlazorWasm 引入不必要的依赖项。 你可以检查这个链接 https://github.com/mostafaefcih/BlazorDaulMode 或查看 plaursight 上的 blazor 入门课程