Call authenticated external APIs using JavaScript from Power Pages

If you need to call external APIs using JavaScript from Power Pages, you may want to secure the calls to avoid exposing information or application hacking, as all the calls are made from client side.

Power Pages sites can have OAuth 2.0 implicit grant flow enabled, so you can obtain an authentication token that has your Portal as the issuer, and you can use this token to do authenticated calls to external APIs.

This post is a quick overview and summary of useful posts in the subject, as there are some good content around, I thought it would be useful to collate the links in a single place.

This Microsoft tutorial explains how to enable the OAuth 2.0 implicit flow in your site:

Use OAuth 2.0 implicit grant flow within your Power Pages site

Use the token in JavaScript

After enabling OAuth 2.0 implicit flow, you can obtain a token by calling the following endpoint and then use it to call the authenticated API:

<portal_url>/_services/auth/token

Sample JavaScript code to wrap obtaining the token in a function:

var GetToken = function() {
     return $.post("/_services/auth/token", { "client_id":"<Your Registered Client Id>"});
}

You could then do an API call using the token as in this example in a WebFile/WebTemplate/WebPage:

 GetToken().then(
        function (token) {
//some object you want to send as data to the post request
            let postData = {
                "title": "something"
            };
            $.ajax({
                url: yourApiUrl,
                type: 'POST',
                contentType: 'application/json',
                headers: {
                    'Authorization': "Bearer " + token
                },
                data: JSON.stringify(postData),
                dataType: 'json',
                success: function (result) {
                    console.log(result);
                }
                ,
                error: function (err) {
                    console.log(err);
                }
            });
        }
    )

Validate the token in the destination api

You can validate the token from Portals directly in the API as in this C# example:

https://github.com/microsoft/PowerApps-Samples/tree/master/portals/ExternalWebApiConsumingPortalOAuthTokenSample

For higher security, you can also validate it from Azure APIM directly and have more usage restrictions in case you will be calling your API from APIM, as in this blog post series:

Hope this post helps you getting started.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *