How to use form-urlencoded content type in Power Automate Custom Connector

Content type x-www-form-urlencoded is used generally to send text data in a query string in the form of name value pairs separated by ampersand. In this blog post, let us see how to use the content-type

  • x-www-form-urlencoded

in a Power Automate custom connector. Refer to this post, if you would like to find out how to use it in a HTTP connector. Find below the screenshot from postman with an API from Twilio (Sample) to send a WhatsApp message with content type x-www-form-urlencoded

x-www-form-urlencoded in a Custom Connector:

The x-www-form-urlencoded content type has its form data which is encoded and sent in a single block on the HTTP request body.

Custom Connector:

To call the above API with the content type x-www-form-urlencoded in a custom connector, the first step is to create a connector from blank with the authentication type filled in (Basic, API Key etc) on the security tab. Now Add a New action to the call the above API. Click + Import from sample to enter details of the API request like Verb, URL and Headers (Content-Type application/x-www-form-urlencoded) and Body. For Body, just add {}. The content on body will sent on the Power Automate cloud flow. PFB screen shot for the action definition

After the above details are entered, click Import.

In the Request section, click the Content-Type under Headers, enter the default value application/x-www-form-urlencoded and then make it required with the visibility set to Internal. This setting will hide the parameter from the cloud flow

Make the body required. Create the connector after all the details has been entered.

Custom Connector in Power Automate Cloud Flow:

The form values to be sent on the API request body with x-www-form-urlencoded implementation must be encoded & the values must be separated by ampersand. Expression encodeUriComponent can be used to encode the form values.

In the Cloud flow, add a compose action with all the values encoded and separated by ampersand (&). Now add the custom connector action which will prompt you to create a connection. In the body section, from the dynamic content select the Outputs of the compose action.

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Create a Power Automate custom connector from Postman V2 Collection

Postman collections makes the creation of custom connectors in Power Automate easier & quicker. As of time I am writing this article, to create a custom connector using Postman collection in Power Automate the version of Postman collection has to be V1. The current version of collections exported from Postman is V2. There is a NPM package by the name Postman Collection Transformer to rescue which helps converting the collection to V1 and vice versa.

Pre-Requisites:

Step 1: Install the NPM package postman-collection-transformer using the following command

npm install -g postman-collection-transformer

Step 2: Generate the Postman collection from Postman

Step 3: Run the following command to generate the V1 collection. For more information on the NPM package go through this link.

postman-collection-transformer convert --input ./Postman_collection-V2.json --input-version 2.0.0 --output ./Postman_collection-V1.json --output-version 1.0.0 --pretty --overwrite

Step 4: V1 Postman collection is ready, you can now proceed with the creation of custom connector in the flow portal.

As pointed out by Richard Wilson, there are third party portals (Requires Registration) available which helps in converting the format of the Postman collection.

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

How to use form-data and form-urlencoded content type in Power Automate or Logic Apps HTTP action

Content type multipart/form-data is used to send both text and binary data to the server and x-www-form-urlencoded is used more generally used to send text data in a query string in the form of name value pairs separated by ampersand. In this blog post, let us see how to use the content-type

  • multipart/form-data
  • x-www-form-urlencoded

in a Power Automate or Logic apps HTTP action to post data with an API which has implemented the content-type. Find below the screenshot from postman with a sample API

multipart/form-data in HTTP Action:

From the above screenshot, the API is called using the content type multipart/form-data. The multipart refers to the data (in the above screenshot it is To, From & Body) which is divided into multiple parts and sent to server. For each key value pair aka part, you will have to construct something like

{
      "headers": {
        "Content-Disposition": "form-data; name=\"KEY\""
      },
      "VALUE": "what ever value you would like to send"
}

Backslash is used close the Content-Disposition header value else you will get Invalid-JSON.

To call the API displayed from the above screenshot on the HTTP Action, the body of the HTTP action should have the two attributes $content-type and $multipart as shown below

{
  "$content-type": "multipart/form-data",
  "$multipart": [
    {
      "headers": {
        "Content-Disposition": "form-data; name=\"To\""
      },
      "body": "whatsapp:+123456"
    },
    {
      "headers": {
        "Content-Disposition": "form-data; name=\"From\""
      },
      "body": "whatsapp:+178910"
    },
    {
      "headers": {
        "Content-Disposition": "form-data; name=\"Body\""
      },
      "body": "Your appointment is coming up on July 21 at 4PM"
    }
  ]
}

You can upload files using the form-data content type

{
      "headers": {
        "Content-Disposition": "form-data; name=\"file\"; filename=\"fileName.png\""
      },
      "body": "file-content"
}

The file content can be the output of the SharePoint or OneDrive connector.

x-www-form-urlencoded in HTTP Action:

The x-www-form-urlencoded content type has its form data which is encoded and sent in a single block on the HTTP request body. To call the sample API from the screenshot posted at the top of this post in the HTTP Action, the form values must be encoded & the values be separated by ampersand. Expression encodeUriComponent can be used to encode the form values

Headers:

Key: Content-Type

Value: application/x-www-form-urlencoded

Body (Separated by &):

Key=Value&Key=Value

Find below screenshot for your reference

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Call a SharePoint REST API as an Application in Power Automate HTTP Connector

SharePoint connector in Power Automate is very rich with various actions that can make the developers or makers life simple when it comes to interacting with SharePoint data. There might be some actions like

  • Breaking permission to a list item
  • Creating a site
  • Adding user to a SharePoint group etc

which is not possible through the SharePoint standard connector or MS Graph API as of the time I am writing this article, SharePoint REST API to rescue. The SharePoint online REST API enables developers to remotely interact with SharePoint data. There is an action Send an HTTP request to SharePoint which could come handy in many scenarios, the point to note here is the action uses the context of user aka flow creator while executing the API. In this blogpost, let us see how to call a SharePoint REST API to create a Modern SharePoint communication site as an application in a Power Automate cloud flow using the HTTP connector with the help of a Self-Signed certificate. Find below the list of steps to enable calling the SharePoint REST API using certificate credentials

  1. Creation of Self-Signed certificate
  2. Application Registration in Azure AD Portal
  3. Creation of Power Automate cloud flow with the HTTP Connector
    • Method 1: Without using Azure Key Vault
    • Method 2: Azure Key Vault to store Certificate

Pre-Requisites:

Creation of Self-Signed certificate:

The first step is to create a certificate. Refer to this blog post for instructions creating a self signed certificate using the PnP utility

https://ashiqf.com/2021/07/05/call-microsoft-graph-api-using-a-certificate-in-a-power-automate-http-connector#self-signed-certificate

Application Registration in Azure AD Portal:

Register an application in Azure AD and obtain the client id & tenant id for the registered application. In this example I have added the Sites.Read.All Application permission with Admin Consent to create the SharePoint communication site, this permission is more than enough to create the site as an Application. Grant appropriate permission based on the requirements, for e.g to break permission on list items grant Sites.Manage.All. Find below screenshot for your reference for granting permissions

To add the above created self-signed certificate, click Certificates & secrets under the Manage blade. Click Upload certificate > Select the certificate file MSFlow.cer > Add

Creation of Power Automate cloud flow with the HTTP Connector:

Let us see below how to access the SharePoint REST API to create a SharePoint site with & without using the Azure Key Vault.

  1. Method 1: Without using Azure Key Vault
  2. Method 2: Azure Key Vault to store Certificate

Method 1: Without using Azure Key Vault

In the cloud flow, add a Compose action to store the PfxBase64 value copied during the creation of the certificate. Now add the HTTP action to create a Modern Communication site

Request Type: POST

URL: https://tenantname.sharepoint.com/_api/SPSiteManager/create

Headers:

Key: accept

Value: application/json

Body:

{
  "request": {
    "Title": "Communication Site from Cloud Flow",
    "Url": "https://tenantname.sharepoint.com/sites/commsitefromPA",
    "Lcid": 1033,
    "ShareByEmailEnabled": false,
    "Description": "Description",
    "WebTemplate": "SITEPAGEPUBLISHING#0",
    "SiteDesignId": "6142d2a0-63a5-4ba0-aede-d9fefca2c767",
    "Owner": "UPNoftheSiteAdministrator@domain.com",
    "WebTemplateExtensionId": "00000000-0000-0000-0000-000000000000"
  }
}

Change the SiteDesignId for the different site teamplate Topic, Showcase, Blank

Authentication: Active Directory OAuth

  • Tenant: TenantId
  • Audience: https://tenantname.microsoft.com
  • Client ID: Azure AD Client Id
  • Pfx: Output of the compose action
  • Password: Certificate password given during the creation

Find below screenshot for your reference

Run the flow, it should be able to create the Site. Find below screenshot of the flow run

Method 2: Azure Key Vault to store Certificate

Azure Key Vault is a cloud service for storing and accessing secrets enabling your applications accessing it in a secure manner. Follow my blog article which I have written to call a Microsoft Graph API with Certificate using a Azure Key Vault to store the certificate

https://ashiqf.com/2021/07/05/call-microsoft-graph-api-using-a-certificate-in-a-power-automate-http-connector/#azure-key-vault

Summary:

Custom Connector can be used to call a SharePoint REST api in the context of the user. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Azure Key Vault in Power Automate cloud flow – Could not retrieve values

Recently I was trying to connect Azure key vault to retrieve certificate details using the action called Get Secret in a cloud flow, as of the time writing this article I am not able to successfully establish the connection. It gave me an error Could no retrieve values as shown below instead of prompting me to enter the credentials to create the connection successfully.

To create a successful connection, follow the steps outlined

Step 1: Go to the Connection as shown below from the Left navigation bar > Select the Azure Key vault connection > Edit.

The first step of adding the Get Secret action in flow would have created the connection with the status Parameter value missing

Step 2: Enter the name of the Azure Key vault and click Save

Step 3: Click Fix connection & sign in using the account which has access to the Azure Key Vault. After this step, the status will be connected.

Step 4: Go back the cloud flow which has the action, the action would now be able to get the secrets from Key Vault as expected. To make sure the action has the correct connection, click the three dots and verify from the My connections list

Summary:

Hope Microsoft fixes this issue for the Azure Key vault connector. I have used Azure Key vault to store Secret & Certificates for authenticating against MS Graph to access its rich api endpoints. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Call Microsoft Graph API using a certificate in a Power Automate HTTP connector

In this blog article, let us see how to call a Microsoft Graph API as an application in a Power Automate HTTP connector using a certificate credentials instead of a secret from the Azure Active directory application. Microsoft recommends using a certificate (instead of a client secret) as a credential for a higher level of assurance. Find below the list of actions to enable calling the Graph API using certificate credentials

  1. Creation of Self-Signed certificate
  2. Application Registration in Azure AD Portal
  3. Creation of Power Automate cloud flow with the HTTP Connector
    • Method 1: Without using Azure Key Vault
    • Method 2: Azure Key Vault to store Certificate

Pre-Requisites:

Creation of Self-Signed certificate:

The first step is to create a certificate. A self-signed certificate can be created by using the Windows PowerShell command New-SelfSignedCertificate or PnP PowerShell command New-PnPAzureCertificate. The self-signed certificate will be used in the Azure AD application. Find below PnP PowerShell command to create the certificate with the default validity of 10 years and secured with a password.

New-PnPAzureCertificate -CommonName "MSFlow Certificate" -OutPfx MSFlow.pfx -OutCert MSFlow.cer -CertificatePassword (ConvertTo-SecureString -String "pass@word1" -AsPlainText -Force)

From the above screenshot, the certificate files MSFlow.pfx and MSFlow.cer will be available on C:\Users\ashiq\Desktop\Projects\PowerAutomate. Copy the PfxBase64 and the password which will be used in the HTTP connector while calling the Graph API. To get the details of an existing certificate, the PnP command

Get-PnPAzureCertificate -Path "MSFlow.pfx" -Password (ConvertTo-SecureString -String "pass@word1" -AsPlainText -Force)

If you already have a self-signed certificate available, find the below command to convert the certificate to PfxBase64 encoding

$fileContentBytes = get-content 'C:\Users\ashiq\Desktop\Projects\PowerAutomate\MSFlow.pfx' -Encoding Byte
[System.Convert]::ToBase64String($fileContentBytes) | Out-File 'PfxBase64.txt'

Application Registration in Azure AD Portal:

Register an application in Azure AD and obtain the client id & tenant id for the registered application. In this example I have added the Application permission with Admin Consent to access all the recent events of a user from Outlook.

To add the above created self-signed certificate, click Certificates & secrets under the Manage blade. Click Upload certificate > Select the certificate file MSFlow.cer > Add

Once the certificate is added successfully, you would be able to see the certificate Thumbprint with the Start date & Expiry date

Creation of Power Automate cloud flow with the HTTP Connector:

Let us see below how to access a Microsoft Graph API with & without using the Azure Key Vault.

  1. Method 1: Without using Azure Key Vault
  2. Method 2: Azure Key Vault to store Certificate

Method 1: Without using Azure Key Vault

In the cloud flow, add a Compose action to store the PfxBase64 value copied during the creation of the certificate. Now add the HTTP action to get the users events from the default calendar

Request Type: GET

URL: https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/calendar/events

Authentication: Active Directory OAuth

  • Tenant: TenantId
  • Audience: https://graph.microsoft.com
  • Client ID: Azure AD Client Id
  • Pfx: Output of the compose action
  • Password: Certificate password during the creation Find below screenshot for your reference

Find below screenshot for your reference

Run the flow, it should be able to get the outlook events as an application for the given user.

Method 2: Azure Key Vault to store Certificate

Azure Key Vault is a cloud service for storing and accessing secrets enabling your applications accessing it in a secure manner. Follow this article to upload the above generated certificate to the Azure key vault.

After the certificate is uploaded to the Azure Key Vault, with the help of the premium Azure Key Vault connector you would be able to access & use the secret in your cloud flow or logic app.

Step 1: Add the action Get secret in the flow. After entering the name of the Key Vault and the sign button is clicked, the connection would be established.

If you have any issues establishing a successful connection to the Azure Key Vault in your Power Automate cloud flow, refer to the blog post https://ashiqf.com/2021/07/18/azure-key-vault-in-power-automate-cloud-flow-could-not-retrieve-values/

Step 2: Select the certificate name from the list of secrets. Add the HTTP action with the details below

Request Type: GET

URL: https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/calendar/events

Authentication: Active Directory OAuth

  • Tenant: TenantId
  • Audience: https://graph.microsoft.com
  • Client ID: Azure AD Client Id
  • Pfx: Output of the action Get secret from the dynamic content
  • Password: null should be added from the expression right next to dynamic content.

Run the flow, it should work as intended. Refer to my other blog posts related to Microsoft Graph API in Power Automate:

Call Microsoft Graph API as a daemon application with application permission from Power Automate using HTTP connector

Call Microsoft Graph API in Power Apps and Power Automate using a Custom connector

Call Microsoft Graph API as a signed in user with delegated permission in Power Automate or Azure Logic apps using HTTP Connector

Batch SharePoint requests [GET, POST, PATCH, DELETE] in PowerAutomate and MS Graph

Summary:

There are different authorization flows available in Microsoft Graph which could be leveraged based on needs. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I post them.

Handle SharePoint site creation response – The site address is unavailable

There is a possibility to change the SharePoint online site address of an existing site by a SharePoint admin or Global admin. There are different options to change the site URL from

  1. SharePoint Admin center
  2. SharePoint online management shell

I’ve recently faced a scenario recently, after renaming a site URL https://tenant.sharepoint.com/sites/site1 to https://tenant.sharepoint.com/sites/site2 from the Admin center I was still not able to use the url https://tenant.sharepoint.com/sites/site1 while trying to create another site though the url has to be available. I’ve tried to create the site from the SharePoint start page & SharePoint admin center, I was getting one of the following message

  • The site address is unavailable
  • Couldn’t create the site, please go back and try again.

SharePoint Online PowerShell to the rescue, run the following command as an Administrator after creating a site with some address from the start page or admin center to rename the URL

Connect-SPOService -Url https://tenant-admin.sharepoint.com/
Start-SPOSiteRename -Identity https://tenant.sharepoint.com/sites/someaddress -NewSiteUrl https://m365pal.sharepoint.com/sites/site1

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Control your Philips Hue Lights from Microsoft Power Platform and .NET

Philips Hue is a smart lighting solution provider with range of smart lights that can be controlled with your smart devices like your mobile phone, Google Home, Alexa etc through the applications developed by Philips. On top of applications from Philips, the Hue system also enables OAuth 2.0 to allow third party integrations to connect to Hue system resources. In this blog post, let us see how to use the Philips Hue OAuth 2.0 remote API to integrate with the Power Platform for controlling the lights.

Pre-Requisites:

  1. Lights connected to the Hue Bridge. Hue bridge is a device which is the brain of the Philips hue smart lighting system that links the lights to the internet.
  2. Register an account in the Philips Hue Developers portal

The first step is to create a Remote Hue API app which provides you with OAuth credentials to remote control the Hue lights.

Add Remote Hue API App:

After logging in to the Philips Hue Developers Portal, access the URL https://developers.meethue.com/my-apps/ to add the App. Click on the link Add new Remote Hue API app

After entering the App name, Callback URL and the description, click the Submit button. For the callback URL I have provided the Postman browser call back url https://oauth.pstmn.io/v1/browser-callback facilitating OAuth 2.0  token generation from Postman. You can also enter http://localhost/ as the callback url. Find below screenshot of the newly registered Remote Hue API app

Copy the ClientId & ClientSecret which will be required to generate access token for controlling the Hue lights. The next step is to generate the access token.

Access Token Generation:

To access a Philips Hue API endpoint to turn on/off or change colours of light, an access token is required. To generate an access token, the first step is to generate an authorization code. Construct the following URL

GET https://api.meethue.com/oauth2/auth?clientid=<clientid>&appid=<appid>&deviceid=<deviceid>&devicename=<devicename>&state=<state>&response_type=code
  • ClientId: From the app registration.
  • ClientSecret: From the app registration.
  • AppId: From the app registration, the name of the app. Per the above screenshot, it is myremotehueapp
  • DeviceId: The device identifier must be a unique identifier in a string format for the app or device accessing the Hue Remote API.
  • DeviceName: The name of the app accessing the remote api.
  • State: any string

The url should look something like

Access the URL in a browser, you will be prompted to accept or decline the permission grant to the created app.

Once the app is trusted, there will be an authorization code automatically generated on the browser address bar as shown below

Make a note of the code which will be used to generate access token. To Deactivate an existing App or see all the list of existing apps, login to https://account.meethue.com/apps.

To generate an access token using Basic Authentication, make the following HTTP request using Postman or any other tool

Type: POST

URL: https://api.meethue.com/oauth2/token?code= bsysFQ65 &grant_type=authorization_code

Replace the code value with yours generated from the authorization grant request.

Authorization Type: Basic Auth. Username should be ClientId of the App and Password should be ClientSecret

Find below screenshot from Postman with the above HTTP POST request, make a note of the access token and refresh token from the response section of the request.

The Access token is approximately valid for 7 days and the refresh token for 100 days. Let us now see, how to refresh the access token.

Refresh Access token:

The access token is valid only for 7 days, to use it beyond 7 days there must be a new access token generated using the Refresh token. Find below the request details using Basic Authentication

Type: POST

URL: https://api.meethue.com/oauth2/refresh?grant_type=refresh_token

Authorization Type: Basic Auth. Username should be ClientId of the App and Password should be ClientSecret

Headers:

Key: Content-Type

Value: application/x-www-form-urlencoded

Body:

refresh_token=refreshtokenfromthefirstrequest

Find below screenshot of the request

Besides Basic authentication, Hue Remote API supports Digest method. For more details on the remote authentication, go through the documentation https://developers.meethue.com/develop/hue-api/remote-authentication-oauth/

Control the Hue Lights using the generated Access token:

Till now we have seen how to register a remote API app, generate access token and to refresh it before it expires. Let us now see how to use the access token to turn on/off, change colours etc with the remote API endpoints. To enable this experience, there must be a username created first.

User Name Creation:

Find the HTTP request details to enable the Link button

Type: PUT

URL: https://api.meethue.com/bridge/0/config

Body-RAW: { “linkbutton”:true }

Headers:

Content-Type: application/json

Authorization: Bearer access_token

Immediately after the above request, make the following HTTP request to create the User Name

Type: POST

URL: https://api.meethue.com/bridge/

Body-RAW: { “devicetype”: “myremotehueapp” }

The devicetype is the appid or the name of the remote app

Headers:

Content-Type: application/json

Authorization: Bearer access_token

Copy the username from the above request response.

Turn On/Off Hue Lights:

To turn On/Off the light, the first step is to get the Light no you are trying to control. To get the list of lights, make the following request with the user name generated above

Type: GET

URL: https://api.meethue.com/bridge/username/lights/

Replace the username in the URL

Body: None

Headers:

Authorization: Bearer access_token

In the above request response, the light no is 1 which is the first light on my Hue system.

To Turn On/Off:

Find the HTTP request details to turn on/off

Type: PUT

URL: https://api.meethue.com/bridge/{{username}}/lights/{{lightno}}/state

Replace the username & lightno in the URL

Body-Raw: {“on”:true} or {“on”:false}

True for Turning On and False for Turning off

Headers:

Authorization: Bearer access_token

Content-Type: application/json

Set colours of the Hue Light:

The Philips Hue system uses Chromaticity to set the colour of the light. Chromaticity consists of two independent parameters, often specified as hue (h) and colourfulness, where the latter is alternatively called saturation, chroma. Find below diagram which will help you to set the colour of the light

Find below HTTP request details for setting the colour to RED

Type: PUT

URL: https://api.meethue.com/bridge/{{username}}/lights/{{lightno}}/state

Replace the username & lightno in the URL

Body-Raw:

{
"on":true,
        "xy": [
            0.720000,
            0.250000 
        ],
  "bri":100,
  "transitiontime": 0
}

Change the XY values for different colours. To increase/decrease brightness update the bri attribute. With the help of the above diagram, for colour GREEN the XY value is 0.350000, 0.550000

Headers:

Authorization: Bearer access_token

Content-Type: application/json

For information on the Light API, refer to the documentation https://developers.meethue.com/develop/hue-api/lights-api/

Control Lights in Power Platform:

As you have seen above, to control the lights an access token and username is required. Store the information in a SharePoint list which will make it easier to get the Client Id, Client Secret, light no, refresh token etc. Find below the list schema I have created to manage the Light configuration.

Refresh the Access Token:

As the token is valid only for 7 days, create a scheduled Power Automate cloud flow which can run once in 6 days to create a new token using the Refresh token. Refer to the earlier section for the API endpoint details to refresh the token.

  1. After the trigger is added, add the SharePoint connector to get values of the Refresh Token, Client Id, Client Sercret etc
  2. Initialize variables to store the values retrieved from the SharePoint list
  3. Add a Switch control to store the values on the variable.
  1. Add a HTTP action to refresh the token as shown below
  1. Add the JSON parse action to get the new token values including the new Refresh Token. Once the refresh token is used, it cannot be used again.
  1. After getting the new values, update the access token & Refresh token in the SharePoint list.
  2. The package of this cloud flow can be downloaded from here. https://github.com/ashiqf/PowerAutomate/tree/PhilipsHue-RefreshtheAccessToken

Turn On/Off from Power Automate or Power Apps:

To turn on/off or set different colours of the light from Power Automate or Power Apps, create a Flow with HTTP action & call the API given in the above section. To call the flow in Power Apps, use the Power Apps trigger or use a custom connector.

Control Lights from a .Net application:

Find code below to turn on/off light from a .NET application

private static async Task<string> TurnOnPhilipsHue(string accessTokenPhilipsHue, string userNamePhilipsHue, string lightNoPhilipsHue)
{
	string requestUrl = "https://api.meethue.com/bridge/" + userNamePhilipsHue + "/lights/"+ lightNoPhilipsHue + "/state";
	using var client = new HttpClient();

	var payload = "{\"on\": true,\"bri\": 102}";
	client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessTokenPhilipsHue);
	var requestData = new StringContent(payload, Encoding.UTF8, "application/json");
	var response = await client.PutAsync(String.Format(requestUrl), requestData);
	var result = await response.Content.ReadAsStringAsync();
	return result;
}

There is also SDK for C#, do look at it on this url https://developers.meethue.com/develop/tools-and-sdks/ for more details.

Summary:

I have used this light to build a Microsoft Teams status light, will post the link as soon as it is available. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Handle HTTP request failures in Power Automate

If the HTTP request you make in Power Automate cloud flow gets a 200 OK response, all is good but if the HTTP response has the status codes like 408 – Request Timeout, 429 – Too many requests, 522 – Connection Timeout, 404 – Not found, 400 – Bad request etc there is a problem which needs attention. This post will show you how to handle HTTP request failures using

  • Retry Policy
  • Custom Retry for requests which cannot be handled by Retry Policy
  • Take actions based on HTTP status code

Retry Policy:

A Retry Policy specifies how the action or trigger retries a request when the original request times out or fails. The retry policy handles the following HTTP status codes

  1. 408 – Request Timeout
  2. 429 – Too many requests
  3. 5xx – xx refers to any number like 500 – Internal server error, 503 – Service Unavailable, 522 – Connection timed out etc

HTTP Action supports retry policy and by default the action retries 4 times at exponentially increasing intervals if there is a request failure. To view or update the Retry Policy configuration settings for the HTTP action, navigate to settings as shown on below screenshot

If you have to retry the request for more than 4 times or set some custom interval between retries, you can do so by changing the retry policy from Default to Fixed interval or Exponential interval as shown below

Exponential Interval:

The policy waits for a random interval before sending the next request. The random interval is selected from an exponentially growing range.

Fixed Interval:

The policy waits for a specified interval before sending the next request.

There will not be any retry if the policy is set to None. For more details on the retry policies, go through this documentation from Microsoft. Find below screenshot of a Fixed Interval Retry Policy which attempts to make a HTTP request 5 more times after the first failed request with a 10-minute delay between each attempt.

The retry interval accepts value in ISO 8601 format. In the above screenshot for the interval field with value PT10M

P is the duration designator and T is the time designator, where M is the minute designator. PT5S translates to 5 seconds. For testing the policy with the HTTP action you can get sample http request links with different status codes request url’s from https://httpstat.us/.

The retry information will be logged in the flow Run history as shown below

Custom Retry for requests which cannot be handled by Retry Policy:

The retry policy handles only HTTP status codes 408, 429 and 5xx. On this section let us see how to handle the other types of HTTP status codes or non-retry-able errors. Let us take an example with a requirement to retry HTTP request with status code 400 – Bad request till the request succeeds.

Step 1: Initialize a boolean variable ExecuteHTTPAction with the default value true. For the Boolean value use the expression true.

Step 2: Add a Do until control. The loop runs for a maximum of 60 times (Default setting) until the HTTP request succeeds or the condition is met. The Left side placeholder should have the ExecuteHTTPAction variable as a value and the right side should have Boolean variable False. Use Expression to enter the Boolean variable false.

Toggle between Edit in advance mode and Edit in basic mode if the right side placeholder to enter value is disabled.

Step 3: Add the HTTP request action and an action to Set variable ExecuteHTTPAction named as Set Variable – HTTP Action Success. Set the value of the variable to boolean false which means on HTTP action success (200 OK), there should not be any retry.

Step 4: Once the Set variable action is added, just above the action click + and Add a parallel branch as shown in the above picture. On the other side of the branch add an action Set variable named as Set variable – HTTP Action Failure to set the ExecuteHTTPAction variable to true which means there should be retry

Step 5: The last step is to configure Run after for the action Set variable – HTTP Action Failure. Find below screenshot for the Run after configuration

No change is required for Set variable – HTTP Action Success, just ensure the Set variable – HTTP Action Failure has the Run After has failed. You can add a Delay action after the parallel branch to make sure the HTTP request is made after certain interval based on scenario. You can also add scope controls for TRY, RETRY etc.

Alternative Method:

The other way to do this without adding the parallel branch is as shown below

Take actions based on HTTP status code:

If you have to take different actions based on the HTTP status code, for example call a different API when there is an HTTP 404 – Not found etc. The quick way to do this is get the HTTP status code of the HTTP request by adding the Compose action below the HTTP request action and select the Status code from the Dynamic content which is an Output of the action HTTP.

Now configure the run after for the compose action as shown below

The compose action would now be able to capture all type of HTTP status code. With the status code in hand, add a switch control to take different actions based on HTTP status code.

Summary:

On this post we have seen how to handle different HTTP request failures codes with options to Retry in your Power Automate flow. You can apply this technique to handle HTTP request made via custom connector, SharePoint Connector etc.  Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

How to invite external users to a SharePoint site or Microsoft Team using Power Automate and Graph API

SharePoint and Microsoft teams services in Microsoft 365 makes it easier to share content or collaborate with external users who is outside your organization. A guest or external user is someone who do not have a school or work account with your organization, they can be your partner, vendor, customer etc. In this article let us see how to build a self-registration experience for external users with the help of Microsoft Forms & Power Automate to onboard them to a

  • SharePoint online site
  • Microsoft Team

Microsoft Form to collect details from External User:

To start building this experience, create a Microsoft form with the setting Anyone can respond and with fields (Name, Email address etc) to collect information from the external user to send invitation.

Azure Active Directory Application registration:

The next step after creating the form is to register an application in Azure AD with Microsoft graph API permission to send invitation to external user. After the app is registered obtain the client id, client secret & tenant id to be used in the Power Automate flow further down this article to generate the JSON webtoken to access Microsoft Graph API for sending invitation. Find below screenshot with the permission User.Invite.All added to the app. Keep in mind the permission requires Admin consent.

There is also delegated permission available for User.Invite.All.

Onboard External users to a SharePoint online site:

Once the Microsoft form is ready, we can start building the Power Automate flow which can send the email invitation to the external user and for granting access to the SharePoint site. The external sharing features of SharePoint Online enables users in your organization share content with people outside the organization. There is no limit to the number of guests you can invite to SharePoint sites as per this SharePoint online limits documentation. Find below steps to create the Power Automate flow with a custom approval on a Microsoft Team

Power Automate Flow:

Create an Automated flow with the trigger When a new response is submitted with the above form name selected on the dropdown and then add the action Get response details with the Response Id selected from the dynamic content for the trigger to get the form details submitted in the Microsoft form by the external user. Find screenshot below

Adaptive card for Teams Approval:

For the Approval in Microsoft Teams, I have used a custom card created from the Adaptive card designer with elements ColumnSet, TextBlock to display information submitted in the form & action button Approve and Reject to take further action by a Microsoft teams user to proceed with Invitation for the Guest account creation. Find screenshot below from the adaptive card designer

  1. After the card is designed, copy the card payload from the designer and go to the flow and then add the action Post adaptive card and wait for a response and make appropriate selection on the available fields as shown below
    • Post as: Flow bot
    • Post in: Channel
    • Message: Payload copied from designer. Replace the fields for usrName & userEmail selected from the dynamic content from the outputs of the action Get response details. The created on textBlock element has the flow expression formatDateTime(utcNow(),’g’) to display the current datetime information on the card.
  • Update Message: Custom message which appear after an action taken in Microsoft Teams
  • Team: Select the Team where you would like to post the card
  • Channel: Select the channel from the Microsoft Team where you would like to have the approval adaptive card posted

Card payload:

{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "weight": "Bolder",
            "text": "Approval for adding the External User",
            "wrap": true
        },
        {
            "type": "TextBlock",
            "spacing": "None",
            "text": "Created Add flow expression to get current date",
            "isSubtle": true,
            "wrap": true
        },
        {
            "type": "ColumnSet",
            "columns": [
                {
                    "type": "Column",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "Name:",
                            "wrap": true,
                            "size": "Medium",
                            "weight": "Bolder"
                        },
                        {
                            "type": "TextBlock",
                            "text": "Email:",
                            "wrap": true,
                            "weight": "Bolder",
                            "size": "Medium"
                        }
                    ],
                    "width": "stretch"
                },
                {
                    "type": "Column",
                    "width": "stretch",
                    "items": [
                        {
                            "type": "TextBlock",
                            "text": "usrName-Replace it from Microsoft Form",
                            "wrap": true
                        },
                        {
                            "type": "TextBlock",
                            "text": "userEmail-Replace it from Microsoft Form ",
                            "wrap": true
                        }
                    ]
                }
            ]
        }
    ],
    "actions": [
        {
            "type": "Action.Submit",
            "title": "Approve",
            "id": "btnApprove"
        },
        {
            "type": "Action.Submit",
            "title": "Reject",
            "id": "btnReject"
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}
  1. The above adaptive card is used to get approval from the Organization teams user based on the information submitted by the external user in the Microsoft form to proceed with the next steps for sending the guest account invite. Now we will have to identify if the user has clicked the button Approve or Reject. This information can be easily obtained from the Outputs of the action.

Note: Adaptive card can also be sent using a Microsoft Graph API with the card payload in Attachments field

Adaptive card for Teams – Dynamic content Missing:

As of the time I am writing this article there is an issue in getting the output as dynamic content for the Post adaptive card and wait for a response action if there is dynamic content added on the JSON Payload (Name, Email from Forms). The fix is to run the flow till the post adaptive card action and take an action on Microsoft teams by clicking either Approve or Reject and then go to the Flow run from the history as shown below

From the above screenshot, we can see if the user has clicked the Approve or Reject button from the field submitActionId. To get this value in Flow, use the expression

outputs('Post_adaptive_card_and_wait_for_a_response').body.submitActionId

or

@outputs('Post_adaptive_card_and_wait_for_a_response')?['body/submitActionId']

Spaces in the name of the action is replaced with underscore.

To get the userPrincipalName, the expression is

outputs('Post_adaptive_card_and_wait_for_a_response').body.responder.userPrincipalName

or

@outputs('Post_adaptive_card_and_wait_for_a_response')?['body/responder/userPrincipalName']

To get the submitActionId, enter the expression outputs(‘Post_adaptive_card_and_wait_for_a_response’).body.submitActionId in the compose action, then add a condition control to decide action based on users approval

I have observed this issue occurs in other team’s adaptive card actions as well, the above fix should work. Now we can implement the logic to send the Guest Invitation using Microsoft Graph API. To send the invite, we will use the Azure AD application registered above.

Generate JSON Web token to Access Graph API:

Be ready with the ClientId, Client Secret and Tenant Id collected from the AD app registration you have done initially. The only authentication flow to generate a access token for application permissions is Client credentials.

To generate a token

  1. Store the Client Secret on a String variable or a compose action
  2. Make a HTTP request using the HTTP connector with the following details. Make sure to replace the string for tenantId, azureAdAppclientId and azureAdAppclientSecret

Add a HTTP connector action to the flow for making a POST request per the following information

HTTP Method: POST

URI: https://login.microsoftonline.com/yourtenantId/oauth2/v2.0/token

Headers: Content-Type: application/x-www-form-urlencoded

Body:

tenant=yourtenantId&client_id=azureAdAppclientId&client_secret=@{decodeUriComponent(variables('azureAdAppclientSecret'))}&grant_type=client_credentials&scope=https://graph.microsoft.com/.default

For the client secret make sure to URL encode using the expression encodeUriComponent(variables(‘clientSecret’)) else the request may fail due to the presence of special characters.

In the above screen, I have added a compose action to store the SharePoint site address to be used for granting the external user access to. To extract the token from the above request, add the parse JSON action with Content from the HTTP request body and the following schema

{
    "type": "object",
    "properties": {
        "token_type": {
            "type": "string"
        },
        "scope": {
            "type": "string"
        },
        "expires_in": {
            "type": "integer"
        },
        "ext_expires_in": {
            "type": "integer"
        },
        "access_token": {
            "type": "string"
        },
        "refresh_token": {
            "type": "string"
        }
    }
}

Include the access token when calling the Microsoft Graph API in the Headers section or raw as shown in the next section.

Send Invitation using Microsoft Graph API:

Before sending the invitation, validate if the user already exists in your organization AD tenant by using the email address of the external user with the help of the action Search for users as shown below

If there is null response for the action Search for users, then the user does not exist. This can be calculated using the expression length and by passing the value as a parameter, if it is equals zero then the external user does not exist. If the user already exists, we can directly proceed to granting the external user access to SharePoint.

Graph API to check if a guest user already exists:

https://graph.microsoft.com/v1.0/users?$filter=UserType eq ‘Guest’&$filter=mail eq exteruseremailaddress@domain.com’

or

https://graph.microsoft.com/v1.0/users?$filter=startswith(mail,’exteruseremailaddress@domain.com’)

Find below the Graph API endpoint http request details to invite the external user

Method: POST

URL: https://graph.microsoft.com/v1.0/invitations

Request Body:

{
  "invitedUserDisplayName": "External User Name",
  "invitedUserEmailAddress": "External User Email Address",
  "sendInvitationMessage": true,
  "inviteRedirectUrl": "SharePoint site URL or any URL",
  "invitedUserMessageInfo": {
    "messageLanguage": "en-US",
    "customizedMessageBody": "Welcome to the M365PAL SharePoint site! Click the link below and sign in."
  }
}

In HTTP request body, use the dynamic content of the form to populate the fields invitedUserDisplayName & Emailaddress. The invite redirectUri is the output of the compose action which has the SharePoint site url. I have added a delay of one minute before granting access to SharePoint site for the external user, this step is to make sure there is an entry in Azure AD for the external user/guest account.

Custom connector can be used for calling the Graph API for sending invitations instead of using HTTP connector, you can refer to the post Call Microsoft Graph API in Power Apps and Power Automate using a Custom connector for detailed instructions.

Grant Access to SharePoint site for the external user:

As soon as the guest account invite is sent from the above Microsoft graph API request HTTP action, it is time to grant access to the SharePoint site for the external user. There is a SharePoint REST API endpoint to add a user to a SharePoint group (Owners, Member, Visitors), find below the request details

Request URL: https://tenantname.sharepoint.com/sites/siteName/ _api/web/sitegroups/GetById(groupId)/users

For the groupId to the corresponding SharePoint group, refer to the following table

SharePoint GroupGroupId
Owners3
Members5
Visitors4

Headers:

Key: accept value: application/json;odata.metadata=none

Key: content-type value: application/json

Body:

{'LoginName':'i:0#.f|membership|userPrinipalNameorEmailaddressofExternalUser'}

For the external user, the email address used to send the invite works.

Go back to the flow and add the action Send an HTTP request to SharePoint to call the above REST api. Find below the screenshot of the action

The above action uses delegated permission, the user of the connection should have access to the SharePoint site. As of now, there is no Graph API for adding the user to a SharePoint group but you can register an app in Active directory and add permission for SharePoint to call the above REST API. Refer to the documentation Granting access via Azure AD App-Only for calling the REST API using the registered AD app.

Testing the flow:

The whole flow can now be tested by submitting the form which sends the adaptive card on Teams first as shown below

After the card is approved, the invite is sent to the external user. After the external user accepts the invite, the user should be automatically redirected to the SharePoint site with the appropriate access. The access to the SharePoint site for the external user can be validated by the checking the membership of the SharePoint group in the site even before the user accepts the invitation. The site members can also be validated by accessing the URL for All users list:

https://tenantName.sharepoint.com/sites/siteName/_layouts/15/people.aspx?MembershipGroupId=0

This approach of granting access to SharePoint site for external user can be applied to internal users by turning off the access requests.

Limit External Sharing by domain:

The external sharing on SharePoint can be restricted based on domain of the external user. To enable the setting login into the SharePoint admin center > Policies > Sharing > Enable the checkbox Limit external sharing by domain > Add domain

Onboard External users to a Microsoft Team:

To onboard the external user to a Microsoft Team, the only change to the above flow is, instead of adding the user to the SharePoint group the user must be added as a Member to the Microsoft 365 group connected to the Microsoft Teams. The graph API to add a member to a Microsoft Team is

Request Type: POST

Request URL: https://graph.microsoft.com/v1.0/teams/{team-id}/members

The team-id is the Microsoft 365 group object Id, as there is always a Microsoft 365 group connected to a Microsoft Team.

Body:

{
    "@odata.type": "#microsoft.graph.aadUserConversationMember",
    "roles": ["owner"],
    "user@odata.bind": "https://graph.microsoft.com/v1.0/users(userObjectIdofGuest')"
}

The expression to get the user object Id of the external user as per the below screenshot is

outputs(‘HTTP-SendGuestInvitation’).body.invitedUser.Id The expression can be used in a compose action to get the Object Id of the external user which can be used in the Graph API request to add the member to a Team. HTTP-SendGuestInvitation is the name of the HTTP Action.

Permission for the Azure AD App to add a member to a Microsoft Team:

The application permission Group.ReadWrite.All has to be added on the Azure AD app, if you are going to be using the same JSON webtoken generated above. There is delegated permission as well for adding members.

https://graph.microsoft.com/Group.ReadWrite.All

I recommend you read the following documentation from Microsoft for External sharing

https://docs.microsoft.com/en-us/microsoftteams/manage-external-access

https://docs.microsoft.com/en-us/microsoftteams/guest-access

https://docs.microsoft.com/en-us/microsoftteams/communicate-with-users-from-other-organizations

https://docs.microsoft.com/en-us/microsoft-365/community/managing-external-guest-in-sharepoint-vs-teams

Summary: With this, the Power Automate flow should send the invitation as shown below to the external user.

If it is for a Microsoft Team, the external user should be licensed for teams service to open it on their teams client. The same flow can be also configured for Microsoft 365 group. If you are visiting my blog for the first time, please do look at my other blogposts.