How to consume Azure REST API App with Azure Active Directory authorization On

北战南征 提交于 2019-12-01 14:37:21

I managed to find a solution on how to enable AAD authorization to Azure REST API App. Just in case anyone has the same challenge, I hope this will be helpful.

These are the steps I did:

1) In App services -> Authentication/authorization

  • App Service Authentication => On
  • Action to take when request is not authenticated => Login with AAD
  • Configured AAD with Express settings (there you have to create Azure AD App for you API App - i.e. "App registration" for your service)

2) In Azure Active Directory -> App registrations

  • Add registration for your client app
  • Edit Manifest of your client app - in the requiredResourceAccess section you must add information about REST API App:
    • resourceAppId -> insert REST API App id here
    • resourceAccess {id} -> OauthPermission id value of REST API (you can get it in REST API's manifest!)

3) In your client application

  • generate your REST client using Autorest (from solution explorer: Add\REST API client) or create it manually
  • add Microsoft.IdentityModel.Clients.ActiveDirectory nuget pack
  • get and use token to access your API with code similar to this:

        //request
        (..)
        var tokenCreds = getToken();
        ServiceClientCredentials credentials = tokenCreds;
    
        using (var client = new YourAPI(credentials)) {
        ...
        }
        (..)
    
        //getting token
    
    private static TokenCredentials getToken()
    {
        //get this from Federation Metadata Document in 
        //Azure Active Directory App registrations -> Endpoints
        var authority = "f1...";
    
        //Identifier of the target resource that is the recipient of the requested token
        var resource = "https://yourapi.azurewebsites.net";
    
        //client application id (see Azure Active Directory App registration
        //for your client app
        var clientId = "a71...";
    
        //return url - not relevant for Native apps (just has to be valid url)
        var redirectUri = "https://just-some-valid-url.net";
    
        AuthenticationContext authContext =
        new AuthenticationContext(string.Format
        ("https://login.windows.net/{0}",
    authority));
    
        AuthenticationResult tokenAuthResult =
        authContext.AcquireTokenAsync(resource,
        clientId,
        new Uri(redirectUri),
        new PlatformParameters(PromptBehavior.Auto)).Result;
    
        return new TokenCredentials(tokenAuthResult.AccessToken);
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!