Azure AD B2C以编程方式获取令牌以进行单元测试 [英] Azure AD B2C get token programatically for unit testing
问题描述
我的情况很简单,我有一个具有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未经授权的响应.
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令牌(无需在浏览器中登录?
到目前为止我正在使用的方法:
The approach I'm using so far:
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.
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:
- 在B2C中创建ROPC策略
- 注册应用程序
-
如下测试策略:
- Create a ROPC policy in B2C
- Register an application
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屋!