Reputation: 450
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
Upvotes: 6
Views: 4983
Reputation: 450
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:
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
Upvotes: 7
Reputation: 14634
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.
Upvotes: 2