{"id":5831,"date":"2019-08-12T04:58:36","date_gmt":"2019-08-12T04:58:36","guid":{"rendered":"https:\/\/blogs.aaddevsup.xyz\/?p=5831"},"modified":"2020-07-29T17:43:43","modified_gmt":"2020-07-29T17:43:43","slug":"using-msal-net-to-call-an-azure-function-app-with-easy-auth-enabled","status":"publish","type":"post","link":"https:\/\/blogs.aaddevsup.xyz\/2019\/08\/using-msal-net-to-call-an-azure-function-app-with-easy-auth-enabled\/","title":{"rendered":"Walkthrough: Using MSAL.Net to call an Azure Function App with Easy Auth enabled"},"content":{"rendered":"

In this post, I’ll walk through the steps for how to create an application using Microsoft Authentication Library for .Net (MSAL.Net)<\/a> to call an Azure AD protected Azure Function App<\/a> using Easy Auth (Azure App Service’ Authentication and Authorization feature<\/a>).<\/p>\n

1. Create an Azure Function with Easy Auth enabled:<\/h2>\n

Assuming you already have an Azure Function App created (refer to https:\/\/docs.microsoft.com\/en-us\/azure\/azure-functions\/functions-create-function-app-portal<\/a> if you don’t know how to create one), go to that Function App in the Azure portal and create an Azure Function. For convenience, I’ll use the Http Trigger<\/a> In-portal template to create an Azure Function.<\/p>\n

\"\"<\/p>\n

Click on ‘Continue’ and then select ‘Webhook + API’ blade and then ‘Create’.<\/p>\n

\"\"<\/p>\n

The template generates the following code in the run.csx file<\/p>\n

\n#r \"Newtonsoft.Json\"\n\nusing System.Net;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.Primitives;\nusing Newtonsoft.Json;\n\npublic static async Task<IActionResult> Run(HttpRequest req, ILogger log)\n{\nlog.LogInformation(\"C# HTTP trigger function processed a request.\");\n\nstring name = req.Query[\"name\"];\n\nstring requestBody = await new StreamReader(req.Body).ReadToEndAsync();\ndynamic data = JsonConvert.DeserializeObject(requestBody);\nname = name ?? data?.name;\n\nreturn name != null\n? (ActionResult)new OkObjectResult($\"Hello, {name}\")\n: new BadRequestObjectResult(\"Please pass a name on the query string or in the request body\");\n}\n<\/pre>\n

\"\"<\/p>\n

Now that we have our Function created, we need to turn on Easy Auth, so navigate to the Azure Function App and select the “Authentication \/ Authorization” link in the ‘Platform features’ tab<\/p>\n

\"\"<\/p>\n

 <\/p>\n

Select ‘On’ for App Service Authentication and ‘Log in with Azure Active Directory’ in the “Action to take when request is not authenticated” section<\/p>\n

 <\/p>\n

\"\"<\/p>\n

 <\/p>\n

In the ‘Authentication Providers’ section select ‘Azure Active Directory’ and choose the Express for Management mode and ‘Create New AD App’ and Save:<\/p>\n

\"\"<\/p>\n

Now that Easy Auth is turned on, test the Function App URL in the browser to make sure it requires authentication. The Function URL can be obtained from the “<\/> Get function URL” link. Append<\/span> the name query string at the end since the Function expects this name value. My test Function URL is https:\/\/easyauthfunctest.azurewebsites.net\/api\/HttpTrigger1?code=zIrQXHC9ypU2ewa4YadZfXgka7XgNG\/U7J\/kDGW79aXig3q907jo2A==&name=Azure<\/span><\/p>\n

 <\/p>\n

When I navigate to the above link, I get prompted for credential and then see the message “Hello, Azure” in the browser after logging in.<\/p>\n

 <\/p>\n

\"\"<\/p>\n

 <\/p>\n

2. Create a new App Registration for the MSAL .Net app<\/h2>\n

Navigate to the Azure portal -> Azure Active Directory -> App registrations -> New registration to create a new App Registration. I use the following parameter for my registration.<\/p>\n

\n\n\n\n<\/colgroup>\n\n\n\n\n
\n

Name<\/p>\n<\/td>\n

\n

msalclient<\/p>\n<\/td>\n<\/tr>\n

\n

Supported account types<\/p>\n<\/td>\n

\n

Accounts in this organizational directory only<\/p>\n<\/td>\n<\/tr>\n

\n

Redirect URI<\/p>\n<\/td>\n

\n

myapp:\/\/auth<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n

Once created, go to that app registration select API permissions -> Add a permission -> select the above Azure Function App in the ‘APIs my organization uses’ tab to add that permission:<\/p>\n

 <\/p>\n

\"\"<\/p>\n

Take note of the following since you will need them later when creating the MSAL App.<\/p>\n

 <\/p>\n

Overview blade:
\n<\/span><\/p>\n

    \n
  • Application ID<\/li>\n
  • Directory ID<\/li>\n<\/ul>\n

    Authentication blade:
    \n<\/span><\/p>\n

      \n
    • \n
      Redirect URI \u2013 this should be myapp:\/\/auth<\/strong>
      \n<\/span>as registered above<\/div>\n<\/li>\n<\/ul>\n

      API permissions blade:
      \n<\/span><\/p>\n

        \n
      • \n
        Get the scope for this Azure Function App: (see screen shot below):<\/div>\n<\/li>\n<\/ul>\n

        \"\"<\/p>\n

         <\/p>\n

        3. Create an MSAL Application<\/h2>\n
          \n
        1. In Visual Studio, create a new C# Console (.Net Framework) project<\/li>\n
        2. \n
          Add the “Microsoft.Identity.Client” nuget package to the project<\/div>\n

          \"\"<\/li>\n

        3. Use the following code in the Program.cs file. Remember to fill in the scopes, ClientId, replyURL, and Tenant (Directory ID) with the info above<\/li>\n<\/ol>\n

           <\/span><\/span><\/span><\/p>\n

          \nclass Program\n{\nstatic string[] scopes = new[] { \"https:\/\/easyauthfunctest.azurewebsites.net\/user_impersonation\" };\nstatic string ClientId = \"xxx\";\nstatic string Tenant = \"xxx\";\nstatic string replyURL = \"myapp:\/\/auth\";\n\u2026\n}\n<\/pre>\n

          [gist id=”9f03df153b77e7cf78041f3fba4880f5″ file=”Program.cs”]<\/span><\/span><\/span><\/p>\n

            \n
          1. \n
            Build and run the application to login to Azure AD. Once logged in you should see the following output in the console<\/div>\n

            \"\"<\/li>\n<\/ol>\n

            Voila, we got the output from Azure Function App.<\/p>\n","protected":false},"excerpt":{"rendered":"

            In this post, I’ll walk through the steps for how to create an application using Microsoft Authentication Library for .Net (MSAL.Net) to call an Azure AD protected Azure Function App using Easy Auth (Azure App Service’ Authentication and Authorization feature). 1. Create an Azure Function with Easy Auth enabled: Assuming you already have an Azure Function App created (refer to https:\/\/docs.microsoft.com\/en-us\/azure\/azure-functions\/functions-create-function-app-portal if you don’t know how to create one), go…<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5,8],"tags":[36,59],"class_list":["post-5831","post","type-post","status-publish","format-standard","hentry","category-authentication","category-azure-ad","category-easy-auth","tag-authentication","tag-easy-auth"],"_links":{"self":[{"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/posts\/5831"}],"collection":[{"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/comments?post=5831"}],"version-history":[{"count":55,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/posts\/5831\/revisions"}],"predecessor-version":[{"id":7428,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/posts\/5831\/revisions\/7428"}],"wp:attachment":[{"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/media?parent=5831"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/categories?post=5831"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.aaddevsup.xyz\/wp-json\/wp\/v2\/tags?post=5831"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}