Tymon Tymański
Tymon Tymański

Reputation: 9

Microsoft Graph Api - upload file and invalidRequest

I have a problem uploading files to sharepoint using the graph api. With the token downloaded from https://developer.microsoft.com/en-us/graph/graph-explorer everything works fine. I get a response with a status of 200.

enter image description here

However, when I want to upload a file with a token received from AD I get an invalid request.

Response from postman

In the scope of my token there is: "Files.ReadWrite Files.ReadWrite.All Group.Read.All Group.ReadWrite.All GroupMember.Read.All GroupMember.ReadWrite.All openid profile Sites.Read.All Sites.ReadWrite.All User.Read email".

Reading the file list works without any problems

Below is the code on how I generate the token to Graph Api

enter image description here

Upvotes: 0

Views: 1065

Answers (1)

Tiny Wang
Tiny Wang

Reputation: 15961

Firstly, pls don't show your code in your picture because we can't copy code from picture directly so that we can't test your code and reproduce your issue.

In your screenshot, I can see you used https://graph.microsoft.com/.default as the scope, and since you used a console application, so you should use client credential flow to generate the author provider so that you can generate a correct access token. And this can also explain why you used the token obtained from graph explorer can work. When we use graph explorer, it will ask us to sign in first so that it can generate an access token which containing delegate api permission. And in your code you used var authProvider = new DelegateAuthenticationProvider.

enter image description here

You also shared the api permissions, but when you used client credential flow, you have to set the application api permission but not the delegate api permission. For this upload file api, the permission should be Files.ReadWrite.All, Sites.ReadWrite.All. Pls don't forget the give the api permission.

By the way, since you've used the graph SDK, you can use my code snippet to call graph api.

using Microsoft.Graph;
using Azure.Identity;

var scopes = new[] { "https://graph.microsoft.com/.default" };
string tenantId = "TenantId";
string clientId = "ClientId";
string clientSecret = "ClientSecret";
var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var uploadFile = await graphClient.Drives[drives].Root.xxxx;

Upvotes: 1

Related Questions