Skip to content

Instantly share code, notes, and snippets.

@phillipharding
Last active July 8, 2023 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipharding/93a172f84b8ad426e05f12523c008b90 to your computer and use it in GitHub Desktop.
Save phillipharding/93a172f84b8ad426e05f12523c008b90 to your computer and use it in GitHub Desktop.
Use SPFx to get a Delegated Access Token for a Resource to Pass onto Azure Functions

Use SPFx to get a Delegated Access Token

Note the tokenAcquisitionEvent part of the code doesn't seem to work

Using this technique you can acquire a delegated access token for a resource, SharePoint or the Graph API, and pass that token onto a HTTP triggered Azure Functions endpoint for it to use to call the appropriate API.

This is a simple re-imagination of the on-behalf-of flow involving a secured Azure Functions endpoint then executing an OAuth on-behalf-of flow to exchange the received access token for one which can be used to call an API on behalf of the calling user.

Documented originally by Paolo Pialorsi and Joel Rodrigues

const tokenEventHandler = useCallback((e: SPEventArgs) => {
	console.debug(`PersonnelDirectory.useEffect([])::> provider.tokenAcquisitionEvent <:: `, e);
}, []);

...

useEffect(() => {
	console.debug(`useEffect([])::> tenantId: ${props.context.pageContext.aadInfo.tenantId.toString()}`);
	( async () => {
		try {
			const provider = await props.context.aadTokenProviderFactory.getTokenProvider();
			console.debug(`provider.getTokenProvider() <:: `, provider);
			provider.tokenAcquisitionEvent.add({
				instanceId: props.context.instanceId,
				componentId: props.context.manifest.id,
				isDisposed: false,
				dispose: () => {
					console.debug(`provider.tokenAcquisitionEvent ::> dispose() <:: `);
				}
			}, tokenEventHandler);

			const spAccessToken = await provider.getToken("https://<tenant-name>.sharepoint.com");
			console.debug(`provider.getToken() SP API <:: `, spAccessToken);

			const graphAccessToken = await provider.getToken("https://graph.microsoft.com");
			console.debug(`provider.getToken() Graph API <:: `, graphAccessToken);

		} catch (error) {
			console.error(error);
		}
	})();
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment