Get Azure Webjob History - 403 Token invalid - azure

I am trying to retrieve the web job history of an Azure web job via REST using a .NET backend and the OAuth2 credentials flow (as described here
https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-triggered-web-job-history-slot)
How do I need to authenticate correctly?
I retrieve the token as follows:
POST https://login.microsoftonline.com/{MySubscription}/oauth2/v2.0/token
client_id={MyApp}
&grant_type=client_credentials
&scope=https://management.azure.com/.default
&client_secret={myclient_secret}
I get a token back, however I get a 403 error message when I try to retrieve the resource:
GET https://management.azure.com/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}/history?api-version=2021-02-01
Authorization: Bearer {MyToken}
Client '{MyApp}' with object ID '{MyApp}' is not
authorized to perform the action
'Microsoft.Web/sites/slots/triggeredwebjobs/history/read' using the
scope
'/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}'
or the scope is invalid. If access was granted recently, please update
your credentials.
What am I doing wrong?
I already added the API-Permission

The "403 Token invalid" error usually occurs if you missed giving permissions to particular scope (Azure Service Management).
By giving this scope it enables you to access https://management.azure.com
To resolve this error, please follow below steps:
Go to Azure Ad ->your application -> API permissions -> Add permission -> Azure Service Management -> delegated permissions ->User impersonation -> Add
After giving these permissions try to retrieve the resource again, there won't be any error.

Since I didn't find a solution that worked with OAuth2 and the Credentials flow, I got it working with Basic Authentication. The username (userName) and password (userPWD) can be taken from the publishing profile of the respective app service.
GET https://{appservicename}.scm.azurewebsites.net/api/triggeredwebjobs/{jobName}/history
Authorization Basic ....

Related

SharePoint Online Webhook Subscription: "Access is Denied" Error?

I have been following this tutorial on how to create a SharePoint webhook subscription, and after authenticating and getting the access token, actually trying to send the request to add a webhook subscription to a SharePoint list through Postman gives me an "Access is denied HRESULT: 0x80070005" error:
Error message
Going into the Postman console to see a more verbose error message shows "917656; Access+denied.+Before+opening+files+in+this+location%2c+you+must+first+browse+to+the+web+site+and+select+the+option+to+login+automatically."
I have tried all of the following:
Gone into SharePoint to enable Sites.Manage.All permissions for my Azure AD App
Reauthorized with several accounts with various access levels
Verified that ngrok, my webhook receiver, and Azure AD App were all running and all connection strings/client ids/secrets were valid.
Could it be that I'm missing something else in regards to SharePoint permissions for my Azure AD App, or is it another issue?
I tried to reproduce in my environment its working fine getting the access token added webhook subscription to a SharePoint list through Postman
First, Check whether you are added content-type and accept in header
This error may cause because of some security issue postman is not authenticated and not authorized to get data from the SharePoint. For this try to register an app using your URL modify at end /_layouts/15/appregnew.aspx
For sample:
https://imu.sharepoint.com/sites/mirror/_layouts/15/appregnew.aspx
Hope you have access, try to register your app as below:
Here, you need to give permission to that particular app such as Full control permission as below snip link :
In App's permission request XML apply permission as below:
And, Click Create and pop up will display trust it. click trust it site setting tab will display if you click that site collection app permission your postman right side will display client id#tenant id
To get the access token click launchpad -> create request ->https://accounts.accesscontrol.windows.net/Tenant ID()/tokens/OAuth/2/
Try to add values in Body tab like
grant_type - client_credentials
Client_id - ClientID#TenantID
Client_secret - Clientsecret
resource - resource/siteDomain#TenantID
Make sure in your Url remove parenthesis in your TenanID and site domain is in your Url like ***.sharepoint.com
Finally, i have added Authorization in header and in value Bearer access token make sure to remember space between bearer and Your access token, I am getting result successfully without any Access Denied error.
For your Reference :
OfficeDev/TrainingContent
Revisit these things
App registered in AD is having AllSites.Manage permission (delegated) and admin consent granted.
While getting access token via postman, use scope as https://yourtenant.sharepoint.com/.default
headers : Content-Type = application/json, Accept = application/json;odata=verbose

Azure registered app error: The user or administrator has not consented to use the application with ID

We´re trying to get the token for Oauth using the official docs request:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id='my client id'
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&code='my auth code obtained in previous auth request'
&grant_type=authorization_code
&client_secret='my client secret'
But when we make the request it responds with this error:
AADSTS65001: The user or administrator has not consented to use the application with ID 'mya app id' named 'my app name'. Send an interactive authorization request for this user and resource"
Thing is, we already gave them this permissions on Azure portal AD and app registration even with the admin consent but still:
is there any permission missing there ?, any clue about this ?
I have tried in my environment and got the access token successfully.
Please check whether you followed the same steps as below:
1) Go to Azure portal -> Azure AD -> App registrations -> Your app -> Authentication -> check the below options -> Save.
2) To resolve the error, make sure to grant below Api permissions along with permissions you have given:
3) To get the token, I used postman by giving parameters like below:
4) I successfully got the token like below:
After every change, try refreshing your Azure Portal and Postman.
For more in detail, please refer below links:
Microsoft identity platform and OAuth 2.0 authorization code flow - Microsoft identity platform | Microsoft Docs
azure - AADSTS65001: The user or administrator has not consented to use the application with ID ' - Stack Overflow

Why aren't the application permissions being added to my MS Graph token?

I'm trying to get a subscription created with the callRecord resource (https://learn.microsoft.com/en-us/graph/api/subscription-post-subscriptions?view=graph-rest-beta&tabs=http)
In the app registration section of the Azure portal, I've created a multi-tenant app with a client secret. That app has permissions for application-level "CallRecords.Read.All" as well as the default delegated "User.Read". The statuses also have a green checkbox for being granted against my organization by an admin.
I am able to get an access token with the following HTTP POST request to https://login.microsoftonline.com/common/oauth2/v2.0/token:
grant_type:authorization_code
scope:https://graph.microsoft.com/.default
client_secret:<client_secret>
client_id:<client_id>
code:<code>
redirect_uri:http://localhost:3000
However, that token is not able to generate a subscription to my callRecord resource. I get a response with this message: "Operation: Create; Exception: [Status Code: Forbidden; Reason: The request is not authorized for this user or application.]"
The message suggests that the app has not been granted admin-level authorization, but in fact it has. This used to work for me. I'm wondering if there has been a regression on the MS Graph side.
Further, when I examine the JWT, I see that the scope is "User.Read profile openid email". There is no mention of the application-level permission (specifically, CallRecords.Read.All)
Thanks.
Because when you use the auth code flow, just the Delegated permission will take effect. So even if you grant the Application permission, the token you got will not include the permission.
From the doc, to call this API Get callRecord, just the Application permission is supported.
To get the token which include the permission, your option is to use the client credential flow.
Note: You need to use <tenant-id> instead of common in this flow.
POST https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token
client_id=xxxxxxx
&scope=https://graph.microsoft.com/.default
&client_secret=xxxxxxx
&grant_type=client_credentials
Decode the token in https://jwt.io, the roles includes the CallRecords.Read.All permission:

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.

Authorization_IdentityNotFound Error while accessing graph API

I have searched with the error which I found, Did not find any matching questions. So posting question. Appreciate if some one provides some pointers to proceed.
My goal is to access graph API in my desktop client. I have started using fiddler to experiment.
I have followed instructions provided at https://graph.microsoft.io/en-us/docs/authorization/app_only
registered Web APP using Application Registration portal using my Microsoft work account.
Provided 'Read all users' full profiles in Delegated permissions
Requested token and Used the token in Authorization header to call the graph API, Getting following error.
https://graph.microsoft.com/v1.0/users
119
{
"error": {
"code": "Authorization_IdentityNotFound",
"message": "The identity of the calling application could not be established.",
"innerError": {
"request-id": "4c3a7bc6-e3d8-453c-adc9-5a12fec3b0ee",
"date": "2016-05-11T00:46:23"
}
}
}
In my case, I got the same error after I used Quickstart (step 1), then configured automatically .net sample (step 2), then download the code sample (step 3) as shown in the picture below.
All steps was done successfully except step 3. Microsoft code generate, generate app id, and app secret in project successfully but the tenant was set to common in appsetting.json as seen in image below.
I thought it was a valid thing, but later found out that this caused the issue.
Solution:
I copied the Directory (tenant) ID, than replace common with tenant Id, and it worked. I am not sure if this is a bug in Azure Quickstart code generation.
This sample helped me understand the flows around app-only permissions.
https://blogs.msdn.microsoft.com/tsmatsuz/2016/10/07/application-permission-with-v2-endpoint-and-microsoft-graph/
Key takeaways for me:
Ensure you set up the app and specify the Application Permissions needed
Do have an admin grant the app permission to run against the relevant directory.
Get the relevant token:
Notice the scope in the request below is https://graph.microsoft.com/.default
POST https://login.microsoftonline.com/{tenantname}.onmicrosoft.com/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials&client_id=6abf3364-0a60-4603-8276-e9abb0d843d6&client_secret=JfgrNM9CcW...&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default
Use the token to request the relevant graph resource, eg:
GET https://graph.microsoft.com/v1.0/users/demouser01#[tenant-name].onmicrosoft.com/drive/root/children
Accept: application/json
Authorization: Bearer eyJ0eXAiOi
For me, I had not given admin consent. This is a critical step. My mistake was in thinking that by granting the app permissions, this was giving admin consent, but its not the same thing.
From step 3 on this site: https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_service
I just pasted their call into a browser after filling in the tenant and client id, then signed in, and everything worked.
GET https://login.microsoftonline.com/{tenant}/adminconsent
?client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
&redirect_uri=http://localhost/myapp/permissions
while generating new access token, make sure to replace tenant_id with the actual tenant id
https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token
You'll find that this document is a better set of instructions for app-only apps.
There are two issues from your description that stand out.
You'll need to make the call with an X509 certificate for app-only flows.
You need to set up app scopes, rather than delegated scopes on your app - delegated scopes are for delegate flows rather than app-only flows.

Resources