Azure AD B2C 以编程方式获取令牌以进行单元测试
Azure AD B2C get token programatically for unit testing
我的场景很简单,我有一个带有 B2C 身份验证的简单 Azure 函数,我正在编写单元测试,但我发现了一个问题,我无法以编程方式对 azure 函数进行身份验证。
我可以通过浏览器访问,甚至可以获取令牌并将其放入单元测试中,它工作正常,但是当我尝试使用 ClientID、TenantID 等生成令牌时。我得到一个令牌,但 Azure 函数上出现 401 未经授权的响应。
有没有办法以编程方式生成有效的 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 Function 请求时,它 returns 401 未经授权。
提前致谢!
伊万
你的单元测试正在从 Azure AD v1.0 端点而不是 Azure AD B2C v2.0 端点获取令牌。
您的 Azure 函数需要令牌由 Azure AD B2C v2.0 终结点颁发。
短期内,您可以考虑通过使用 HttpClient
class.
重放浏览器请求从 Azure AD B2C v2.0 终结点获取令牌
在短期内,support for the resource owner password credential grant by Azure AD B2C 将使您的单元测试能够通过将用户凭据发布到端点来从 Azure AD B2C v2.0 端点获取令牌。
几个月前,Microsoft 发布了资源所有者密码凭据流策略,使用该策略您可以模拟登录,在查询中传递登录详细信息,如下所示:
- 在 B2C 中创建 ROPC 策略
- 注册一个应用程序
测试策略如下:
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
您可以找到更详细的信息here
我的场景很简单,我有一个带有 B2C 身份验证的简单 Azure 函数,我正在编写单元测试,但我发现了一个问题,我无法以编程方式对 azure 函数进行身份验证。
我可以通过浏览器访问,甚至可以获取令牌并将其放入单元测试中,它工作正常,但是当我尝试使用 ClientID、TenantID 等生成令牌时。我得到一个令牌,但 Azure 函数上出现 401 未经授权的响应。
有没有办法以编程方式生成有效的 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 Function 请求时,它 returns 401 未经授权。
提前致谢! 伊万
你的单元测试正在从 Azure AD v1.0 端点而不是 Azure AD B2C v2.0 端点获取令牌。
您的 Azure 函数需要令牌由 Azure AD B2C v2.0 终结点颁发。
短期内,您可以考虑通过使用 HttpClient
class.
在短期内,support for the resource owner password credential grant by Azure AD B2C 将使您的单元测试能够通过将用户凭据发布到端点来从 Azure AD B2C v2.0 端点获取令牌。
几个月前,Microsoft 发布了资源所有者密码凭据流策略,使用该策略您可以模拟登录,在查询中传递登录详细信息,如下所示:
- 在 B2C 中创建 ROPC 策略
- 注册一个应用程序
测试策略如下:
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
您可以找到更详细的信息here