connecting oneDrive file picker v8 using JavaScript
Sahir Khan
10
Reputation points
i am trying to connect OneDrive for my client on website where they can use their OneDrive to select files to upload.
oneDrive file picker connected successfully but showing empty picker like this
when i check console there are some errors showing
Error: Resource #285 "provider.instrumentation" is being consumed, but is not available in the current scope.
1) Check to ensure that the dependency on this resource (and each step up the chain) is properly declared.
2) If availability is expected, check to see if the target resource has a dependency that is only available in a child scope. Consumed directly.
here is my Manifest
{
"id": "e8228c9a-c27**********15ec255",
"acceptMappedClaims": null,
"accessTokenAcceptedVersion": 2,
"addIns": [],
"allowPublicClient": null,
"appId": "731db10********fd9e801356",
"appRoles": [],
"oauth2AllowUrlPathMatching": false,
"createdDateTime": "2024-01-29T10:38:51Z",
"description": null,
"certification": null,
"disabledByMicrosoftStatus": null,
"groupMembershipClaims": null,
"identifierUris": [],
"informationalUrls": {
"termsOfService": null,
"support": null,
"privacy": null,
"marketing": null
},
"keyCredentials": [],
"knownClientApplications": [],
"logoUrl": null,
"logoutUrl": "https://nazimism360.com",
"name": "Dap360 - OneDrive Access",
"notes": null,
"oauth2AllowIdTokenImplicitFlow": true,
"oauth2AllowImplicitFlow": true,
"oauth2Permissions": [],
"oauth2RequirePostResponse": false,
"optionalClaims": {
"idToken": [],
"accessToken": [],
"saml2Token": []
},
"orgRestrictions": [],
"parentalControlSettings": {
"countriesBlockedForMinors": [],
"legalAgeGroupRule": "Allow"
},
"passwordCredentials": [],
"preAuthorizedApplications": [],
"publisherDomain": null,
"replyUrlsWithType": [
{
"url": "https://nazimism360.com",
"type": "Spa"
}
],
"requiredResourceAccess": [
{
"resourceAppId": "00000003-0000-0000-c000-000000000000",
"resourceAccess": [
{
"id": "06da0dbc-49e2-44d2-8312-53f166ab848a",
"type": "Scope"
},
{
"id": "64a6cdd6-aab1-4aaf-94b8-3cc8405e90d0",
"type": "Scope"
},
{
"id": "10465720-29dd-4523-a11a-6a75c743c9d9",
"type": "Scope"
},
{
"id": "df85f4d6-205c-4ac5-a5ea-6bf408dba283",
"type": "Scope"
},
{
"id": "7427e0e9-2fba-42fe-b0c0-848c9e6a8182",
"type": "Scope"
},
{
"id": "37f7f235-527c-4136-accd-4a02d197296e",
"type": "Scope"
},
{
"id": "14dad69e-099b-42c9-810b-d002981feec1",
"type": "Scope"
},
{
"id": "205e70e5-aba6-4c52-a976-6d2d46c48043",
"type": "Scope"
},
{
"id": "e1fe6dd8-ba31-4d61-89e7-88639da4683d",
"type": "Scope"
}
]
}
],
"samlMetadataUrl": null,
"signInUrl": null,
"signInAudience": "AzureADandPersonalMicrosoftAccount",
"tags": [],
"tokenEncryptionKeyId": null
}
here is my JavaScript code
< script type = "text/javascript"
src = "https://alcdn.msauth.net/browser/2.19.0/js/msal-browser.min.js" > < /script> <
script src = "{{asset('js/one-drive-auth.js')}}" > < /script> <
script >
function combine(...paths) {
return paths
.map(path => path.replace(/^[\\|/]/, "").replace(/[\\|/]$/, ""))
.join("/")
.replace(/\\/g, "/");
}
const baseUrl = "https://onedrive.live.com/picker";
// the options we pass to the picker page through the querystring
const params = {
sdk: "8.0",
entry: {
oneDrive: {
files: {},
}
},
authentication: {},
messaging: {
origin: "https://nazimism360.com/",
channelId: "27"
},
typesAndSources: {
mode: "files",
pivots: {
oneDrive: true,
recent: true,
},
},
};
let win = null;
let port = null;
async function launchPicker(e) {
e.preventDefault();
win = window.open("", "Picker", "width=800,height=600")
const authToken = await getToken();
const queryString = new URLSearchParams({
filePicker: JSON.stringify(params)
});
const url = `${baseUrl}?${queryString}`;
const form = win.document.createElement("form");
form.setAttribute("action", url);
form.setAttribute("method", "POST");
win.document.body.append(form);
const input = win.document.createElement("input");
input.setAttribute("type", "hidden")
input.setAttribute("name", "access_token");
input.setAttribute("value", authToken);
form.appendChild(input);
form.submit();
window.addEventListener("message", (event) => {
if (event.source && event.source === win) {
const message = event.data;
if (message.type === "initialize" && message.channelId === params.messaging.channelId) {
port = event.ports[0];
port.addEventListener("message", messageListener);
port.start();
port.postMessage({
type: "activate",
});
}
}
});
}
async function messageListener(message) {
switch (message.data.type) {
case "notification":
console.log(`notification: ${message.data}`);
break;
case "command":
port.postMessage({
type: "acknowledge",
id: message.data.id,
});
const command = message.data.data;
switch (command.command) {
case "authenticate":
// getToken is from scripts/auth.js
const token = await getToken();
if (typeof token !== "undefined" && token !== null) {
port.postMessage({
type: "result",
id: message.data.id,
data: {
result: "token",
token,
}
});
} else {
console.error(`Could not get auth token for command: ${JSON.stringify(command)}`);
}
break;
case "close":
win.close();
break;
case "pick":
console.log(`Picked: ${JSON.stringify(command)}`);
document.getElementById("pickedFiles").innerHTML = `<pre>${JSON.stringify(command, null, 2)}</pre>`;
port.postMessage({
type: "result",
id: message.data.id,
data: {
result: "success",
},
});
win.close();
break;
default:
console.warn(`Unsupported command: ${JSON.stringify(command)}`, 2);
port.postMessage({
result: "error",
error: {
code: "unsupportedCommand",
message: command.command
},
isExpected: true,
});
break;
}
break;
}
}
document.getElementById("onedrive-picker").onclick = launchPicker;
<
/script>
and this is auth.js code
const dynamicKey = getQueryParam('key');
const msalParams = {
auth: {
authority: "https://login.microsoftonline.com/consumers",
clientId: "731db103-6e22-4d74-9f8f-d9fd9e801356",
redirectUri: "https://nazimism360.com"
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: true,
},
}
const app = new msal.PublicClientApplication(msalParams);
async function getToken() {
let accessToken = "";
authParams = {
scopes: [`${combine(`https://graph.microsoft.com/`, ".default")}`]
};
try {
// see if we have already the idtoken saved
const resp = await app.acquireTokenSilent(authParams);
accessToken = resp.accessToken;
} catch (e) {
// per examples we fall back to popup
const resp = await app.loginPopup(authParams);
app.setActiveAccount(resp.account);
if (resp.idToken) {
const resp2 = await app.acquireTokenSilent(authParams);
accessToken = resp2.accessToken;
}
}
return accessToken;
}
Sign in to answer