User Review
( votes)Recently, I had a requirement where I had to grant access to a user to use SharePoint as well as CRM using Azure App. While working on this, I came across an OAuth2 request that would allow us to get access tokens & refresh tokens using the scope of required resources (here, CRM & SharePoint).
Since multiple scopes were being accepted, I went ahead and passed scopes of CRM SharePoint in the same request. The request was similar to the below –
var b2cAuthUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/authorize?"+ "client_id=" + clientId + "&response_type=code" + "&redirect_uri=" + redirectUrl + "&scope=offline_access"+" "+crmURL + "/user_impersonation" +" "+ sharepointSite + "/User.read.all Sites.FullControl.All " + "";
After the above request, I continued to perform operations according to the requirement. When I used the generated access token to perform CRM-related functionality it worked as expected. However, when I used the same access token to upload a file in SharePoint, it threw a 401 UNAUTHORIZED ERROR.
Then after some digging, I found out that there is a restriction from the OAuth2 endpoint as it is designed to provide a token for the resource specified in the first scope listed in the request. This means that if a request is made with multiple scopes specified, only the first scope will be considered for token generation. As a result, any additional scopes listed in the request will not affect the token generation process.
So, due to the restriction from OAuth2, I created a new request consisting of a single resource with a particular scope and generated the tokens using that request which worked as expected.
Conclusion
In the future, if you want to use multiple scopes and multiple resources, for each resource, a distinct request should be made that includes the request for that specific resource and its corresponding scope. By doing this, the requests can be tailored to meet the unique requirements of each resource and scope, providing greater control and flexibility in the request process.
The post Authorize multiple resources while working with OAuth2 request first appeared on Microsoft Dynamics 365 CRM Tips and Tricks.