How to use Logic App with Azure Active Directory Authorization Policies
Published Dec 15 2020 01:42 AM 9,764 Views

 

Mobarqaw_1-1607955738591.png

 

In this article, I will demonstrate how to call a logic app with the Aouth2 approach

The problem that I going to solve is to provide a gatekeeper page that will not download files from the Storage account unless the user is authenticated.

 

I will utilize a static web site on the storage account to host small HTTP pages and javascripts

Spoiler
the Idea of a Static site is to provide simple hosting and the same solution can be hosted on the app service as well 

the web page will be responsible to obtain the Bearer token when the user Sign-in

then it will use this Token to pass it to the logic app  

 

Spoiler

Create website.

You can create the static by following the Host a static website in Azure Storage | Microsoft Docs

Mobarqaw_2-1607955738597.png

 

 

Create the Active Directory application

 

I have followed the article https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-javascript

Register your application
  1. Sign in to the Azure portal.
  2. If you have access to multiple tenants, use the Directory + subscription filter Mobarqaw_3-1607955738600.png

     

     in the top menu to select the tenant in which you want to register an application.
  3. Search for and select Azure Active Directory.
  4. Under Manage, select App registrations > New registration.
  5. Enter a Name for your application. Users of your app might see this name, and you can change it later.
  6. Under Supported account types, select Accounts in any organizational directory and personal Microsoft accounts.
  7. Select Register. On the app Overview page, note the Application (client) ID value for later use.
  8. Under Platform Configurations, select Add a platform. A panel opens on the left. There, select the Web Applications region.
  9. Still on the left, set the Redirect URI value to [the static website URL] Then, select Access Token and ID Token.
  10. Select Configure.

 

1.2.2        Build the HTML page with msal.js

Create HTML with the below content

 

 

 

 

 

!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
  <title>Demo for using Logic app using Azure Active Directory Authorization Policies </title>
  <link rel="SHORTCUT ICON" href="./favicon.svg" type="image/x-icon">

  <!-- msal.min.js can be used in the place of msal.js; included msal.js to make debug easy -->
  <script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.4/js/msal.js"
    integrity="sha384-fTmwCjhRA6zShZq8Ow5ZkbWwmgp8En46qW6yWpNEkp37MkV50I/V2wjzlEkQ8eWD"
    crossorigin="anonymous"></script>

  <!-- msal.js with a fallback to backup CDN -->
  <script type="text/javascript">
    if (typeof Msal === 'undefined') document.write(unescape("%3Cscript src='https://alcdn.msftauth.net/lib/1.4.4/js/msal.js' type='text/javascript' %3E%3C/script%3E"));
  </script>

  <!-- adding Bootstrap 4 for UI components  -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>

<body>
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <a class="navbar-brand" href="/">Storage account Gate keeper using logic app </a>
    <div class="btn-group ml-auto dropleft">
      <button type="button" id="signIn" class="btn btn-secondary" onclick="signIn()">Sign In</button>
      <button type="button" id="signOut" class="btn btn-success d-none" onclick="signOut()">Sign Out</button>
    </div>
  </nav>
  <br>
  <h5 class="card-header text-center">this is a demo only site </h5>
  <br>
  <div class="row" style="margin:auto">
    <div id="card-div" class="col-md-3 d-none">
      <div class="card text-center">
        <div class="card-body">
          <h5 class="card-title" id="welcomeMessage">Please sign-in to see your profile and read your mails</h5>
          <div id="profile-div"></div>
          <br>
          <br>
          <button class="btn btn-primary" id="seeProfile" onclick="downloadFile()">Download File</button>
          <br>
        </div>
      </div>
    </div>
    <br>
    <br>
    <div class="col-md-4">
      <div class="list-group" id="list-tab" role="tablist">
      </div>
    </div>
    <div class="col-md-5">
      <div class="tab-content" id="nav-tabContent">
      </div>
    </div>
  </div>
  <br>
  <br>
  <!-- importing bootstrap.js and supporting js libraries -->
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
    integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
    crossorigin="anonymous"></script>
  <!-- importing app scripts (load order is important) -->
  <script type="text/javascript" src="./authConfig.js"></script>
  <script type="text/javascript" src="./ui.js"></script>
  <script type="text/javascript" src="./authPopup.js"></script>

</body>

</html>

 

 

 

 

 

 

 

Create file authPopup.js

 

 

 

 

 

// Create the main myMSALObj instance
// configuration parameters are located at authConfig.js
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
var Bearer = ''
let searchParams = new URLSearchParams(window.location.search)
let fileParam = searchParams.get('file')
function signIn() {
  myMSALObj.loginPopup(loginRequest)
    .then(loginResponse => {
      console.log("id_token acquired at: " + new Date().toString());
      console.log(loginResponse);

      if (myMSALObj.getAccount()) {
        Bearer = loginResponse.idToken.rawIdToken;
        showWelcomeMessage(myMSALObj.getAccount());
      }
    }).catch(error => {
      console.log(error);
    });
}

function signOut() {
  myMSALObj.logout();
}

//endpoint, token, callback
function downloadFile() {

  const headers = new Headers();
  const bearer = `Bearer ${Bearer}`;

  headers.append("Authorization", bearer);
  headers.append("FileName", fileParam);

  const options = {
    method: "post",
    headers: headers
  };
  fetch(logicAppUrl, options)
    .then(resp => resp.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      // the filename you want
      a.download = fileParam;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      alert('your file has downloaded!'); // or you know, something with better UX...
    })
    .catch(error => console.log(error))
}

 

 

 

 

authConfig.js

 

 

 

 

 
// Config object to be passed to Msal on creation.
// For a full list of msal.js configuration parameters, 
// visit https://azuread.github.io/microsoft-authentication-library-for-js/docs/msal/modules/_authenticationparameters_.html
const msalConfig = {
  auth: {
    clientId: "7ebe8908-7acd-4e20-b1f4-24715b364cf0",
    authority: "https://login.microsoftonline.com/common",
    redirectUri: "https://largfile.z6.web.core.windows.net",
  },
  cache: {
    cacheLocation: "sessionStorage", // This configures where your cache will be stored
    storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
  }
};  
  
// Add here the scopes to request when obtaining an access token for MS Graph API
// for more, visit https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-core/docs/scopes.md
const loginRequest = {
  scopes: ["openid", "profile", "User.Read"]
};

const logicAppUrl='https://prod-39.eastus.logic.azure.com:443/workflows/92083fac9d2c4805b153907db6976f86/triggers/manual/paths/invoke?api-version=2016-10-01'

 

 

 

 

Creating the logic app

 

The logic app will receive the request using HTTP and will pass the file name to the storage account action

Mobarqaw_4-1607955738602.png

 

 

1.3.1        Enable logic app Azure Active Directory Authorization Policies

Make the issuer https://login.microsoftonline.com/9188040d-6c67-4c5b-b112-36a304b66dad/v2.0  The GUID that indicates that the user is a consumer user from a Microsoft account is 9188040d-6c67-4c5b-b112-36a304b66dad for information at

https://docs.microsoft.com/en-us/azure/active-directory/develop/access-tokens

 

 

Mobarqaw_5-1607955738604.png

 

More information on Secure access and data - Azure Logic Apps | Microsoft Docs

 

the HTML and JavaScript attached 

Version history
Last update:
‎Dec 15 2020 01:42 AM
Updated by: