1
votes

I am having a .Net Core 2.0 asp.net mvc web application. For the same I have a .Net Standard 2.0 unit test project. For the unit test written I have to call a Azure AD protected Web API. Can anyone let me know how can we get azure ad access token from a unit test project in .net standard 2.0.

It is possible in .Net framework as it has "UserPasswordCredential" class available in the "Microsoft.IdentityModel.Clients.ActiveDirectory" dll. But this class is removed in .Net Standard 2.0 (https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/482)

1

1 Answers

0
votes

I've used something like this for integration tests:

string tokenUrl = _authority + "oauth2/token";
var req = new HttpRequestMessage(HttpMethod.Post, tokenUrl)
{
    Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        ["grant_type"] = "password",
        ["client_id"] = settings.ClientId,
        ["client_secret"] = settings.ClientSecret,
        ["resource"] = _resourceUri,
        ["username"] = settings.UserName,
        ["password"] = settings.Password
    })
};

HttpResponseMessage res = await _client.SendAsync(req);

string json = await res.Content.ReadAsStringAsync();
AadTokenResponse tokenResponse = JsonConvert.DeserializeObject<AadTokenResponse>(json);

There's a few class-level fields like the AAD authority, API resource URI and an HttpClient.

So what this does is acquire an access token using the Resource Owner Password Credentials Grant flow. This is one of those few cases where using this flow actually makes sense. We acquire an access token in a user's context without a login window. This flow should not be used when something better is available, and in this case also requires that the user is not federated, does not have MFA etc.

You'll probably want to cache the token so you don't hammer the token endpoint from your tests pointlessly.