This is a demo code for video Graph APIs: Upload large file w/ progress to OneDrive, use of special folder & more | CodeNameK - 04.
kiquenet kiquenet raised the question:
I need create Windows Service, NOT InteractiveBrowser for access to shared folder in our OneDrive company. The folder is shared with a external client. External client upload and download files from/to our ONe Drive. Our Windows service requires upload and download files from/to our OneDrive. Not interactive process requires. How-to authenticated?
Here's example code. Note, I can't verify end to end because my account doesn't have an SharePoint Online (SPO) license with it. And you will also have to have an SPO license to make it work.
Here's the walk-through
-
Go to https://aka.ms/AppRegistrations to register an app if you don't have it already.
-
Add an authentication endpoint for
web
, it will be used by admin consent step later later. -
Add a client secret
Copy the secret now and save it. Once you leave the page, you can't copy it again.
-
Add API Permissions
- Do NOT choose delegated permission, use
application permissions
instead to grant permission to the application.
- Do NOT choose delegated permission, use
Now the registration is ready.
The tenant admin need to consent the permissions. Paste this URL template into any browser:
https://login.microsoftonline.com/{tenantId}/adminconsent?client_id={clientId}&state=12345&redirect_uri=https://localhost/myapp/permissions
- You can get the
tenant id
&client id
from the overview page of the registered app. They are displayed asDirectory (tenant) ID
&Application (client) ID
. - state could be anything. It will be post back to you when the consent is done.
- The
redirect_uri
need to match one of the Web endpoint you created earlier.
If you happen to be the tenant admin, you can consent it in the browser to allow the application to use the graph api. If you aren't, you send the URL to the admin, asking them to consent it. The consent dialog looks like this:
Once the consent is there, process forward for authenticating with the code.
Code is relative simple:
TokenCredential tokenCredential = new ClientSecretCredential(
tenantId: "your-tenant-id",
clientId: "your-client-id",
clientSecret: "the-client-secret"
);
GraphServiceClient client = new GraphServiceClient(tokenCredential, Scopes);
ListItem result = await client.Drive.Root.ListItem.Request().GetAsync(stoppingToken);
For a complete example, refer to Worker.cs.
These are the packages needed, also in OneDrive-Sample-Worker-Service.csproj:
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Microsoft.Graph" Version="4.29.0" />