您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

如何缓存身份验证令牌How to cache the authentication token

本文演示如何缓存身份验证令牌以提高应用程序的性能。This article demonstrates how to cache the authentication token in order to improve performance of your application.

使用 ASP.NETUsing ASP.NET

导入 Microsoft.IdentityModel.Clients.ActiveDirectory NuGet 包,该包用于获取令牌。Import the Microsoft.IdentityModel.Clients.ActiveDirectory NuGet package, which is used to acquire a token. 接下来,使用以下代码获取 AuthenticationResult,并使用在创建沉浸式阅读器资源时获取的身份验证值。Next, use the following code to acquire an AuthenticationResult, using the authentication values you got when you created the Immersive Reader resource.

private async Task<AuthenticationResult> GetTokenAsync()
{
    AuthenticationContext authContext = new AuthenticationContext($"https://login.windows.net/{TENANT_ID}");
    ClientCredential clientCredential = new ClientCredential(CLIENT_ID, CLIENT_SECRET);
    AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://cognitiveservices.azure.com/", clientCredential);
    return authResult;
}

AuthenticationResult 对象具有 AccessToken 属性,该属性是在使用 SDK 启动沉浸式阅读器时将使用的实际令牌。The AuthenticationResult object has an AccessToken property which is the actual token you will use when launching the Immersive Reader using the SDK. 它还具有 ExpiresOn 属性,该属性表示令牌的过期时间。It also has an ExpiresOn property which denotes when the token will expire. 在启动沉浸式阅读器之前,可以检查令牌是否已过期,并仅在过期后获取新令牌。Before launching the Immersive Reader, you can check whether the token has expired, and acquire a new token only if it has expired.

使用 Node.JSUsing Node.JS

request npm 包添加到项目。Add the request npm package to your project. 使用以下代码获取令牌,并使用在创建沉浸式阅读器资源时获取的身份验证值。Use the following code to acquire a token, using the authentication values you got when you created the Immersive Reader resource.

router.get('/token', function(req, res) {
    request.post(
        {
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            url: `https://login.windows.net/${TENANT_ID}/oauth2/token`,
            form: {
                grant_type: 'client_credentials',
                client_id: CLIENT_ID,
                client_secret: CLIENT_SECRET,
                resource: 'https://cognitiveservices.azure.com/'
            }
        },
        function(err, resp, json) {
            const result = JSON.parse(json);
            return res.send({
                access_token: result.access_token,
                expires_on: result.expires_on
            });
        }
    );
});

expires_on 属性是令牌过期的日期和时间,表示为自 1970 年 1 月 1 日 UTC 起的秒数。The expires_on property is the date and time at which the token expires, expressed as the number of seconds since January 1, 1970 UTC. 使用此值来确定令牌是否已过期,然后再尝试获取新令牌。Use this value to determine whether your token has expired before attempting to acquire a new one.

async function getToken() {
    if (Date.now() / 1000 > CREDENTIALS.expires_on) {
        CREDENTIALS = await refreshCredentials();
    }
    return CREDENTIALS.access_token;
}

后续步骤Next steps