首页 > 解决方案 > AcquireTokenAsync 不返回新令牌

问题描述

我的 WebAPI 应用程序在启动时从服务获取令牌。然后,此令牌将在共享 HTTP 客户端中使用,以防止端口耗尽。

当此令牌即将到期时,我想获得一个新令牌并将其保存在我的服务中以供重复使用。

在我的实现中,检索了一个令牌 - 但是它与原始令牌具有相同的到期时间:

    // Retrieve the token and assign to AuthenticationResult
    private async Task GetAPIToken()
    {
        AuthenticationContext authContext = new AuthenticationContext(Authority);
        var clientCredential = new ClientCredential(clientId, clientSecret);

        // Same token after multiple calls
        AuthenticationResult = await authContext.AcquireTokenAsync(resourceId, clientCredential).ConfigureAwait(false);
    }

如何保存最新的身份验证令牌?

标签: c#authenticationasp.net-web-apidotnet-httpclientbearer-token

解决方案


这里的问题是AuthenticationContext authContext = new AuthenticationContext(Authority);它将缓存一个令牌并在它尚未过期时检索它。

自己禁用缓存和管理令牌生命周期是一种解决方案:

AuthenticationContext authContext = new AuthenticationContext(Authority, null);


推荐阅读