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:
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:
- Steps to set up APIM: https://psempruch.medium.com/powerapps-portals-and-external-api-integration-a-must-know-for-powerplatform-developer-6e177f8ba110
- How to validate the token in APIM/properly authorize & secure the calls: https://psempruch.medium.com/authorizing-powerapps-portal-calls-with-azure-api-management-8880c0bbd64d
Hope this post helps you getting started.
[…] Call authenticated external APIs using JavaScript from Power Pages […]