Azure AD B2C 以编程方式获取令牌以进行单元测试 [英] Azure AD B2C get token programatically for unit testing

查看:16
本文介绍了Azure AD B2C 以编程方式获取令牌以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景很简单,我有一个带有 B2C 身份验证的简单 Azure 函数,我正在编写单元测试,但我发现了一个问题,我无法以编程方式对 azure 函数进行身份验证.

My scenario is simple I have a simple Azure Function with B2C authentication on it and I'm writing unit tests but I found an issue, I'm not able to authenticate to the azure functions programmatically.

我可以通过浏览器访问,甚至可以获取令牌并将其放入单元测试中,它工作正常,但是当我尝试使用 ClientID、TenantID 等生成令牌时,我得到一个令牌,但在 Azure 函数上出现 401 Unauthorized response.

I'm able to access through the browser and even I can grab the token and put it into the unit test and it works fine, but when I try to generate a token using the ClientID, TenantID, etc. I get a token, but 401 Unauthorized response on the Azure functions.

有没有办法以编程方式生成有效的 B2C 令牌(无需在浏览器中登录?

我目前使用的方法:

public static async  Task<AuthenticationResult> GetAccessToken(string resourceUri, string clientId, string clientSecret)
{
        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

        string aadInstance = "https://login.microsoftonline.com/";
        string tenant = "<mytenant>.onmicrosoft.com";
        string authority = string.Concat(aadInstance, tenant);
        AuthenticationContext authContext = new AuthenticationContext(authority);

        return await authContext.AcquireTokenAsync(resourceUri, clientCredential);
}

我得到一个令牌 (EY.......) 但无效,当我传递给 Azure 函数请求时,它返回 401 Unauthorized.

I'm getting a token (EY.......) but is not valid, when I passed to the Azure Function request, it returns 401 Unauthorized.

提前致谢!伊万

推荐答案

几个月前,Microsoft 发布了资源所有者密码凭据流策略,使用该策略您可以模拟登录,并在查询中传递登录详细信息:如下:

A couple of months ago, Microsoft released a policy for resource owner password credentials flow, with that policy you can simulate a login passing the login details in a query as follows:

  1. 在 B2C 中创建 ROPC 策略
  2. 注册申请
  3. 按如下方式测试策略:

  1. Create a ROPC policy in B2C
  2. Register an application
  3. Test the policy as follows:

  https://te.cpim.windows.net/{B2C TENANT}/{ROPC B2C POLICY}/oauth2/v2.0/token?username={USERNAME}&password={password}&grant_type=password&scope=openid+{CLIENT ID}+offline_access&client_id=[CLIENT ID]&response_type=token+id_token

您可以找到更详细的信息 这里

You can find more detailed info here

这篇关于Azure AD B2C 以编程方式获取令牌以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆