Class MsalTestTokenProvider
Acquires real Azure Entra ID tokens for E2E integration tests using the MSAL ROPC (Resource Owner Password Credentials) flow.
[RequiresUnreferencedCode("MSAL uses reflection for token serialization and is not AOT-compatible.")]
public sealed class MsalTestTokenProvider
- Inheritance
-
MsalTestTokenProvider
- Inherited Members
- Extension Methods
Examples
var tokenProvider = new MsalTestTokenProvider(msalOptions);
var token = await tokenProvider.AcquireTokenAsync("salesRep");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Remarks
ROPC is deprecated for production use but remains suitable for automated test scenarios against dedicated test tenants. The test tenant must have ROPC enabled and MFA disabled for test users.
Tokens are cached per MsalTestTokenProvider instance. Create one instance per test class or fixture to avoid redundant token acquisitions.
Constructors
MsalTestTokenProvider(MsalTestOptions)
Initializes a new MsalTestTokenProvider with the specified options.
public MsalTestTokenProvider(MsalTestOptions options)
Parameters
optionsMsalTestOptionsMSAL configuration including tenant, client, and test user credentials.
Methods
AcquireTokenAsync(string, CancellationToken)
Acquires an access token for the named test user using the ROPC flow. Tokens are cached by MSAL — subsequent calls for the same user return cached tokens until they expire.
public Task<string> AcquireTokenAsync(string testUserName, CancellationToken cancellationToken = default)
Parameters
testUserNamestringThe key in TestUsers identifying the test user (e.g.,
"salesRep","admin").cancellationTokenCancellationTokenCancellation token.
Returns
Exceptions
- KeyNotFoundException
Thrown when
testUserNameis not found in TestUsers.- MsalException
Thrown when token acquisition fails (invalid credentials, tenant misconfiguration, etc.).