question

AnupMahato-5646 avatar image
0 Votes"
AnupMahato-5646 asked AmosWu-MSFT answered

ClientContext gives 401 unauthorized for AccessToken from https://login.microsoftonline.com/{tennant_id}/oauth2/token

I'm using CSOM APP-only auntentication method to connect with SharePoint in a .Net Core Application using MicrosoftSharePointCSOM package and not PNP packages.

Problem- I'm using below endpoints to auntenticate. I'm getting Access_Token for both of them

  1. https://accounts.accesscontrol.windows.net/{tennant_id}/tokens/OAuth/2

  2. https://login.microsoftonline.com/{tennant_id}/oauth2/token


API Calls

Method 1

POST /{tennant_id}/tokens/OAuth/2 HTTP/1.1

Host: accounts.accesscontrol.windows.net

Content-Type: application/x-www-form-urlencoded


grant_type=client_credentials

&client_id ={client_id}@{tennant_id}

&client_secret ={client_secret}

&resource ={resource_id}/{host_name}@{tennant_id}



Method 2

POST /{tennant_id}/oauth2/token HTTP/1.1

Host: login.microsoftonline.com

Content-Type: application/x-www-form-urlencoded


grant_type=client_credentials

&client_id ={client_id}

&client_secret ={client_secret}

&resource ={host_name}



I'm getting acess_token for both of them. But when I use this access_token to make ClientContext object, the access_token for only first method 1 works.
And when I use the access_token of method 2 , I get 401 unauthorized error.

C# code of ClientContext

ClientContext context = new ClientContext(web);


context.ExecutingWebRequest += (sender,e) =>

{

string access_token = accessToken;

e.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer" + access_token;

};



Can you please tell me what am I doing wrong here? And why access_token of method 1 works but method 2 doesn't?

P.S - Please ignore any typo.

office-sharepoint-server-developmentazure-ad-authentication
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

AmosWu-MSFT avatar image
1 Vote"
AmosWu-MSFT answered

Hi @AnupMahato-5646 ,
The first URL is authenticated by Azure Access Control (ACS), and the obtained access token can be used for CSOMand REST API.
Context Token OAuth flow for SharePoint Add-ins
The OAuth 2.0 Client Credentials Grant Flow use the second url to get the access token, The access token is used to authenticate to the secured resource.
Service to service calls using client credentials (shared secret or certificate)


If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.