azureasp.net-coreauthenticationmicrosoft-entra-id

How to secure API with EntraID


We have an on-premise API that needs be accessed by a mobile APP developed by a third party (don't know which technology). At the moment the authentication is done via user/password against an internal login API that returns a token that is then used in the calls, but this has to be discontinued to use authentication with Azure AD (EntraID) with MFA.

So the question is how to secure the API so we can guarantee that calls have been properly authenticated, and how will the the APP have to be changed to do so.


Solution

  • I agree with you, if you are using username and password to authenticate for a mobile application then the user accounts with MFA enabled is not supported. Refer this MsDoc

    Hence you can make use of InteractiveBrowserCredential authentication which is used by mobile applications and desktop applications.

    I created a Microsoft Entra application and exposed an API like below:

    enter image description here

    Added redirect URL as http://localhost in Mobile and desktop applications platform:

    enter image description here

    Granted API permissions:

    enter image description here

    To secure the API, you can make use of below code:

    using Azure.Core;
    using Azure.Identity;
    using System;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            var scopes = new[] { "api://xxx/access_app" }; 
    
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var options = new InteractiveBrowserCredentialOptions
            {
                TenantId = tenantId,
                ClientId = clientId,
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
                // MUST be http://localhost or http://localhost:PORT
                RedirectUri = new Uri("http://localhost"),
            };
    
            var interactiveCredential = new InteractiveBrowserCredential(options);
    
            var accessToken = await interactiveCredential.GetTokenAsync(new TokenRequestContext(scopes));
            Console.WriteLine($"Access Token: {accessToken.Token}");
        }
    }
    

    I logged in with the MFA enabled user:

    enter image description here

    Access token for the API generated successfully:

    enter image description here

    enter image description here

    Using the above access token, you can call your API.

    Reference:

    Choose a Microsoft Graph authentication provider - Microsoft Graph | Microsoft