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.