Trigger a Microsoft Flow from your own app

If this then Microsoft Flow

Most of us know about IFTTT. And for those who do not: it stands for If This, Then That and is basically a cloud based workflow engine that lets you wire up different backend systems and apps and create channels and rules between them. Well, Flow is Microsoft’s take on IFTTT and is part of the new PowerApps and Flow offering. It aims at providing a Web environment for creating and managing Flows that can be used standalone or combined with the brand new PowerApps.

Microsoft Flow promises to able to support almost any “time consuming task or process” and currently supports 42 services. Yes 42, the answer to life, the universe and everything!

Note: Microsoft Flow is not to be confused with Microsoft Azure Logic Apps. Although they do share technology, platform and some of the offered functionality, Logic Apps are more targeted at the developer covering complex scenarios and tight integration with Visual Studio, Azure Resource Manager and the Azure Portal.  For more information on Logic Apps, see the service description: https://azure.microsoft.com/en-us/services/logic-apps/

Be warned, this stuff is awesome, but also new,  paint not even dry.  No guarantees 🙂 

Because it is still in preview the offering is far from complete.  But if we look at the connections already available today it already is a compelling tool.  Although you can create flows that act on other events (Facebook post, Twitter mention) or from a PowerApp there is currently no way to fire a flow on demand say from an external website or your own Single Page App. Note: Unlike IFTTT,  because they do have an option to create actions fired by Http requests.

I expect Flow to land this functionality in the future and render this guidance useless 🙂 but for now I will share my findings.

Scenario

So I decided to try to make the following simplified scenario work:

  1. Phone user presses a button in my app
  2. This triggers a Microsoft Flow
  3. The Flow does “stuff”, maybe something like adding a Dynamics CRM Online opportunity

We simplify this a bit more and create a modest Angular 1.x app and trigger our flow from a HTML input button. The Flow itself just sends out an email, but any of the available services should work. We can also send all kinds of payload data to the Flow, but I will save that for a future post.

While I was doing the research for a small proof of concept, I found this great topic on the Flow powerusers forum providing valuable insight on the inner workings of Flow. Make sure to check it out, although all the required info will be included in this post. https://powerusers.microsoft.com/t5/Flow-Forum/Example-Http-action/td-p/1105

Requirements, pre-requisites and setup

Flows run on Azure (they share technology with Azure Logic Apps and as far as I can tell they actually are Logic Apps), so we need a few things from Microsoft Azure.

  • An Azure Active Directory Tenant
  • A user account within the Azure Active Directory Tenant with a configured Microsoft Flow
  • A client application in this Azure Active Directory Tenant
  • Permission for this application to access the Azure Service Management APIs
  • An Authorization header token. According to the forementioned forum topic, we should be able to use the same token that would be used to talk to the Azure Resource Manager endpoint.

Assuming we have a working Azure Active Directory in place, let’s start with creating the user account. In this case, a simple user account will work and the account only needs some basic permissions to be able to get the correct Authorization token. It is also this account that will be used to login to Microsoft Flow and create the flow we will trigger from the app.

1

We can now use the new Role Based Access Control system to allow this account to get the Azure Resource Manager token. In this case I added the account to the Reader role on my Azure subscription, although we could have probably setup a more fine grained permission.

2

Next stop: creating our client App in the Azure Active Directory.

Azure Active Directory Client Application

From the Active Directory page, Add an application and make sure it is of type “Native Client Application”. You also need to supply a redirect URI for the OAuth2 response. Make sure you apply an applicable value, in my testcase I use my local IIS Express web server.

345

The most important part of information we need for our client application is the Client ID (in the form of a GUID), so make sure you make note of it.

Permissions

To be able to access the Service Management APIs we need set this permission from the “Configure”tab of your Client Application:

6

Token and Implicit Grant

In order to trigger the flow we call an endpoint (see the forum topic mentioned earlier). This endpoint expects the same token that would be used to talk to the Azure Resource Manager endpoint, so we can acquire the correct token from https://management.core.windows.net/

This is all undocumented, so if things go wrong you would have to dive in yourself to see what is wrong. To check how Flow works under the hood, I find it the easiest to login to PowerApps or Flow and use the Google Chrome Dev Tools to check out things like the required Authorization tokens and Http payload.

The Request Headers for instance will show you the Authorization info, which you can decode with tools like https://jwt.io

7

In this simple scenario (calling a Flow from an Angular Single Page App) I would like to leverage the Azure AD Sign On process to acquire this token. I do not care about refresh tokens and only need an access token. This type of authentication is supported by Azure AD although not enabled by default and is known by the name “oauth2AllowImplicitFlow”. You can change this setting by downloading and editing your application’s manifest.

  1. Go to your Application registered in Azure Active Directory and from the Dashboard click Manage Manifest/ Download Manifest;
  2. Open the file and look for the oauth2AllowImplicitFlow property and make sure to change this to “true”;
  3. You can then upload the file back to your application (Manage Manifest/ Upload Manifest) and save the changes.

A lot of pieces to the puzzle, but this concludes the Azure part of our exercise. Next we need to create a simple Flow that we will call from our application.

Flow

We create a flow by logging into https://flow.microsoft.com/ . We need to use the same account we setup earlier.

  1. From the start screen we need to navigate to “My Flows” and select “Create from blank” to start creating the flow;
  2. For the trigger we select “PowerApps” as if we were going to trigger this flow from a PowerApp;
  3. The action can be anything, but for this exercise I will pick a generic “Mail – Send Email” action;
  4. Name the Flow and click “Create”.

8

The final piece of information we need now is the GUID identifying our Flow. We can get this GUID from the URL once we manage or edit our Flow.

10

Our Client App

Time to create our app! I provided the complete source code of the demo app at the end of this article.

Adal JS

The app uses the Active Directory Authentication Library for JavaScript (ADAL JS) for handling our authentication. Please see the GitHub project for more information: https://github.com/AzureAD/azure-activedirectory-library-for-js

The first thing we need to do is configure ADAL Authentication Service Provider with the correct settings. This is typically done during the app config phase:

app.config(['$httpProvider', 'adalAuthenticationServiceProvider', function ($httpProvider, adalAuthenticationServiceProvider) {
adalAuthenticationServiceProvider.init(
{
cacheLocation: 'localStorage', //optional
anonymousEndpoints: ['Scripts/Login'],
clientId: 'your client ID from the Azure App',
endpoints: {
'https://management.core.windows.net/': 'https://management.core.windows.net/'
}
},
$httpProvider // Http provider to inject request interceptor and attach tokens
);
}]);

Couple of things to note here:

  • Make sure you use the client ID from the Azure App we registered earlier;
  • Couple of optional settings, you can ignore them as they are needed for this particular app;
  • We get our token from https://management.core.windows.net/, but we will send our trigger to a different endpoint. In this case the interceptor will not attach the tokens, because it does not match any of the endpoints. We will have to handle this in our code as we will see in a later snippet.

The trigger

The trigger itself is a Http POST to a predefined URL with the correct access token attached.

var resource = adalAuthenticationService.getResourceForEndpoint('https://management.core.windows.net/');
var tokenForFlow = adalAuthenticationService.acquireToken(resource);

$http({
method: 'POST',
headers: {
'Authorization': 'Bearer ' + tokenForFlow.$$state.value
},
url: 'https://msmanaged-na.azure-apim.net/apim/logicflows/5cc77c51-9a87-4716-99d7-3aac38bb4839/triggers/manual/run?api-version=2015-02-01-preview'
}).then(function successCallback(response) {

}, function errorCallback(response) {

});

Again, couple of things to note:

  • We need to get the token by hand (with the help of adalAuthenticationService.acquireToken ) because the interceptor does not help us here;
  • The POST url contains the GUID of our Flow, so make sure you update this accordingly.

But before we can do any of this stuff, we need to sign in to Azure AD. Fortunately the ADAL JS library makes this extremely simple, we just need to call the login method!

vm.login = function () {
adalAuthenticationService.login();
}

Run it

If we now run the app we need to login to Azure AD using the account we created earlier. If we then trigger our Flow, all should work as designed.

11

You can download the demo application here: Blog.Examples.DemoCallFlow.zip

/Y.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s