Blazor 服务器,API 使用 OpenIdDict 并使用自省 - 如何处理访问令牌?

Blazor Server, API with OpenIdDict and using introspection - What to do with the access token?

我有一个 API 也托管了一个 OpenIdDict 令牌端点。 API 没有任何带有登录表单的网页,而是 return 作为接收表单 post.

的响应中的访问令牌

我以前有一个旧的 AngularJS 前端,它与 API 对话以获取令牌并将其存储在客户端上。 Angular 负责将令牌添加到对服务器的每个请求。

我现在正计划使用 Blazor Server 重建前端。我希望新的 Blazor 服务器 client/frontend 对 APIs 令牌端点使用内省。

我的计划是在 post 上构建一个自定义登录页面,在服务器端与 API 对话并获取访问令牌、刷新令牌等。但我没有知道之后将访问令牌放在哪里,以便 Blazor 在我使用 Authorize 属性时通过自省使用它。我可以只 return 令牌并可能写一些 javascript 将其保存在某处并将其添加到任何后续的 http 请求中,但这不像 Blazor Server 解决方案?

我的最新发现是令牌可以存储在服务器上的“会话中”,并在客户端创建“会话标识符”cookie?可能完全离开这里...

当我在 Blazor Server 中使用身份支持时,在成功登录后总是会创建一个名为“.AspNetCore.Identity.Application”的 cookie。

我一直在考虑的另一个不太理想的解决方案或解决方法是将 API 的 OpenIdDict 设置代码复制到 Blazor Server 项目并将它们指向同一数据库。

如有任何帮助,我们将不胜感激!

My plan was to build a custom Login page that on post would, server-side, talk to the API and get an access token, refresh token, etc. But I have no idea where to put the access token afterwards so that it's used by Blazor through introspection whenever I use the Authorize attribute. I could just return the tokens and maybe write some javascript that saves it somewhere and adds it to any subsequent http requests, but that does not feel like a Blazor Server solution?

您可以将访问令牌存储在本地存储中,并在需要时取回它的值。是的,它是 Blazor Server 解决方案。这就是你应该做的。

When I played around with the Identity support in Blazor Server a cookie with the name ".AspNetCore.Identity.Application" was always created after a successful login.

这是事实。这是一个声明还是你在这里问一个问题? 无论如何,我猜这个 cookie 会在其生命周期结束时自动删除。但在你的情况下,你必须手动完成;您必须编写代码来检查访问令牌是否已过期。如果不这样做,当您尝试访问 Wep Api 端点时,您的应用程序将出现问题。如果您不管理存储的访问令牌,Blazor 中的授权组件和对象也会错误地执行,例如,LoginDisplay 组件中嵌入的 AuthorizeView 将显示经过身份验证的用户的名称(因为您从中提取的声明访问令牌构成 AuthenticationSateProvider 从中创建 AuthenticationState 对象的数据),但不检查访问令牌的有效性。但 使用当前访问令牌访问您的网站 api 将导致异常,因为访问令牌无效。

我在上面描述了一些应该用数百页的文字来解释的东西。希望你不要太困惑。

希望这对您有所帮助...