Search code examples
sharepointazure-active-directoryazure-functionsspfxaadhttpclient

From Azure Function (secured by AAD), how to properly detect the caller (the end-user of SPFx WebPart) through the AadHttpClient?


Note: Both Azure Function and the SPFx WebPart mentioned below are written in NodeJS/JavaScript. None of them are in C#.

I have an Azure Function (secured by AAD: App Registration) which is being called by AadHttpClient via SPFx WebPart on a SharePoint page. The SPFx codes look like this:

return new Promise<void>((resolve: () => void, reject: (error: any) => void): void => {
    this.context.aadHttpClientFactory.getClient("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") // <--- This is the AAD Client App Id.
    .then((client: AadHttpClient): void => {
        
        client.post("https://myAzureFunctionName.azurewebsites.net/api/HttpTrigger1", AadHttpClient.configurations.v1, {
            body: JSON.stringify({
                data: someData
            })
        })
        .then((res: HttpClientResponse): Promise<any> => {
            return res.json();
        })
        .then((response: any): void => {
            console.log("SUCCESSFUL API RESPONSE:", response); // <--- At this point, I get the respond back from the Azure Function, successfully.
            resolve();
        }, (err: any): void => {
            console.error(err);
        });

    }, err => reject(err));
});

It is working fine except from the Azure Function end, I don't know how to properly detect who/which current SharePoint User is calling this API. The only dirty trick I can use is, of course, to attach the User Information, such as Email Address, (retrieved from _spPageContextInfo object) into the AadHttpClient API call, to the Azure Function.

Question

  • What is the proper/authentic way in which I can detect the caller (the currently logged in, end-user of SPFx WebPart) through the AadHttpClient, from the Azure Function end? So that I can use the user's Email Address further in the Azure Function.

Appreciate the helps in advance.


Solution

  • You can access the current user details from request header properties:

    • User ID: X-MS-CLIENT-PRINCIPAL-ID
    • User Name: X-MS-CLIENT-PRINCIPAL-NAME
    • Claims: X-MS-CLIENT-PRINCIPAL
    • Identity Provider's ID: X-MS-CLIENT-PRINCIPAL-IDP

    Source: From Azure Function (secured by AAD), how to properly detect the caller (the end-user of SPFx WebPart) through the AadHttpClient?