如何使用 Identity Server 授权 Blazor WebAssembly SPA 应用程序

Vu *_*inh 2 authentication identityserver4 blazor blazor-client-side

我正在编写一个演示 Blazor WebAssembly SPA 技术演示应用程序,但我在身份验证方面遇到了一些问题。我将使用 Identity Server 进行授权,但我找不到任何支持它的库。我发现的所有教程都指导使用 Blazor Server 或添加托管的 ASP.net Core,但这对我的演示应用程序来说没有意义。

如果有人可以提供帮助,我很高兴。

谢谢

agu*_*ars 9

2020 年 3 月 12 日

若要使用现有 OAuth 身份提供程序将 OIDC 添加到现有 Blazor WASM 应用程序,请阅读使用身份验证库保护 ASP.NET Core Blazor WebAssembly 独立应用程序
新的Microsoft.AspNetCore.Components.WebAssembly.Authentication支持自动静默更新。

如果您更喜欢使用配置文件而不是硬编码值,您可以像这样设置应用程序

访问theidserver.herokuapp.com/以获得完整的功能示例。

  • 将您的应用升级到 3.2.0 预览版 2
    阅读升级现有项目段落

  • 添加包 Microsoft.AspNetCore.Components.WebAssembly.Authentication

dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Authentication::3.2.0-preview2.20160.5
Run Code Online (Sandbox Code Playgroud)
  • 将 AuthenticationService.js 添加到 index.html
dotnet add package Microsoft.AspNetCore.Components.WebAssembly.Authentication::3.2.0-preview2.20160.5
Run Code Online (Sandbox Code Playgroud)
  • 使用此结构在应用程序的 wwwroot 文件夹中添加一个 oidc.json 文件
{
  "authority": "https://myidp.com", // Uri to your IDP server
  "client_id": "myclientid", // Your client id
  "redirect_uri": "https://localhost:44333/authentication/login-callback", // Uri to the application login callback
  "post_logout_redirect_uri": "https://localhost:44333/authentication/logout-callback", // Uri to the application logout callback
  "response_type": "code", // OAuth flow response type. For `authorization_code` flow the response type is 'code'. For `implicit` flow, the response type is 'id_token token'
  "scope": "BlazorIdentityServer.ServerAPI openid profile" // list of scope your application wants
}
Run Code Online (Sandbox Code Playgroud)
  • 配置 Api 授权以从您的 oidc.json 文件中读取配置将
    您的Program.cs更新为:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
    <app>Loading...</app>
...
    <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script>
    <script src="_framework/blazor.webassembly.js"></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

2020 年 3 月 11 日

3.2.0-preview2提供了一种将 Blazor Wasm 与 IdentityServer
Read 结合使用的方法

2020 年 3 月 9 日

目前,您可以使用一些 blazor OIDC lib,但没有一个经过认证并实现所有功能。

如果你很好奇,我自己写来支持令牌静默更新,但它还没有完成,我被这个问题困住了:[wasm] WasmHttpMessageHandler,为每条消息提供获取选项
该问题已在此尚未合并的 PR 中得到解决。所以必须等待或实施我自己的WasmHttpMessageHandler.

第二种方法是使用JS interop包装oidc.js