Configurar Microsoft Graph API en SPFx

Primer paso: Añadir el recurso en package-solution (Resource y Scope):

{
  "$schema": "https://dev.office.com/json-schemas/spfx-build/package-solution.schema.json",
  "solution": {
  "name": "spfx-package",
  "id": "8s13d6v9-d221-468d-22e4-2d207b966cd2",
  "version": "1.0.0.0",
  "includeClientSideAssets": true,
  "skipFeatureDeployment": true,
  "webApiPermissionRequests": [
    {
      "resource": "Microsoft Graph",
      "scope": "User.ReadBasic.All"
    }
  ]
},
"paths": {
  "zippedPackage": "solution/spfx-package.sppkg"
}

Segundo Paso: Aprobar los permisos desde el Admin Center de nuestro tenant (Advanced -> API management -> Select Request -> Approve or reject):

Y en nuestros componentes:

Importar MSGraphClient de la librería sp-http:

import { MSGraphClient } from '@microsoft/sp-http';

Acceder al cliente de Graph mediante el contexto del Client Web Part de SPFx:

context.msGraphClientFactory.getClient().then((client: MSGraphClient): void = {
    //Call the Graph API here
});

Ejemplo para obtener todos los usuarios:

public static getAllUsers(context: WebPartContext): Promise {
    return new Promise((resolve, reject) => {
        context.msGraphClientFactory.getClient().then((client: MSGraphClient): void => {
            client
              .api('users')
              .version('v1.0')
              .get((error: any, result: any, rawResponse?: any) => {
                  if(error) {
                      console.log(error);
                      reject(error);
                  }
                  else {
                      resolve(result.value);
                  }
              });
          });
    });
}

Para más información: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aad-tutorial

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *