I have an API and it's using the Microsoft Identity Platform as a way to authenticate users.
I need to refactor It because I think I've done some errors in the implementation.
So to start fresh, I want to know what is the logic on how to handle 3rd party authenticators. With that said, I would be thankful if someone could confirm if the following authentication flow makes sense.
The sequence that seems plausible is: Authentication Sequence
login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
?code
parametercode
and redirect_uri
to my APIaccess_token
and refresh_token
by passing the code
to the token endpoint login.microsoftonline.com/{tenant}/oauth2/v2.0/token
.Token validation
When storing the tokens in the database, store their expiration date.
refresh_token
and replace old tokens with the new tokens.Microsoft provides authentication libraries (MSAL) for different clients. But these libraries, from what I understand, it is to authenticate the user, storing the tokens locally, and consume the Microsft Graph API. This leads me to question the reliability of my flow, because the way I made it, it is not compatible with these libraries.
I believe you need not do all of these and can make things really simple.
Here's what you can do:
Assuming you're using .Net 5/Core, you would need to add the following lines in your Startup.cs first:
services
.AddMicrosoftIdentityWebApiAuthentication(Configuration, "ApiSettingsConfigurationSectionName")
.EnableTokenAcquisitionToCallDownstreamApi()//This does the magic of getting the token for protected resources.
.AddInMemoryTokenCaches();
Then this is how you would get the token for a protected resources in your API controllers:
private readonly ITokenAcquisition _tokenAcquisition;
...
...
...
public YourController(ITokenAcquisition tokenAcquisition,
...other injected parameters
)
{
_tokenAcquisition = tokenAcquisition;
...
}
/// <summary>
/// Gets the access token on behalf of signed-in user to perform Azure
/// Resource Manager (ARM) API.
/// </summary>
/// <returns>
/// Access token.
/// </returns>
private async Task<string> GetAccessTokenForAzureSubscriptionManagementApiRequest()
{
string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(['scopes for the protected API e.g. https://management.azure.com/user_impersonation']);
return accessToken;
}
Microsoft provides authentication libraries (MSAL) for different clients. But these libraries, from what I understand, it is to authenticate the user, storing the tokens locally, and consume the Microsft Graph API.
This is not entirely true. MSAL can be used to acquire token for any API that is protected by Azure AD. Graph API is certainly one of them but then you can also use MSAL against your own API provided it is protected by Azure AD.