SharePoint Online multi-tenant REST calls return 404 on resources that definitely exist - sharepoint

I am attempting to access the SharePoint Online REST API (this is hand coded REST calls, no library being used).
Access tokens are acquired using authorization grant flow as follows:
I send the browser https://login.microsoftonline.com/common/oauth2/authorize?...
This redirects to a handler endpoint that we extract the access code from
I obtain the tenant ID by:
GET https://{tenantname}.sharepoint.com/_vti_bin/client.svc
Then extracting the tenant ID from the WWW-Authenticate header
I then POST https://login.microsoftonline.com/{tenantid}/oauth2/authorize to obtain the access token
When I use that access token, I am able to do queries using:
GET https://{tenantname}.sharepoint.com/_api/search/query?querytext=....
This works and returns documents.
But when I attempt to retrieve information about one of those documents:
GET https://{tenantname}.sharepoint.com/_api/web/getfilebyserverrelativeurl('/TestFiles/test.pdf')
I get a 404 response with the following body:
{"odata.error":{"code":"-2130575338, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The file /TestFiles/test.pdf does not exist."}}}
If I navigate to the URL in a browser (https://{tenantname}.sharepoint.com/TestFiles/test.pdf), it accesses the file without issue.
This makes me think that I'm running into some sort of permission issue.
I have tried setting the following scopes in the authorize redirect:
Attempt 1: scope = Web.Write AllSites.Write Site.Write
Attempt 2: scope = https://{tenantname}.sharepoint.com/.default
Attempt 3: scope = https://{tenantname}.sharepoint.com/Web.Write https://{tenantname}.sharepoint.com/AllSites.Write https://{tenantname}.sharepoint.com/Site.Write
No matter what I set as the scope parameter of the authorize URL, the JWT details of the access token show (I can post the entire decoded JWT if anyone needs it):
"scp": "User.Read"
Nothing I do has any impact on the scp in the token - I have no idea if that's the issue or not. If it is, I would appreciate hearing how to properly request scope.
The application registration in Azure Active Directory has desired permissions (plus more):
What am I doing wrong?
UPDATE: Switching to OAuth endpoint v2.0:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize
With query parameters:
response_type = code
client_id = my app id
redirect_uri = my redirect uri
scope = <varying - I'll explain what happens under different scenarios below>
Here's what I've tried for scopes:
AllSites.Write Site.Write - the redirect has invalid_client with error_description = AADSTS650053: The application '' asked for scope 'AllSites.Write' that doesn't exist on the resource '00000003-0000-0000-c000-000000000000'. Contact the app vendor.
https://{tenantname}.sharepoint.com/AllSites.Write https://.sharepoint.com/Site.Write - the redirect has invalid_client with error description = AADSTS650053: The application '' asked for scope 'Site.Write' that doesn't exist on the resource '00000003-0000-0ff1-ce00-000000000000'. Contact the app vendor.
https://{tenantname}.sharepoint.com/.default - this goes through
But the resulting JWT has only scp=User.Read
The following works: GET https://{tenantname}.sharepoint.com/_api/search/query?querytext=
But the following returns a 404: GET https://{tenantname}.sharepoint.com/_api/web/getfilebyserverrelativeurl('/TestFiles/test.pdf')
I don't understand how Scope=.Default isn't including the allowed permissions from the application registration. And I definitely don't understand why the AllSites.Write scope is failing when it's explicitly specified.
If it helps, I have also tried all of the above using a tenant specific authorize endpoint instead of 'common':
https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize
UPDATE2: More scope changes:
I finally found a magical combination that works:
Use a tenant based URI for the /authorize and /token endpoint and use {tenanturl}\AllSites.Write for the scope (do NOT specify the Site.Write scope):
https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize?response_type=code&client_id={clientid}&redirect_uri={redirecturi}&scope=https%3A%2F%2F{tenantname}.sharepoint.com%2FAllSites.Write
The resulting JWT has the following:
"scp": "AllSites.Write User.Read"
I am completely perplexed about why Site.Write wasn't allowed. I suppose that AllSites.Write is a superset of Site.Write, so maybe not needed?
All of my testing so far has been on my own tenant, next step is to test on a different tenant and make sure it actually works there as well.

It seems you use v1.0 endpoint https://login.microsoftonline.com/common/oauth2/authorize but not v2.0 endpoint https://login.microsoftonline.com/common/oauth2/v2.0/authorize. If we use v1.0 endpoint, we should use resource instead of scope. So that is why the scp claim in your access token always the same no matter you modify the scope.
You should use resource with https://{tenant-name}.sharepoint.com and the parameter scope is useless when you use v1.0 endpoint.
If you still want to use scope parameter, you can also change the endpoint to v2.0. Just add v2.0 into your endpoint, like: https://login.microsoftonline.com/common/oauth2/v2.0/authorize

I finally found a magical combination that works:
use the https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize and https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token endpoints
specify {tenanturl}\AllSites.Write for the scope (do NOT specify the Site.Write scope - that was the primary problem):
https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize?response_type=code&client_id={clientid}&redirect_uri={redirecturi}&scope=https%3A%2F%2F{tenantname}.sharepoint.com%2FAllSites.Write
The resulting JWT has the following: "scp": "AllSites.Write User.Read"
This works across tenants and gets us the access we need.
For thoroughness, we also specify offline_access scope so we get a refresh_token in addition to the access_token.

Related

The provided value for the input value scope is not valid for OnlineMeeting.ReadWrite

I am trying to create meeting on behalf of a user for that I am trying to get the code. I have registered the app on Azure. Also generated Application(Client) ID I have also added the required permission in the API. But when I am visiting this page the page asks for the email id but once the users fill the email id it says The provided value for the input value scope is not valid for OnlineMeeting.ReadWrite in the redirect URL.
Please guide me to know what I am missing here.
Edit 1: As suggested by #Rukmini I tried this and here is the relevant details.
To obtain the the code I am building url like this image
This does not work when I pass the OnlineMeetings.ReadWrite scope. But when I pass https://graph.microsoft.com/.default as scope it works and I am able to authenticate and generate a code. Then I can use that code to get the access token like following image. But using this access token I can not create the meeting as it does not have the OnlineMeetings.ReadWrite scope as stated in this doc **https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=http**[![enter image description here]3]3
Let me know what I can do to generate code and access token for the OnlineMeetings.ReadWrite scope so that I can create the meeting on users behalf. Thanks
EDIT 2: I generated the authorization URL as suggested by #Rukmini using the following query parameters.
When I visited the link, I was presented with a login screen but as my previous error I see the same screen. Am I missing something here? Do I need to verify my app? Or Do I have to only use some specific IDs like we do in GCP and AWS?
Please let me know what I am missing here.
Thanks
I tried to reproduce the same in my environment and got the results successfully like below:
I created an Azure AD Multi-Tenant Application:
I granted Admin Consent to the API permissions like below:
I generated the code by using below endpoint and authorizing it via browser:
https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://jwt.ms
&response_mode=query
&scope=OnlineMeetings.ReadWrite
&state=12345
Now, I generated access token by using the below parameters:
https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:OnlineMeetings.ReadWrite
grant_type:authorization_code
redirect_uri:https://jwt.ms
code:code
Decode the access token using jwt.ms and check whether the scope is OnlineMeetings.ReadWrite:
I am able to create the Online meetings successfully by using the below query:
https://graph.microsoft.com/v1.0/me/onlineMeetings
Content-Type: application/json
{
"startDateTime":"2023-01-12T14:30:34.2444915-07:00",
"endDateTime":"2023-02-12T15:00:34.2464912-07:00",
"subject":"User Token Meeting"
}

Is it possible to access microsoft graph using custom audience?

I have an API that uses Azure AD to provide access to resources. It has one scope api://{client_id}/Api.Read and following API permissions:
User.Read.All,
User.Read.
When I receive an access token from the AD it has only one aud - {client_id} and when I try to access Microsoft graph (e.g. https://graph.microsoft.com/v1.0/me) I get "Access token validation failure. Invalid audience." response as expected.
My question is - Is it possible to access both graph API and my API using one token and how do it?
I am exchanging current token to a "proper" token using on-behalf-of call: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow
Basically, you just make the following call (copied from the link above):
POST /oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com/<YOUR_TENANT>
Content-Type: application/x-www-form-urlencoded
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
&requested_token_use=on_behalf_of
&client_id=<YOUR_CLIENT_ID>
&client_secret=<YOUR_CLIENT_SECRET>
&assertion=<YOUR_CURRENT_TOKEN>
&scope=<YOUR_NEW_SCOPES>
The response contains the new token to access the resources that are requested in the scopes. My scenario is not exactly yours, but I think this should work for your case as well. You need to make this call server-side.
This assumes that the user has already consented that your app is okay to use <YOUR_NEW_SCOPES>, or otherwise this call will result in "interaction_required" or "invalid_grant" error (something like this, don't remember the exact error name) that basically means you need to raise UI prompt for the user to agree to the new scopes (how to do that is another question)

Setting additionalLoginParams with auth v2

I've followed this guide to configure access to my backend app, but I use Node backend and React frontend. However I'm unable to perform the step Configure App Service to return a usable access token. I get the error "Cannot execute the request for site x because the site is running on auth version v2.". To handle this I tried instead editing the sheet authsettingsV2, and I believe I found that the property properties.identityProviders.azureActiveDirectory.login.loginParameters in v2 equals properties.additionalLoginParams in v1 as editing this v2 property according to the tutorial shows the desired property in the v1 authsettings sheet.
However accessing my frontend app with this setting I get the error AADSTS901002: The 'resource' request parameter is not supported. before even being able to enter my credentials.
I've also tried without the additionalLoginParams setting completely, this gives me the error {"code":401,"message":"IDX10511: Signature validation failed. Keys tried: '[PII is hidden]'. \nkid: '[PII is hidden]'. \nExceptions caught:\n '[PII is hidden]'.\ntoken: '[PII is hidden]'."} on the API call, and upon inspecting my token, I find that the audience is the Microsoft Graph API. But I guess that is expected with this setup.
How can I proceed to enable access to my backend app? / How do I set the additionalLoginParams in auth version v2?
I am not sure if you have a correct access token. Please note that I am not talking about id token. Because from your response_type=code id_token, there should be only one id_token returned, but obviously the id_token cannot call your api, because what you need is an access token.
If you have not obtained a correct access token, then you should request an access token in the next step, refer to this link.
In addition, I must explain that all 401 errors are caused by api audiences. Therefore, make sure that your Application ID URI is set in the scope parameter.
When requesting an access token, you need to set the scope to: scope=openid api://{back-end api client id}/.default. Set response_type to: response_type=token.

Authenticate for Azure REST API without login

I have a backend process that doesn't directly interact with the user. I want to access reservations associated with my Azure account but I'm having trouble with the authentication step. I was following the guide here and I managed to get the authentication request to work by calling
https://login.microsoftonline.com/{tenant-ID}/oauth2/token
as a POST with the following x-www-form-urlencoded body:
grant_type=client_credentials&
client_id={client-ID}&
client_secret={client-Secret}&
resource=http://myapp42
However, when I attempt to call:
https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}?api-version=2019-04-01
with the bearer token I received during the authentication step, I get the following error message:
The access token has been obtained for wrong audience or resource 'http://myapp42'. It should exactly match with one of the allowed audiences 'https://management.core.windows.net/', 'https://management.core.windows.net', 'https://management.azure.com/', 'https://management.azure.com'
However, if I modify the resource on the request to be one of these, http://management.core.windows.net/ for instance, the authentication then fails with:
AADSTS500011: The resource principal named https%3A%2F%2Fmanagement.core.windows.net%2F was not found in the tenant named {tenant-ID}. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: b54cedea-3804-41cf-bd27-fcf0ed1c4700\r\nCorrelation ID: 2371d375-6c89-4f05-83c9-c4629b3340a8\r\nTimestamp: 2020-02-05 01:59:57Z
How do I authenticate so that I can then get my reservations without having to login?
Update:
The service principal has both the Owner and Contributor roles assigned.
Update 2:
Thanks to #Jim Xu, I was realized that I needed to refrain from url-encoding the URL. That allowed me to get the access token with a value of https://management.azure.com/ for the resource field. However, at this point, when I attempt to call the REST API with the resulting bearer token, I get the following error:
The client '{Object-ID}' with object id '{Object-ID}' does not have authorization to perform action 'Microsoft.Capacity/reservationOrders/reservations/read' over scope '/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}' or the scope is invalid. If access was recently granted, please refresh your credentials
Note: The object ID returned by this error is the one associated with the service principal.
Update 3:
I checked the reservation and it seems that the principal does not have a role in that reservation's access control. However, I also cannot assign the principal a role because it does not show when I search for principals during the role-assigning process.
If you want to call Azure Rest API to get the information of reservation Orders, you need to assign Owner\Contributor for the service principal.(the action needs Microsoft.Capacity/reservationOrders/read permission).
The steps are as below
Get access token
POST : https://login.microsoftonline.com/{tenant-ID}/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&
client_id={client-ID}&
client_secret={client-Secret}&
resource=https://management.azure.com/ or https://management.core.windows.net
Call the api
GET : https://management.azure.com/providers/Microsoft.Capacity/reservationOrders/{order-ID}/reservations/{reservation-ID}?api-version=2019-04-01
Authorization: Bearer <token>
For more details, please refer to the issue and the issue
update
If you have assigned role but you still cannot get access token, please try to encode your url.

Including "prompt=consent" on Office 365 OAuth authorization request for resource "https://graph.microsoft.com/" generates an error

I'm moving our existing Office365 API usage over to the Unified API (at https://graph.microsoft.com/v1.0).
For reasons explained in Adding an additional Windows Azure AD delegated permission to an existing grant, I need to include prompt=consent in my authorization request Url, and so up until now my authorization Url has looked like:
https://login.microsoftonline.com/common/oauth2/authorize?resource=https%3a%2f%2fgraph.windows.net%2f&prompt=consent&client_id=ec49c780-6767-46f2-8697-bdd816e42504&redirect_uri=https%3a%2f%2flogin.airhead.io%2fservices%2freply%2foffice365%2foauth&scope=UserProfile.Read+Calendars.Read+Files.Read+Sites.Read.All+Mail.Read&response_type=code
..which (after auth and consent) returns me to something like:
https://login.airhead.io/services/reply/office365/oauth?code=AAABAAAAiL9Kn2Z27UubvWFPbm0gLeSvP6UG3gEwceCQ8hU_03hUjXRvPUfs_Y-324csuR0rDFE-qdNIsD0on-DjKGoSzvVL4PKh7_uQkghxtOGCZGEJ7GwcUDpvoHH86pjct3vAb94wPt8Pkdm46HhvPeBn6JDrK5VIBYdwxS2r8dLRmjqiyIBbGZDsOUCDymeFebYsFc-V39sQ9WFSx5ErjIeHvZ_Qf4zB1SDjT-iEqJPTW7H5bZpvFJQHhUqn3TvVL37Up4ZzkWxz5fb0zMk_7yKuz6G-DW6kz_Y1S30ZNgO45maDEw9KBqmdIR_NeewmFSKokgF4Unsfi__xNzjf6xO6VcMOidych7V7uQi_jxX7zP5hLvXgAoNmqBU-AnV2NVZ-5tq2s4w8vvl61TXUjR1MtwVf4TzcsL55uvyP16lid6JpWsdssZvWJNXna_zJC0Ok629vE5-4pzu-zF5C_PJztkx8VQ8QDmP4_JqkHkRmq2zO0doY25AF6Sh3odyNEx6IwWxe9jirPv_8NfwlmldYnpItzbmYlqLilOIEBNXpESgUmPz02A0Czu--pZP45JfjNDrVnUBBV9liPToK_QPe99xOSNHmk70h171M5BjVnhggAA&session_state=8494e152-60ab-4ddc-a247-ee55798e0595
..which allows me to continue with the flow, using the code auth'd against the old https://graph.windows.net/ resource. All good.
However, after modifying the resource param value on the authorization Url to https://graph.microsoft.com/ to authorize against the new Unified API, i.e.:
https://login.microsoftonline.com/common/oauth2/authorize?resource=https%3a%2f%2fgraph.microsoft.com%2f&prompt=consent&client_id=ec49c780-6767-46f2-8697-bdd816e42504&redirect_uri=https%3a%2f%2flogin.airhead.io%2fservices%2freply%2foffice365%2foauth&scope=UserProfile.Read+Calendars.Read+Files.Read+Sites.Read.All+Mail.Read&response_type=code
..I'm returned an error response:
https://login.airhead.io/services/reply/office365/oauth?error=access_denied&error_description=AADSTS65005%3a+The+client+application+has+requested+access+to+resource+%27https%3a%2f%2fgraph.microsoft.com%2f%27.+This+request+has+failed+because+the+client+has+not+specified+this+resource+in+its+requiredResourceAccess+list.%0D%0ATrace+ID%3a+d9cc9773-feb5-42b4-9414-eaf64620fc0f%0D%0ACorrelation+ID%3a+ea1f37de-35bb-4b41-af49-c877dda75d11%0D%0ATimestamp%3a+2016-01-18+13%3a15%3a18Z
..with description "AADSTS65005: The client application has requested access to resource 'https://graph.microsoft.com/'. This request has failed because the client has not specified this resource in its requiredResourceAccess list".
If I try the same authorization Url (against resource https://graph.microsoft.com/ again), but drop the prompt=consent param this time, i.e:
https://login.microsoftonline.com/common/oauth2/authorize?resource=https%3a%2f%2fgraph.microsoft.com%2f&client_id=ec49c780-6767-46f2-8697-bdd816e42504&redirect_uri=https%3a%2f%2flogin.airhead.io%2fservices%2freply%2foffice365%2foauth&scope=UserProfile.Read+Calendars.Read+Files.Read+Sites.Read.All+Mail.Read&response_type=code
..it works.
The documentation at https://msdn.microsoft.com/en-US/library/azure/dn645542.aspx still suggests that prompt=consent is valid, so is the documentation wrong (i.e. I can't use prompt=consent with resource https://graph.microsoft.com/) or is this a bug?
It turns out there's a whole new set of scopes for v1.0 of graph.microsoft.com, which weren't needed during the preview. Adding these scopes to my app manifest resolved the issue. (facepalm)

Resources