pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

異步調用時 Azure KeyVault Active Directory AcquireTokenA

Azure KeyVault Active Directory AcquireTokenAsync timeout when called asynchronously(異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時)
本文介紹了異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我已按照 Microsoft

第二個令牌請求使用單線程:

  1. GetKeyAsync() 在 ThreadASP 上調用 GetAccessToken()(不在單獨的線程上.)
  2. GetKeyAsync() 返回一個Task.
  3. 我們調用 GetResult() 阻塞 ThreadASP,直到 GetKeyAsync() 完成.
  4. GetAccessToken() 必須等到 ThreadASP 空閑,ThreadASP 必須等到 GetKeyAsync() 完成,GetKeyAsync() 必須等到 GetAccessToken() 完成.哦哦.
  5. 死鎖.

為什么?誰知道?!?

GetKeyAsync() 中必須有一些依賴于訪問令牌緩存狀態的流控制.流控制決定是否在自己的線程上運行GetAccessToken(),以及在什么時候返回Task.

解決方案:一直異步

為避免死鎖,最佳做法是一直使用異步".當我們調用來自外部庫的異步方法時尤其如此,例如 GetKeyAsync().重要的是不要強制方法與 Wait()結果,或<代碼>GetResult().相反,請使用 asyncawait 因為 await 會暫停方法而不是阻塞整個線程.

異步控制器動作

公共類 HomeController : 控制器{公共異步任務<ActionResult>指數(){var provider = new EncryptionProvider();等待提供者.GetKeyBundle();var x = provider.MyKeyBundle;返回視圖();}}

異步公共方法

由于構造函數不能是異步的(因為異步方法必須返回一個Task),我們可以將異步的東西放到一個單獨的公共方法中.

公共類 EncryptionProvider{////認證屬性省略公共 KeyBundle MyKeyBundle;公共加密提供者(){}公共異步任務 GetKeyBundle(){var keyVaultClient = new KeyVaultClient(GetAccessToken);var keyBundleTask = 等待 keyVaultClient.GetKeyAsync(KeyVaultUrl, KeyVaultEncryptionKeyName);MyKeyBundle = keyBundleTask;}私有異步任務<字符串>獲取訪問令牌(字符串權限、字符串資源、字符串范圍){TokenCache.DefaultShared.Clear();//重現問題var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);var clientCredential = new ClientCredential(ClientIdWeb, ClientSecretWeb);var 結果 = 等待 authContext.AcquireTokenAsync(resource, clientCredential);var token = result.AccessToken;返回令牌;}}

謎團解開了.:) 這是最終參考我的理解.

控制臺應用

我最初的答案是這個控制臺應用程序.它作為最初的故障排除步驟.它沒有重現問題.

控制臺應用每五分鐘循環一次,反復請求新的訪問令牌.在每個循環中,它都會輸出當前時間、到期時間和檢索到的密鑰的名稱.

在我的機器上,控制臺應用程序運行了 1.5 小時,并在原始過期后成功檢索到密鑰.

使用系統;使用 System.Collections.Generic;使用 System.Threading.Tasks;使用 Microsoft.Azure.KeyVault;使用 Microsoft.IdentityModel.Clients.ActiveDirectory;命名空間 ConsoleApp{課堂節目{私有靜態異步任務 RunSample(){var keyVaultClient = new KeyVaultClient(GetAccessToken);//創建一個密鑰 :)var keyCreate = 等待 keyVaultClient.CreateKeyAsync(保險庫:_keyVaultUrl,密鑰名稱:_keyVaultEncryptionKeyName,密鑰類型:_keyType,關鍵屬性:新的關鍵屬性(){啟用 = 真,過期 = UnixEpoch.FromUnixTime(int.MaxValue),NotBefore = UnixEpoch.FromUnixTime(0),},技術標簽: 新字典<字符串、字符串>{{ "目的", "StackOverflow 演示" }});Console.WriteLine(string.Format(已創建 {0}",keyCreate.KeyIdentifier.Name));//取回密鑰var keyRetrieve = 等待 keyVaultClient.GetKeyAsync(_keyVaultUrl,_keyVaultEncryptionKeyName);Console.WriteLine(string.Format("檢索到 {0}",keyRetrieve.KeyIdentifier.Name));}私有靜態異步任務<字符串>獲取訪問令牌(字符串權限、字符串資源、字符串范圍){var clientCredential = 新的 ClientCredential(_keyVaultAuthClientId,_keyVaultAuthClientSecret);var context = new AuthenticationContext(權威,TokenCache.DefaultShared);var result = await context.AcquireTokenAsync(resource, clientCredential);_expiresOn = 結果.ExpiresOn.DateTime;Console.WriteLine(DateTime.UtcNow.ToShortTimeString());Console.WriteLine(_expiresOn.ToShortTimeString());返回結果.AccessToken;}私有靜態日期時間_expiresOn;私有靜態字符串_keyVaultAuthClientId = "xxxxx-xxx-xxxxx-xxx-xxxxx",_keyVaultAuthClientSecret = "xxxxx-xxx-xxxxx-xxx-xxxxx",_keyVaultEncryptionKeyName = "MYENCRYPTIONKEY",_keyVaultUrl = "https://xxxxx.vault.azure.net/",_keyType = "RSA";靜態無效主要(字符串 [] 參數){var keepGoing = true;同時(繼續){RunSample().GetAwaiter().GetResult();//休眠五分鐘System.Threading.Thread.Sleep(new TimeSpan(0, 5, 0));如果(日期時間.UtcNow > _expiresOn){Console.WriteLine("---過期---");Console.ReadLine();}}}}}

I have setup Azure Keyvault on my ASP.Net MVC web application by following the example in Microsoft's Hello Key Vault sample application.

Azure KeyVault (Active Directory) AuthenticationResult by default has a one hour expiry. So after one hour, you must get a new authentication token. KeyVault is working as expected for the first hour after getting my first AuthenticationResult token, but after the 1 hour expiry, it fails to get a new token.

Unfortunately it took a failure on my production environment for me to realize this, as I never tested past one hour in development.

Anyways, after over two days of trying to figure out what was wrong with my keyvault code, I came up with a solution that fixes all of my problems - remove the asynchronous code - but it feels very hacky. I want to find out why it was not working in the first place.

My code looks like this:

public AzureEncryptionProvider() //class constructor
{
   _keyVaultClient = new KeyVaultClient(GetAccessToken);
   _keyBundle = _keyVaultClient
     .GetKeyAsync(_keyVaultUrl, _keyVaultEncryptionKeyName)
     .GetAwaiter().GetResult();
}

private static readonly string _keyVaultAuthClientId = 
    ConfigurationManager.AppSettings["KeyVaultAuthClientId"];

private static readonly string _keyVaultAuthClientSecret =
    ConfigurationManager.AppSettings["KeyVaultAuthClientSecret"];

private static readonly string _keyVaultEncryptionKeyName =
    ConfigurationManager.AppSettings["KeyVaultEncryptionKeyName"];

private static readonly string _keyVaultUrl = 
    ConfigurationManager.AppSettings["KeyVaultUrl"];

private readonly KeyBundle _keyBundle;
private readonly KeyVaultClient _keyVaultClient;

private static async Task<string> GetAccessToken(
    string authority, string resource, string scope)
{
   var clientCredential = new ClientCredential(
       _keyVaultAuthClientId, 
       _keyVaultAuthClientSecret);
   var context = new AuthenticationContext(
       authority, 
       TokenCache.DefaultShared);
   var result = context.AcquireToken(resource, clientCredential);
   return result.AccessToken;
}

The GetAccessToken method signature has to be asynchronous to pass into the new KeyVaultClient constructor, so I left the signature as async, but I removed the await keyword.

With the await keyword in there (the way it should be, and is in the sample):

private static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
   var clientCredential = new ClientCredential(_keyVaultAuthClientId, _keyVaultAuthClientSecret);
   var context = new AuthenticationContext(authority, null);
   var result = await context.AcquireTokenAsync(resource, clientCredential);
   return result.AccessToken;
}

The program works fine the first time I run it. And for an hour, AcquireTokenAsync returns the same original authentication token which is great. But once the token expires, AcquiteTokenAsync should get a new token with a new expiry date. And it doesn't - the application just hangs. No error returned, nothing at all.

So calling AcquireToken instead of AcquireTokenAsync solves the problem, but I have no idea why. You'll also notice that I'm passing 'null' instead of 'TokenCache.DefaultShared' into the AuthenticationContext constructor in my sample code with async. This is to force the toke to expire immediately instead of after one hour. Otherwise, you have to wait an hour to reproduce the behavior.

I was able to reproduce this again in a brand new MVC project, so I don't think it has anything to do with my specific project. Any insight would be appreciated. But for now, I'm just not using async.

解決方案

Problem: deadlock

Your EncryptionProvider() is calling GetAwaiter().GetResult(). This blocks the thread, and on subsequent token requests, causes a deadlock. The following code is the same as yours is but separates things to facilitate explanation.

public AzureEncryptionProvider() // runs in ThreadASP
{
    var client = new KeyVaultClient(GetAccessToken);

    var task = client.GetKeyAsync(KeyVaultUrl, KeyVaultEncryptionKeyName);

    var awaiter = task.GetAwaiter();

    // blocks ThreadASP until GetKeyAsync() completes
    var keyBundle = awaiter.GetResult();
}

In both token requests, the execution starts in the same way:

  • AzureEncryptionProvider() runs in what we'll call ThreadASP.
  • AzureEncryptionProvider() calls GetKeyAsync().

Then things differ. The first token request is multi-threaded:

  1. GetKeyAsync() returns a Task.
  2. We call GetResult() blocking ThreadASP until GetKeyAsync() completes.
  3. GetKeyAsync() calls GetAccessToken() on another thread.
  4. GetAccessToken() and GetKeyAsync() complete, freeing ThreadASP.
  5. Our web page returns to the user. Good.

The second token request uses a single thread:

  1. GetKeyAsync() calls GetAccessToken() on ThreadASP (not on a separate thread.)
  2. GetKeyAsync() returns a Task.
  3. We call GetResult() blocking ThreadASP until GetKeyAsync() completes.
  4. GetAccessToken() must wait until ThreadASP is free, ThreadASP must wait until GetKeyAsync() completes, GetKeyAsync() must wait until GetAccessToken() completes. Uh oh.
  5. Deadlock.

Why? Who knows?!?

There must be some flow control within GetKeyAsync() that relies on the state of our access token cache. The flow control decides whether to run GetAccessToken() on its own thread and at what point to return the Task.

Solution: async all the way down

To avoid a deadlock, it is a best practice "to use async all the way down." This is especially true when we are calling an async method, such as GetKeyAsync(), that is from an external library. It is important not force the method to by synchronous with Wait(), Result, or GetResult(). Instead, use async and await because await pauses the method instead of blocking the whole thread.

Async controller action

public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
        var provider = new EncryptionProvider();
        await provider.GetKeyBundle();
        var x = provider.MyKeyBundle;
        return View();
    }
}

Async public method

Since a constructor cannot be async (because async methods must return a Task), we can put the async stuff into a separate public method.

public class EncryptionProvider
{
    //
    // authentication properties omitted

    public KeyBundle MyKeyBundle;

    public EncryptionProvider() { }

    public async Task GetKeyBundle()
    {
        var keyVaultClient = new KeyVaultClient(GetAccessToken);
        var keyBundleTask = await keyVaultClient
            .GetKeyAsync(KeyVaultUrl, KeyVaultEncryptionKeyName);
        MyKeyBundle = keyBundleTask;
    }

    private async Task<string> GetAccessToken(
        string authority, string resource, string scope)
    {
        TokenCache.DefaultShared.Clear(); // reproduce issue 
        var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var clientCredential = new ClientCredential(ClientIdWeb, ClientSecretWeb);
        var result = await authContext.AcquireTokenAsync(resource, clientCredential);
        var token = result.AccessToken;
        return token;
    }
}

Mystery solved. :) Here is a final reference that helped my understanding.

Console App

My original answer had this console app. It worked as an initial troubleshooting step. It did not reproduce the problem.

The console app loops every five minutes, repeatedly asking for a new access token. At each loop, it outputs the current time, the expiry time, and the name of the retrieved key.

On my machine, the console app ran for 1.5 hours and successfully retrieved a key after expiration of the original.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace ConsoleApp
{
    class Program
    {
        private static async Task RunSample()
        {
            var keyVaultClient = new KeyVaultClient(GetAccessToken);

            // create a key :)
            var keyCreate = await keyVaultClient.CreateKeyAsync(
                vault: _keyVaultUrl,
                keyName: _keyVaultEncryptionKeyName,
                keyType: _keyType,
                keyAttributes: new KeyAttributes()
                {
                    Enabled = true,
                    Expires = UnixEpoch.FromUnixTime(int.MaxValue),
                    NotBefore = UnixEpoch.FromUnixTime(0),
                },
                tags: new Dictionary<string, string> {
                    { "purpose", "StackOverflow Demo" }
                });

            Console.WriteLine(string.Format(
                "Created {0} ",
                keyCreate.KeyIdentifier.Name));

            // retrieve the key
            var keyRetrieve = await keyVaultClient.GetKeyAsync(
                _keyVaultUrl,
                _keyVaultEncryptionKeyName);

            Console.WriteLine(string.Format(
                "Retrieved {0} ",
                keyRetrieve.KeyIdentifier.Name));
        }

        private static async Task<string> GetAccessToken(
            string authority, string resource, string scope)
        {
            var clientCredential = new ClientCredential(
                _keyVaultAuthClientId,
                _keyVaultAuthClientSecret);

            var context = new AuthenticationContext(
                authority,
                TokenCache.DefaultShared);

            var result = await context.AcquireTokenAsync(resource, clientCredential);

            _expiresOn = result.ExpiresOn.DateTime;

            Console.WriteLine(DateTime.UtcNow.ToShortTimeString());
            Console.WriteLine(_expiresOn.ToShortTimeString());

            return result.AccessToken;
        }

        private static DateTime _expiresOn;
        private static string
            _keyVaultAuthClientId = "xxxxx-xxx-xxxxx-xxx-xxxxx",
            _keyVaultAuthClientSecret = "xxxxx-xxx-xxxxx-xxx-xxxxx",
            _keyVaultEncryptionKeyName = "MYENCRYPTIONKEY",
            _keyVaultUrl = "https://xxxxx.vault.azure.net/",
            _keyType = "RSA";

        static void Main(string[] args)
        {
            var keepGoing = true;
            while (keepGoing)
            {
                RunSample().GetAwaiter().GetResult();
                // sleep for five minutes
                System.Threading.Thread.Sleep(new TimeSpan(0, 5, 0)); 
                if (DateTime.UtcNow > _expiresOn)
                {
                    Console.WriteLine("---Expired---");
                    Console.ReadLine();
                }
            }
        }
    }
}

這篇關于異步調用時 Azure KeyVault Active Directory AcquireTokenAsync 超時的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests(ASP.NET Core 使用 Azure Active Directory 進行身份驗證并跨請求保留自定義聲明)
ASP.NET Core 2.0 Web API Azure Ad v2 Token Authorization not working(ASP.NET Core 2.0 Web API Azure Ad v2 令牌授權不起作用)
ASP Core Azure Active Directory Login use roles(ASP Core Azure Active Directory 登錄使用角色)
How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API(如何獲取守護進程或服務器到 C# ASP.NET Web API 的 Azure AD OAuth2 訪問令牌和刷新令牌) - IT屋-程序員軟件開發技
.Net Core 2.0 - Get AAD access token to use with Microsoft Graph(.Net Core 2.0 - 獲取 AAD 訪問令牌以與 Microsoft Graph 一起使用)
Getting access token using email address and app password from oauth2/token(使用電子郵件地址和應用程序密碼從 oauth2/token 獲取訪問令牌)
主站蜘蛛池模板: 广东机电安装工程_中央空调工程_东莞装饰装修-广东粤标建设有限公司 | 电镀标牌_电铸标牌_金属标贴_不锈钢标牌厂家_深圳市宝利丰精密科技有限公司 | 江苏密集柜_电动_手动_移动_盛隆柜业江苏档案密集柜厂家 | 悬浮拼装地板_幼儿园_篮球场_悬浮拼接地板-山东悬浮拼装地板厂家 | 油罐车_加油机_加油卷盘_加油机卷盘_罐车人孔盖_各类球阀_海底阀等车用配件厂家-湖北华特专用设备有限公司 | 杭州用友|用友软件|用友财务软件|用友ERP系统--杭州协友软件官网 | 挨踢网-大家的导航!| LED灯杆屏_LED广告机_户外LED广告机_智慧灯杆_智慧路灯-太龙智显科技(深圳)有限公司 | 冷却塔降噪隔音_冷却塔噪声治理_冷却塔噪音处理厂家-广东康明冷却塔降噪厂家 | 干式磁选机_湿式磁选机_粉体除铁器-潍坊国铭矿山设备有限公司 | 水冷式工业冷水机组_风冷式工业冷水机_水冷螺杆冷冻机组-深圳市普威机械设备有限公司 | 净化板-洁净板-净化板价格-净化板生产厂家-山东鸿星新材料科技股份有限公司 | 胀套-锁紧盘-风电锁紧盘-蛇形联轴器「厂家」-瑞安市宝德隆机械配件有限公司 | 儿童乐园|游乐场|淘气堡招商加盟|室内儿童游乐园配套设备|生产厂家|开心哈乐儿童乐园 | 智能楼宇-楼宇自控系统-楼宇智能化-楼宇自动化-三水智能化 | 道达尔润滑油-食品级润滑油-道达尔导热油-合成导热油,深圳道达尔代理商合-深圳浩方正大官网 | 塑钢课桌椅、学生课桌椅、课桌椅厂家-学仕教育设备首页 | 软启动器-上海能曼电气有限公司| PCB接线端子_栅板式端子_线路板连接器_端子排生产厂家-置恒电气 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 假肢-假肢价格-假肢厂家-河南假肢-郑州市力康假肢矫形器有限公司 | 茶楼装修设计_茶馆室内设计效果图_云臻轩茶楼装饰公司 | 石家庄网站建设|石家庄网站制作|石家庄小程序开发|石家庄微信开发|网站建设公司|网站制作公司|微信小程序开发|手机APP开发|软件开发 | 标策网-专注公司商业知识服务、助力企业发展 | 石家庄网站建设|石家庄网站制作|石家庄小程序开发|石家庄微信开发|网站建设公司|网站制作公司|微信小程序开发|手机APP开发|软件开发 | 飞扬动力官网-广告公司管理软件,广告公司管理系统,喷绘写真条幅制作管理软件,广告公司ERP系统 | 范秘书_懂你的范文小秘书| COD分析仪|氨氮分析仪|总磷分析仪|总氮分析仪-圣湖Greatlake | 粉丝机械,粉丝烘干机,粉丝生产线-招远市远东粉丝机械有限公司 | 内六角扳手「厂家」-温州市威豪五金工具有限公司 | 欧盟ce检测认证_reach检测报告_第三方检测中心-深圳市威腾检验技术有限公司 | 济南办公室装修-厂房装修-商铺装修-工装公司-山东鲁工装饰设计 | 高通量组织研磨仪-多样品组织研磨仪-全自动组织研磨仪-研磨者科技(广州)有限公司 | 网架支座@球铰支座@钢结构支座@成品支座厂家@万向滑动支座_桥兴工程橡胶有限公司 | 高压包-点火器-高压发生器-点火变压器-江苏天网 | 骨龄仪_骨龄检测仪_儿童骨龄测试仪_品牌生产厂家【品源医疗】 | 济南办公室装修-厂房装修-商铺装修-工装公司-山东鲁工装饰设计 | 生产加气砖设备厂家很多,杜甫机械加气砖设备价格公道 | 医用空气消毒机-医用管路消毒机-工作服消毒柜-成都三康王 | 佛山市钱丰金属不锈钢蜂窝板定制厂家|不锈钢装饰线条|不锈钢屏风| 电梯装饰板|不锈钢蜂窝板不锈钢工艺板材厂家佛山市钱丰金属制品有限公司 | 无菌检查集菌仪,微生物限度仪器-苏州长留仪器百科 | 大学食堂装修设计_公司餐厅效果图_工厂食堂改造_迈普装饰 | 算命免费_生辰八字_免费在线算命 - 卜算子算命网 |