如何缓存令牌以及过期时应该静默更新它

问题描述 投票:0回答:0

我有一个使用 Azure AD 保护的 .Net Web API,我需要通过 C# 控制台应用程序生成令牌并调用 API。

我正在使用旧的 ADAL.NET 方法,因为它是一个遗留应用程序并支持 V1.0 AD 端点。

下面的代码有效,但每次调用都会生成一个带有新到期日期/时间的新令牌。

如何缓存直至过期并自动静默续订?

我尝试了下面的代码,但似乎不起作用。

private async Task<string> GetTokenAsync()
    {
        // Create the AuthenticationContext with token cache
        var authContext = new AuthenticationContext("https://login.windows.net/{tenant_id}", new TokenCache());
        var credential = new ClientCredential("ClientID", "ClientSecret");

        try
        {
            // Acquire an access token for the API
            var result = await authContext.AcquireTokenAsync("Resource", credential);
            return result.AccessToken;
        }
        catch (AdalSilentTokenAcquisitionException)
        {
            // If AcquireTokenAsync fails, try refreshing the token using AcquireTokenSilentAsync
            try
            {
                var result = await authContext.AcquireTokenSilentAsync("Resource", credential, UserIdentifier.AnyUser);
                return result.AccessToken;
            }
            catch (AdalException exception)
            {
            }
        }
        catch (AdalException exception)
        {
        }
        catch (Exception exception)
        {
        }

        return string.Empty;
    }
c# asp.net-core-webapi adal bearer-token
© www.soinside.com 2019 - 2024. All rights reserved.