我的场景很简单我有一个简单的Azure功能,上面有B2C身份验证,而我正在编写单元测试,但是我发现了一个问题,我无法以编程方式对azure函数进行身份验证。
我能够通过浏览器访问,甚至我可以抓取令牌并将其放入单元测试中它工作正常,但是当我尝试使用ClientID,TenantID等生成令牌时获取令牌,但Azure功能上的401 Unauthorized响应。
有没有办法以编程方式生成有效的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请求时,它返回401 Unauthorized。
提前致谢! 伊万
答案 0 :(得分:2)
几个月前,Microsoft发布了资源所有者密码凭据流策略,使用该策略,您可以模拟登录,并在查询中传递登录详细信息,如下所示:
如下测试策略:
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
答案 1 :(得分:1)
您的单元测试是从Azure AD v1.0端点而不是Azure AD B2C v2.0端点获取令牌。
您的Azure功能期望该令牌由Azure AD B2C v2.0端点发布。
在短期内,您可以考虑使用HttpClient
类重播浏览器请求,从Azure AD B2C v2.0端点获取令牌。
在短期内,support for the resource owner password credential grant by Azure AD B2C将使您的单元测试能够通过将用户凭据张贴到端点来从Azure AD B2C v2.0端点获取令牌。