I'm successfully communicating with the PowerPages API from a Vue SPA hosted on a StaticWebApp (after having set the expected CORS config).
Now as you can guess I need to do PATCH & POST requests so I need the kind of CSRF token that is managed in the officially suggested safeAjax snippet.
I'm using Axios for my requests and not using jQuery (anymore for years now).
How can I satisfy this CSRF protection without jQuery and shell ?
Here is my attempt of porting safeAjax to vanilla JS, but it still requires the global shell & validateLoginSession()
safeAjax(config) {
return new Promise((resolve, reject) => {
shell.getTokenDeferred()
.then(token => {
if (!config.headers) config.headers = {}
config.headers.__RequestVerificationToken = token
fetch(config)
.then(resolve)
.then(response => {
const xhr = new XMLHttpRequest();
xhr.status = response.status;
xhr.statusText = response.statusText;
xhr.responseURL = response.config.url;
xhr.response = response.data;
xhr.readyState = 4;
validateLoginSession(response.data, response.status, xhr, resolve)
})
.catch(error => {
return reject(error)
})
})
.catch(error => {
return reject(error)
})
})
}
First, I did need to use PowerPages API and not Dataverse directly because I need to security layer of PP.
Though after a bit of reverse engineering, I've actually been able to implement both getTokenDeferred() that is simply getting the CSRF token from the publicly available /_layout/tokenhtml route and validateLoginSession() which redirects the user to the login in case of specific error returned by the API.
So we can easily get this token and inject it as the expected header, but after that, all non GET requests don't pass the preflight OPTIONS saying:
Access to XMLHttpRequest at '<PowerPagesAPI URI>' from origin '<StaticWebApp URL>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status
My current CORS settings on PowerPages are the following:
Am I missing something ? Or can't we just do it ? Which would be odd since we can already read any data from there. And in that case I wouldn't understand the use of these CORS settings.
Correct. Power Pages Web API is designed to be only used inside the portal and not for integration purposes or external services. For that, you can use Dataverse API (either via Web API or SDK).
You mean I can't even use a bit of liquid injecting the token into a Power page that I would request ?
Hi @Glide ,
You can fully omit jQuery and use vanilla JS inside Power Pages to communicate with Web API. However, there is no way to get a token without the shell as it is provided and managed by Power Pages.