-
Notifications
You must be signed in to change notification settings - Fork 232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
OneDrive FilePicker Multitenant Instructions are still unclear #1858
Comments
I don't know if these issues are still being reviewed, but for the benefit of others, documenting here how I eventually got both consumer and multitenant business accounts working. For what it's worth, there were two issues that I literally spent many hours trying to figure out the right configuration to get things working, and I think it would be well worth it to more clearly and explicitly document the solutions to these issues in the OneDrive Picker doc. These 2 issues were:
For the first issue, note that for clarification I wanted to implement something very similar to what ChatGPT recently added to their website: the ability to connect a OneDrive account (either a consumer or a business account) and open the Picker to select files that can then be uploaded to the app (in that case ChatGPT). The thing I find honestly unhelpful about the docs and examples is how it specifies the All that said, here are the major things I had to do differently between consumer accounts and multitenant accounts to get everything working.
In the consumer case: const pickerBaseUrl = "https://onedrive.live.com/picker"; // this is static, doesn't change for the consumer case
const pickerConfig = {
sdk: "8.0",
entry: {
sharePoint: {
byPath: { list: "https://onedrive.live.com" }, // this is also static and doesn't change
},
},
authentication: {},
messaging: {
origin: window.location.origin,
channelId = "...", // set the channel ID to some unique value, e.g. a uuid
},
// for my purposes I wanted to allow multiple file selection
typesAndSources: { mode: "files" },
selection: { mode: "multiple" },
search: { enabled: true },
}; That is, for the consumer case, the In the multitenant business account case, things become more complicated because after the user first logs in through OAuth, we need to query the API to get the values. There are no examples of this in the doc, and only one small FAQ at https://github.com/OneDrive/samples/tree/master/samples/file-picking#faq that was helpful: const token = ...; // get a token e.g. as described above and in the examples
// need to determine the user's main OneDrive URL:
const usersMainDriveResponse = await fetch(
"https://graph.microsoft.com/v1.0/me/drive",
{
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
},
);
const usersMainDriveWebUrlString = (await usersMainDriveResponse.json())
.webUrl;
// now we have the info for this user's pickerBaseUrl and pickerConfig.entry.sharePoint.byPath.list values
const pickerBaseUrl = `${new URL(usersMainDriveWebUrlString).origin}/_layouts/15/FilePicker.aspx`;
const pickerConfig = {
sdk: "8.0",
entry: {
sharePoint: {
byPath: { list: usersMainDriveWebUrlString },
},
},
authentication: {},
messaging: {
origin: window.location.origin,
channelId = "...", // set the channel ID to some unique value, e.g. a uuid
},
// for my purposes I wanted to allow multiple file selection
typesAndSources: { mode: "files" },
selection: { mode: "multiple" },
search: { enabled: true },
}; Again, I hope the above is useful for someone else. To Microsoft folks, I would strongly suggest adding an explicit example for the multitenant case. Even better, I think it would be much better to wrap the Picker control as a JS object - there is much too much manual setup (e.g. setting up the communication port between windows) IMO for what should be a client API. I'll doc the steps for the download-in-javascript case in a subsequent comment. |
In order to download picked files from javascript (that is, when responding to the "pick" message, and note the for (const pickedItem of message.data.data.items) {
// to first get more detailed info about the picked item, including the mime type of the file
const fileInfoUrl = `${pickedItem["@sharePoint.endpoint"]}/drives/${pickedItem.parentReference.driveId}/items/${pickedItem.id}`;
const infoResponse = await fetch(fileInfoUrl, {
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
const fileInfo = await infoResponse.json();
// now you can download the file contents at the /content url
const downloadUrl = `${fileInfoUrl}/content`;
const downloadResponse = await fetch(downloadUrl, {
method: "GET",
headers: { Authorization: `Bearer ${token}` },
});
const bodyContents = await downloadResponse.arrayBuffer();
const downloadedFile = new File([bodyContents], fileInfo.name, { type: fileInfo.file.mimeType });
// TODO - do something with the downloadedFile
} |
@adevine The documentation in this issue has saved me MANY hours. Honestly thank you so much. and I completely second this statement:
|
@adevine Thanks for much for this awesome explanation! I'm still running into some issues though, would you be able to give a full example? |
I also encountered murky documentation from MS. This is how I solved the picker issues when integrating with personal and multi-tenant org users. It is for documentation purposes. Thanks to @adevine for pointing me in the right direction. I solved this issue by seeing the implementation done by ChatGPT. Steps I did1. Registering the App
2. Integrating the picker into our application
import {
BrowserCacheLocation,
PublicClientApplication,
} from "@azure/msal-browser";
import { MsalProvider } from "@azure/msal-react";
/**
* @type {import("@azure/msal-browser").Configuration} MSAL configuration
* Refer https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md for more info
*/
const configuration = {
auth: {
clientId: <insert client id>,
},
cache: {
cacheLocation: BrowserCacheLocation.MemoryStorage,
storeAuthStateInCookie: true,
secureCookies: import.meta.env.PROD,
},
system: {
windowHashTimeout: 9000, // Applies just to popup calls - In milliseconds
iframeHashTimeout: 9000, // Applies just to silent calls - In milliseconds
loadFrameTimeout: 9000, // Applies to both silent and popup calls - In milliseconds
},
};
const pca = new PublicClientApplication(configuration);
export default function MSALProvider({ children }) {
return <MsalProvider instance={pca}>{children}</MsalProvider>;
}
const { instance, accounts } = useMsal(); // This is for getting the Instance of MSAL and accounts that are signed in.
// For personal accounts this will always be the tid. Refer https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference
function checkPersonalAccount({ idTokenClaims: { tid } }) {
return tid === "9188040d-6c67-4c5b-b112-36a304b66dad";
}
function checkOrgAccount({ idTokenClaims: { tid } }) {
return tid !== "9188040d-6c67-4c5b-b112-36a304b66dad";
}
const personalAccount = accounts.find(checkPersonalAccount);
const orgAccount = accounts.find(checkOrgAccount);
// Now we can ask for login if the account doesn't exist
// This should be handled in a button event :).
if(personalAccount == null){
const url = window.location.origin;
instance.loginPopup({
redirectUri: `${url}`,
scopes: oneDriveOrgScopes, // This scopes and authority will be explained below.
authority: msalOrgAuthority,
});
}else{
// Later points
}
/**
* Combines an arbitrary set of paths ensuring and normalising the slashes
* This is used for getting scopes based on the resource type in Onedrive Picker
* @param paths 0 to n path parts to combine
*/
export function combine(...paths) {
return paths
.map((path) => path.replace(/^[\\|/]/, "").replace(/[\\|/]$/, ""))
.join("/")
.replace(/\\/g, "/");
}
/**
*
* @param {Object} Properties
* @param {import("@azure/msal-browser").IPublicClientApplication} Properties.instance MSAL Instance to use
* @param {string[]} Properties.scopes Scopes to ask for in the token. This is overridden when type and resource are passed
* @param {import("@azure/msal-browser").AccountInfo} Properties.currentUser User Account to get the access token for
* @param {string} Properties.Authority URL to use for OAuth
* @param {string | undefined} Properties.type Which Type of Resource to fetch from, this is only used in the onedrive file picker event listener. This will be used to get access tokens according to the resource
* @param {string | undefined} Properties.resource Which Resource to scope for, this is only used in the one drive file picker event listener.
* @returns {Promise<string>} Access Token for the particular scope
*/
export async function getOneDriveAccessToken({
currentUser,
instance,
scopes,
authority,
type,
resource,
}) {
let accessToken = "";
let currentScopes = scopes;
switch (type) {
case "SharePoint":
case "SharePoint_SelfIssued":
currentScopes = [`${combine(resource, ".default")}`];
break;
default:
break;
}
try {
// See if we have already the id token saved
const resp = await instance.acquireTokenSilent({
scopes: currentScopes,
authority,
account: currentUser,
});
accessToken = resp.accessToken;
} catch (e) {
if (e instanceof InteractionRequiredAuthError) {
return instance.acquireTokenPopup({
scopes: currentScopes,
authority,
account: currentUser,
});
} else {
throw e;
}
}
return accessToken;
}
/**
* Entry is left blank because it is based on whether the user is org-based or personal.
* Refer https://learn.microsoft.com/en-us/onedrive/developer/controls/file-pickers/v8-schema
*/
export const oneDrivePickerOptions = {
sdk: "8.0",
entry: {},
authentication: {},
messaging: {
origin: window.location.origin,
channelId: crypto.randomUUID(), // This is like a state that only the host and this picker can able to used, other people can't intercept it.
},
typesAndSources: {
mode: "files",
filter: ["photo", "document"],
pivots: {
oneDrive: true,
recent: true,
myOrganization: true,
},
},
search: {
enabled: true,
},
selection: {
mode: "multiple",
enablePersistence: true,
},
};
if(personalAccount != null){
//
}else{
const oneDriveWindow = window.open(
"",
"Picker",
"width=1080,height=680"
);
const accessToken = await getOneDriveAccessToken({
instance,
currentUser: personalAccount,
authority: msalConsumerAuthority,
scopes: oneDriveConsumerScopes,
});
const queryString = new URLSearchParams({
filePicker: JSON.stringify({
...oneDrivePickerOptions,
entry: { // See the entry difference for org
oneDrive: {
files: {},
},
},
}),
locale: "en-us",
});
// We can use this URL for getting personal account files
const oneDriveConsumerBaseUrl = "https://onedrive.live.com/picker";
const url = `${oneDriveConsumerBaseUrl}?${queryString}`;
const form = oneDriveWindow.document.createElement("form");
//Set the action of the form to the URL defined above
// This will include the query string options for the picker.
form.setAttribute("action", url);
// must be a post request
form.setAttribute("method", "POST");
oneDriveWindow.document.body.append(form);
// Create a hidden input element to send the OAuth token to the Picker.
// This is optional when using a popup window but required when using an iframe.
const tokenInput =
oneDriveWindow.document.createElement("input");
tokenInput.setAttribute("type", "hidden");
tokenInput.setAttribute("name", "access_token");
tokenInput.setAttribute("value", accessToken);
form.appendChild(tokenInput);
//Submit the form, this will load the picker page
form.submit();
window.addEventListener("message", (event) => {
if (event.source && event.source === oneDriveWindow) {
const message = event.data;
if (
message.type === "initialize" &&
message.channelId ===
oneDrivePickerOptions.messaging.channelId
) {
const port = event.ports[0];
port.addEventListener(
"message",
onedrivePortEventListener({ // This will be explained below.
port,
oneDriveWindow,
type: "personal",
})
);
port.start();
port.postMessage({
type: "activate",
});
}
}
});
} For Org if (orgAccount != null) {
const oneDriveWindow = window.open(
"",
"Picker",
"width=1080,height=680"
);
const accessToken = await getOneDriveAccessToken({
instance,
currentUser: orgAccount,
scopes: oneDriveOrgScopes,
authority: msalOrgAuthority,
});
// This is to get the org drive URL, Since this is not a personal account
const {
data: { webUrl },
} = await axios.get(
"https://graph.microsoft.com/v1.0/me/drive",
{
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
withCredentials: false,
}
);
const queryString = new URLSearchParams({
filePicker: JSON.stringify({
...oneDrivePickerOptions,
entry: { // See the entry point differnce for org
sharePoint: {
byPath: { list: webUrl },
},
},
site: {},
}),
locale: "en-us",
});
const url = `${new URL(webUrl).origin}/_layouts/15/FilePicker.aspx?${queryString}`;
// Same form methods as above
window.addEventListener("message", (event) => {
if (event.source && event.source === oneDriveWindow) {
const message = event.data;
if (
message.type === "initialize" &&
message.channelId ===
oneDrivePickerOptions.messaging.channelId
) {
const port = event.ports[0];
port.addEventListener(
"message",
onedrivePortEventListener({
port,
oneDriveWindow,
type: "org",
})
);
port.start();
port.postMessage({
type: "activate",
});
}
}
});
/**
* Listens to Events sent by the one drive window
* @param {{port:WindowProxy,oneDriveWindow:Window, type:"personal"|"org"}} param0
*/
const onedrivePortEventListener =
({ port, oneDriveWindow, type }) =>
async (message) => {
switch (message.data.type) {
case "notification":
break;
case "command": {
port.postMessage({
type: "acknowledge",
id: message.data.id,
});
const {
command,
items, // This is the files picked from the picker
type: commandType,
resource,
} = message.data.data;
// This is the place, Where the documentation missed out on a key detail but it will be used in their sample codes. They don't explain why it is needed.
const tokenOptions =
type === "personal"
? {
scopes: oneDriveConsumerScopes,
authority: msalConsumerAuthority,
currentUser: personalAccount,
instance,
}
: {
scopes: oneDriveOrgScopes,
authority: msalOrgAuthority,
currentUser: orgAccount,
instance,
type: commandType, // In the getOneDriveAccessToken, you would have seen one switch statement based on type. For tenant users we can't use the same resource rather the picker emits this resource and their access type for that we have to get an access token.
resource,
};
switch (command) {
case "authenticate": {
// Based on the token options above, we can send the token to the picker
const token =
await getOneDriveAccessToken(tokenOptions);
if (token != null) {
port.postMessage({
type: "result",
id: message.data.id,
data: {
result: "token",
token,
},
});
} else {
enqueueSnackbar(
`Could not get auth token for command: ${command}`,
{
variant: "error",
}
);
}
break;
}
case "close":
oneDriveWindow.close();
break;
case "pick": {
// You can use the items from message.data.data and get the files picked by the users.
port.postMessage({
type: "result",
id: message.data.id,
data: {
result: "success",
},
});
oneDriveWindow.close();
break;
}
default:
enqueueSnackbar(`Unsupported command: ${command}`, {
variant: "warning",
});
port.postMessage({
result: "error",
error: {
code: "unsupportedCommand",
message: command,
},
isExpected: true,
});
break;
}
break;
}
default:
break;
}
};
/**
* Get Onedrive Download URL
* @param {{parentReference:{driveId:string},id:string,"@sharePoint.endpoint"?:string}} Object you get from message.data.data.items that is emitted by the picker
* @param {string} accessToken
* @param {"org" | "personal"} type
* @returns {Promise<string>} Download URL
*/
export async function getOnedriveDownloadUrlFromPickerObject(
pickerObj,
accessToken,
type
) {
const {
parentReference: { driveId },
id,
} = pickerObj;
if (type === "org") {
const { data } = await axios.get(
`https://graph.microsoft.com/v1.0/drives/${driveId}/items/${id}`,
{
withCredentials: false,
headers: {
Authorization: "Bearer " + accessToken,
},
}
);
return data["@microsoft.graph.downloadUrl"];
} else {
const { data } = await axios.get(
pickerObj["@sharePoint.endpoint"] +
"/drives/" +
driveId +
"/items/" +
id,
{
withCredentials: false,
headers: {
Authorization: "Bearer " + accessToken,
},
}
);
return data["@content.downloadUrl"];
}
} Final NotesBased on this you can have two buttons to use for picker so that the user can either use a personal account or an org account. Instead of signing in with only a single account. If you don't want to use two account logins, you can use the |
Category
There are a couple of issues around multitenant support for the FilePicker control (#1636 and #1684) that are unfortunately closed, but with no actual good solutions. This seems to be a common problem because there are similar unanswered questions online at https://learn.microsoft.com/en-us/answers/questions/1165692/multi-tenant-setup-for-sharepoint-v8-for-filepicke and https://techcommunity.microsoft.com/t5/onedrive-developer/base-url-used-for-multi-tenants/m-p/3792211.
The overview of what I'm trying to do is the same as listed in those linked issues and comments: I would like to provide a control where people can pull down files from their OneDrive accounts (both personal and business) and then upload them to my application. As a working example of this, I essentially want to do exactly what ChatGPT recently added with their "Connect to Microsoft OneDrive" file upload feature.
I understand how to set up multitenant in the Azure portal in the AAD registration ("Supported account types" is "Accounts in any organizational directory (Any Microsoft Entra ID tenant - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)"). The problem is that the FilePicker requires a
baseUrl
before I know what the user's tenant is going to be - this feels like a catch 22 to me. Here is the relevant section from the doc in the Initiate the Picker section:What I don't understand at all is what I should set that
baseUrl
value to if I wish to allow any user to authenticate with their OneDrive/Sharepoint account. I think it would really, really help cut down on confusion if the doc just outlined the following cases:Thanks for your assistance.
The text was updated successfully, but these errors were encountered: