【问题标题】:How to automatically refresh token in ASP.NET Core 3.0 for API requests?如何在 ASP.NET Core 3.0 中为 API 请求自动刷新令牌?
【发布时间】:2020-05-22 10:32:48
【问题描述】:

我有一个ASP NET Core 3.0 应用程序,我正在使用Azure Active Directory 进行身份验证。参见下面的autentication配置

services.AddAuthentication(options =>
{
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
 })
.AddOpenIdConnect(options =>
{
    options.Authority = auth.Authority;
    options.ResponseType = OpenIdConnectResponseType.IdToken;
    options.SignedOutRedirectUri = auth.SignedOutRedirectUri;
    options.CallbackPath = auth.CallbackPath;
    options.ClientId = auth.ClientId;
})
.AddCookie(options =>
{
    options.AccessDeniedPath = "/Home/AccessDenied/";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
}); 

当我在 20 分钟不活动后更改页面时,cookie 会自动重新生成,但如果我调用 API Controller,则不会发生这种情况。当我进行AJAX 调用并且令牌已过期时,我该怎么做才能自动刷新令牌?我是否忘记在配置中添加一些东西?

【问题讨论】:

    标签: api asp.net-core cookies token openid-connect


    【解决方案1】:

    这个earlier post 可能会给你一些想法——来自之前遵循相同概念的 MS 技术堆栈。

    SlidingExpiration 选项可能会给您带来一些运气。传统上,由于 2 种不同类型的 Authorize 属性,这一直是一个问题区域。

    更宽的点

    一种更简洁的架构,可以通过最简单的代码和最佳的 UI 控制来实现最基于标准的解决方案,它是避免在同一个服务器端组件中混合 Web 和 API 代码。

    当然,这可能不在您当前项目的范围内,但您可能会考虑下一个项目:

    • 一个验证令牌的 ASP.Net Core Web API
    • 作为单页应用程序实现的无 cookie Web UI
    • Web 静态内容托管
    • UI 向 API 发送令牌
    • UI 以静默方式更新令牌,不涉及后端

    如果有兴趣,请查看我的 Azure AD 示例:

    【讨论】:

      猜你喜欢
      • 2015-07-03
      • 1970-01-01
      • 2020-09-21
      • 2018-03-30
      • 2016-01-05
      • 2020-11-04
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      相关资源
      最近更新 更多