Creating usercontext for SharePoint Online site in a .netcore Web API without username and password
As per my understanding, Microsoft provides an authorizing mechanism for generating an access token on behalf of a user. The million-dollar question is , if Microsoft allows generation of an access token outside SharePoint context, for any user and if a user context can be created which is similar to SPFX webparts to extract data for a specific user , based on his permission.
The following are the steps I tried.
- I created an Azure AD app and gave the following permissions. These permissions were only set to read the site data.
- In order to generate the Authorization Code, the user has to be redirected to the Microsoft identity platform. It will ask the user to login. I did not see any way to get the Auth code without User intervention.
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize
I created the following request to generate the Authorization code
https://login.microsoftonline.com/[Azure AD Tenant ID]/oauth2/v2.0/authorize?
client_id=[Azure AD Client ID]
&response_type=code
&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient
&response_mode=query
&scope=Sites.Read.All
&state=12345
- Next, is exchanging the Authorization code for an Access token.This is done by hitting the following:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
I passed the following parameters to the above endpoint
- client_id: The client ID of your registered application.
- client_secret: The client secret of your registered application.
- redirect_uri: The redirect URI specified during application registration.
- code: The authorization code obtained from the previous step.
- grant_type: Set this to "authorization_code".
- Next , use the access token to create the context for SharePoint. When I run the code to read a SharePoint resource, I get 401 unauthorized.
- I wasn’t able to generate Authorization code for non admin users, which requires a consent. I get the following error.
- AADSTS65001: The user or administrator has not consented to use the application with ID '6692f227-5d5f-4efa-be3e-a96bfac92840' named 'Azure AD App'. Send an interactive authorization request for this user and resource.\r\nTrace ID: 8d869845-142d-40b3-8c73-1cf564a60a00\r\nCorrelation ID: 7570b751-e266-4010-ad75-4040cef3b3fa\r\nTimestamp: 2023-06-08 04:57:26Z",
- I require someone to validate my understanding and give their valuable insights on this.