【问题标题】:Get Azure AD Access token from .Net Standard 2.0 unit test从 .Net Standard 2.0 单元测试获取 Azure AD 访问令牌
【发布时间】:2019-01-27 21:28:19
【问题描述】:

我有一个 .Net Core 2.0 asp.net mvc Web 应用程序。同样,我有一个 .Net Standard 2.0 单元测试项目。对于编写的单元测试,我必须调用受 Azure AD 保护的 Web API。谁能告诉我如何从 .net 标准 2.0 中的单元测试项目中获取 azure 广告访问令牌。

在 .Net 框架中是可能的,因为它在“Microsoft.IdentityModel.Clients.ActiveDirectory”dll 中提供了“UserPasswordCredential”类。但是这个类在 .Net Standard 2.0 (https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482) 中被删除了

【问题讨论】:

    标签: unit-testing azure-active-directory .net-standard-2.0


    【解决方案1】:

    我在集成测试中使用过类似的东西:

    string tokenUrl = _authority + "oauth2/token";
    var req = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
    {
        Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "password",
            ["client_id"] = settings.ClientId,
            ["client_secret"] = settings.ClientSecret,
            ["resource"] = _resourceUri,
            ["username"] = settings.UserName,
            ["password"] = settings.Password
        })
    };
    
    HttpResponseMessage res = await _client.SendAsync(req);
    
    string json = await res.Content.ReadAsStringAsync();
    AadTokenResponse tokenResponse = JsonConvert.DeserializeObject<AadTokenResponse>(json);
    

    有一些类级别的字段,例如 AAD 权限、API 资源 URI 和 HttpClient。

    因此,它的作用是使用资源所有者密码凭据授予流程获取访问令牌。 这是使用此流程实际上有意义的少数情况之一。 我们在没有登录窗口的情况下在用户上下文中获取访问令牌。 当有更好的东西可用时,不应使用此流程,并且在这种情况下还要求用户没有联合,没有 MFA 等。

    您可能希望缓存令牌,这样您就不会从测试中毫无意义地敲击令牌端点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多