Azure AD B2C get token programatically for unit testing

好久不见. 提交于 2019-12-22 10:56:31

问题


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.

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.

Is there a way to generate a valid B2C token programmatically (without login in the browser?

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);
}

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

Thanks in advance! Ivan


回答1:


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. 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




回答2:


Your unit test is acquiring a token from the Azure AD v1.0 endpoint rather than the Azure AD B2C v2.0 endpoint.

Your Azure function is expecting the token to be issued by the Azure AD B2C v2.0 endpoint.

In the short term, you can consider acquiring the token from the Azure AD B2C v2.0 endpoint by replaying the browser requests using the HttpClient class.

In the near term, support for the resource owner password credential grant by Azure AD B2C will enable your unit test to acquire a token from the Azure AD B2C v2.0 endpoint by POSTing a user credential to the endpoint.



来源:https://stackoverflow.com/questions/49307985/azure-ad-b2c-get-token-programatically-for-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!