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

352 Views Asked by At

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.

3

There are 3 best solutions below

1
Ganesh Sanap - MVP On BEST ANSWER

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?

2
Marcin Wojciechowski On

You can try this: How to get current user identity in Azure Function with Azure Authentication? To get current user info. You can also decode access token You provided to the azure function with this code

var token = "[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jwtSecurityToken = handler.ReadJwtToken(token);
0
AlfredoRevilla-MSFT On

As @marcin-wojciechowski suggests, you can decode the JWT token attached within the Authorization header and read its claims.

Here is some sample code:

const jwt_decode = require("jwt-decode");

module.exports = async function (context, req) {

    const { headers } = req;
    const { authorization } = headers;

    const token = authorization.split("Bearer ")[1];
    const decoded = jwt_decode(token);

    //  returning the user object id
    context.res = {
        body: JSON.stringify(decoded.oid)
    };
}