This .NET 9 project demonstrates how to perform file operations in SharePoint Online using the Microsoft Graph API with OAuth 2.0 authentication and delegated access. The application facilitates seamless file interactions, leveraging modern authentication techniques and the capabilities of the Graph API.
Microsoft Graph API is a unified API endpoint that provides access to Microsoft 365 data and intelligence. It serves as a single endpoint (https://graph.microsoft.com
) to access data across various Microsoft services including SharePoint, OneDrive, Outlook, Teams, and more. Key advantages include:
- Unified Access - A single API to access data across multiple Microsoft services
- Consistent Data Model - Standardized entities and relationships
- Rich SDK Support - Official SDKs for .NET, JavaScript, Java, Python, and more
- Modern Authentication - OAuth 2.0 and OpenID Connect support
- Intelligence & Insights - AI-powered features and analytics
In this project, we leverage Microsoft Graph API to interact with SharePoint Online document libraries and files.
- OAuth 2.0 authentication with delegated access
- File operations on SharePoint Online, such as:
- Uploading files
- Downloading files
- Deleting files
- Listing files
- Updating file metadata
- Easy-to-use interface for managing files in SharePoint document libraries
- Distributed caching for improved performance
Before running the application, ensure you have the following:
- A Microsoft 365 tenant with SharePoint Online enabled
- Azure Active Directory (AAD) App Registration with:
- Client ID
- Tenant ID
- Client Secret
- Redirect URI configured for OAuth 2.0 authentication
- API Permissions granted in Azure AD App Registration:
Sites.ReadWrite.All
- Required for accessing and modifying SharePoint sitesFiles.ReadWrite.All
- Required for file operations
- Development environment:
- Visual Studio 2022 or later
- .NET 9 SDK installed
- (Optional) Bruno API client for testing
- Go to Azure Portal and navigate to Azure Active Directory
- Select App registrations and click New registration
- Enter a name for your application and select the appropriate account type
- Set the Redirect URI to your application's callback URL
- Click Register
- Navigate to API permissions and add the following permissions:
- Microsoft Graph API > Application permissions > Sites.ReadWrite.All
- Microsoft Graph API > Application permissions > Files.ReadWrite.All
- Click Grant admin consent for these permissions
- Navigate to Certificates & secrets and create a new client secret
- Note down the Client ID, Tenant ID, and Client Secret for configuration
git clone https://github.com/nitin27may/sharepoint-graph-api
cd sharepoint-graph-api
- Open the
appsettings.json
file and update the placeholders with your Azure AD App Registration details:{ "GraphApiSettings": { "ClientId": "<YOUR-CLIENT-ID>", "TenantId": "<YOUR-TENANT-ID>", "ClientSecret": "<YOUR-CLIENT-SECRET>", "Scope": "https://graph.microsoft.com/.default ", "BaseGraphUri": "https://graph.microsoft.com/v1.0", "BaseSpoSiteUri": "<YOUR-BASE-SHAREPOINT-SITE-Name>.sharepoint.com" } }
- Open the project in Visual Studio.
- Restore NuGet packages:
dotnet restore
- Build the solution:
dotnet build
- Run the application:
dotnet run
Note: We are using Bruno API client for the testing Rest API, the files are added in Api Collection Folder
- This project has
GraphApiCientFactory
which is handling the authentication. - Upon successful authentication, the application will obtain an access token to interact with SharePoint Online via the Graph API.
This section provides detailed instructions on how to use the API endpoints for SharePoint file operations.
In SharePoint Online, the hierarchy is:
- Site: A collection of document libraries and other content
- Drive: A document library within a site (e.g., "Documents")
- Path: The location within a drive where files are stored
- Use
root
as thesiteName
parameter if you are using the base SharePoint Online site. - The default document library name in SharePoint is usually "Documents".
- File paths are relative to the drive root and should not include a leading slash.
Retrieves a list of files in a specified path within a document library.
GET /api/graph/files?siteName={siteName}&driveName={driveName}&path={path}
Parameters:
siteName
: Name of the SharePoint site (use "root" for base site)driveName
: Name of the document library (e.g., "Documents")path
: Path within the library (e.g., "Folder1/SubFolder")
Uploads a file to a specified path within a document library.
POST /api/graph/files?siteName={siteName}&driveName={driveName}&path={path}
Parameters:
siteName
: Name of the SharePoint sitedriveName
: Name of the document librarypath
: Target path for the file- Request body: Form data containing the file
Retrieves file metadata or downloads the file.
GET /api/graph/files/{fileName}?siteName={siteName}&driveName={driveName}&path={path}
Parameters:
fileName
: Name of the file to downloadsiteName
: Name of the SharePoint sitedriveName
: Name of the document librarypath
: Path to the file
Deletes a file from a specified path.
DELETE /api/graph/files/{fileName}?siteName={siteName}&driveName={driveName}&path={path}
Parameters:
fileName
: Name of the file to deletesiteName
: Name of the SharePoint sitedriveName
: Name of the document librarypath
: Path to the file
Updates metadata of an existing file.
PATCH /api/graph/files/{fileName}/metadata?siteName={siteName}&driveName={driveName}&path={path}
Parameters:
fileName
: Name of the file to updatesiteName
: Name of the SharePoint sitedriveName
: Name of the document librarypath
: Path to the file- Request body: JSON object with metadata key-value pairs
The application follows a layered architecture pattern with clear separation of concerns. Below is an architectural diagram of the codebase:
flowchart TB
Client[Client Application]
SpoWebApi[Spo.WebApi]
SpoGraphApi[Spo.GraphApi Library]
GraphApiClient[GraphApiClient]
GraphApiFactory[GraphApiClientFactory]
AuthHandler[GraphApiAuthenticationHandler]
GraphAPI[Microsoft Graph API]
SharePoint[SharePoint Online]
Client -->|HTTP Requests| SpoWebApi
SpoWebApi -->|Uses| SpoGraphApi
SpoGraphApi -->|Creates| GraphApiFactory
GraphApiFactory -->|Creates| GraphApiClient
GraphApiClient -->|Authenticated Requests| GraphAPI
GraphApiClient -->|Uses| AuthHandler
AuthHandler -->|OAuth 2.0| GraphAPI
GraphAPI -->|Interacts with| SharePoint
subgraph "Client Layer"
Client
end
subgraph "API Layer"
SpoWebApi
end
subgraph "Core Library"
SpoGraphApi
GraphApiFactory
GraphApiClient
AuthHandler
end
subgraph "External Services"
GraphAPI
SharePoint
end
-
Client Application: External applications that consume the API endpoints.
-
Spo.WebApi: ASP.NET Core Web API that exposes endpoints for SharePoint file operations. It acts as a façade over the core library.
-
Spo.GraphApi Library: Core library containing all the logic for interacting with Microsoft Graph API.
-
GraphApiClientFactory: Factory class responsible for creating instances of GraphApiClient with proper authentication.
-
GraphApiClient: Main class that handles all file operations by making authenticated requests to Microsoft Graph API.
-
GraphApiAuthenticationHandler: Handles OAuth 2.0 authentication with Azure AD and token management.
-
Microsoft Graph API: Microsoft's unified API endpoint that provides access to SharePoint data.
-
SharePoint Online: The destination service where files are stored and managed.
- The client sends an HTTP request to one of the endpoints in Spo.WebApi.
- The controller in Spo.WebApi processes the request and calls the appropriate method in the Spo.GraphApi library.
- The GraphApiClientFactory creates an authenticated instance of GraphApiClient.
- GraphApiClient sends authenticated requests to Microsoft Graph API.
- Microsoft Graph API interacts with SharePoint Online to perform the requested operation.
- The response follows the same path back to the client.
- .NET 9 - The latest version of the .NET framework
- Microsoft Graph API - Unified REST API for Microsoft 365 services
- OAuth 2.0 Authentication - Industry-standard protocol for authorization
- Azure Active Directory - Microsoft's cloud-based identity and access management service
- SharePoint Online - Cloud-based content management and collaboration platform
- Distributed Caching - For improved performance when accessing repeated resources
- Bruno API Client - For testing REST API endpoints
This section provides insights into the key components of the codebase to help developers understand and extend the functionality.
-
Spo.GraphApi: Core library containing interfaces, models, and implementations for Graph API operations
GraphApiClient.cs
: Main implementation of Graph API operationsGraphApiClientFactory.cs
: Factory for creating authenticated clientsGraphApiAuthenticationHandler.cs
: Handles OAuth 2.0 token acquisitionModels/
: Contains data models used throughout the application
-
Spo.WebApi: ASP.NET Core Web API exposing endpoints
Controllers/GraphApiController.cs
: Exposes REST endpointsProgram.cs
: Application startup and configurationappsettings.json
: Application settings including Graph API configuration
-
API Collection: Bruno API client collections for testing
- Contains pre-configured requests for all API operations
-
Authentication Flow
- The application uses the Client Credentials OAuth 2.0 flow
GraphApiClientFactory
handles authentication token acquisition and renewal- Tokens are cached to improve performance
-
Performance Optimizations
- Site and drive information is cached using distributed caching
- This reduces redundant calls to Microsoft Graph API
-
Error Handling
- Custom exception types for Graph API-specific errors
- Consistent error response format across all endpoints
-
Extension Points
- The modular design allows for easy extension of functionality
- Implement additional Graph API features by extending the
IGraphApiClient
interface
This project includes a collection of API requests for testing with Bruno API client.
- Install Bruno API client
- Open the
API Collection
folder in Bruno - Configure the environment variables in
environments/Local.bru
- Execute requests to test different endpoints
-
Authentication Errors
- Verify Client ID, Tenant ID, and Client Secret in
appsettings.json
- Ensure proper permissions are granted in Azure AD
- Verify Client ID, Tenant ID, and Client Secret in
-
File Operation Errors
- Check if the site, drive, and path parameters are correct
- Verify that the SharePoint site is accessible
-
Rate Limiting
- Microsoft Graph API has rate limits that may be encountered during heavy usage
- Implement retry logic or backoff strategies for production use
Contributions are welcome! If you find a bug or have a feature request, feel free to open an issue or submit a pull request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
This project is licensed under the MIT License. See the LICENSE file for details.
For any inquiries or support, please contact nitin27may@gmail.com.
Built with ❤️ using .NET 9 and Microsoft Graph API.