SPFx and Microsoft Graph: Accessing User Data

SharePoint Framework (SPFx) 1.10+ makes consuming the Microsoft Graph API trivial. Accessing user emails, calendars, and OneDrive files is now a standard requirement for modern intranets. This guide demonstrates how to consume Graph securely using the MSGraphClient.

Requesting Permissions

In `package-solution.json`, declare the API scopes your web part needs. These must be approved by an M365 Admin.

"webApiPermissionRequests": [
  {
    "resource": "Microsoft Graph",
    "scope": "User.Read"
  },
  {
    "resource": "Microsoft Graph",
    "scope": "Mail.Read"
  }
]

Using MSGraphClient

SPFx handles the OAuth token acquisition and refresh automatically (ADAL/MSAL under the hood).

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

export default class GraphConsumer extends React.Component<IProps, IState> {
  
  private async getEmails() {
    // Factory pattern
    const client: MSGraphClient = await this.props.context.msGraphClientFactory.getClient();
    
    const response = await client
      .api('/me/messages')
      .top(5)
      .select('subject,from,receivedDateTime')
      .get();
      
    this.setState({ emails: response.value });
  }
  
  public componentDidMount() {
    this.getEmails();
  }
}

Key Takeaways

  • Permissions are granted at the **Tenant** level, not per user/site.
  • Always use `.select()` to minimize data transfer (OData best practice).
  • Use the Microsoft Graph Explorer to test queries before coding.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.