"Subscription validation request failed. Response must exactly match validationToken query parameter." - microsoft-graph-api

I have the requirement to enable a subscription for change notifications for OneDrive (me/drive/SharedWithMe) but it is giving error when I post the payload.
When I change the resource to OneDrive( me/drive/root) which Microsoft API recommends for subscriptions but that also giving error.
I set up the API permission for the app. Few of the application permission which needs admin consent but could not be done for the current user. User grants are given below.
I have created ngrok URL to redirect webserver http://localhost:5000 /notify to ngrok URL. This is mentioned in the payload for posting for a new subscription. Python code also is given below.
I want to know what is the prerequisite for the enabling subscription. Please provide light on license requirement, API permission and scopes, resource group, and azure key vault. This requirement is for OneDrive storage subscription.
Document referenced:
https://learn.microsoft.com/en-us/samples/microsoftgraph/aspnetcore-webhook-with-resource-data/sample-application---microsoft-graph-change-notifications/
When we are posting the payload for new subscriptions, it is giving error.
payload:
{
"changeType": "updated",
"notificationUrl": "https://d76209350b89.ngrok.io/notify",
"resource": "me/drive/root",
"expirationDateTime": "2020-07-24T18:23:45.9356913Z",
"clientState": "secretClientValue",
"latestSupportedTlsVersion": "v1_2"
}
subscriptions:
https://graph.microsoft.com/v1.0/subscriptions
{
"error": {
"code": "InvalidRequest",
"message": "Subscription validation request failed. Response must exactly match validationToken query parameter.",
"innerError": {
"date": "2020-07-22T16:45:41",
"request-id": "d5d7f05b-9f3d-44a9-a74a-9f21e3c8a9ba"
}
}
}
Endpoint that receives the validation request
enter code here:
http_header={'Authorization':f'Bearer
{token_response["accessToken"]}','Content-type':'application/json'}
print(http_header)
post_data={
"changeType": "updated",
"notificationUrl": REDIRECT_URI_2,
"resource": "me/drive/root",
"expirationDateTime": "2020-07-22T18:23:45.9356913Z",
"clientState": "secretClientValue",
"latestSupportedTlsVersion": "v1_2"
}
res=requests.post('https://graph.microsoft.com/v1.0/subscriptions',headers=http_header,data=post_data)
Receives the change notifications
#app.route("/notify",methods=['GET','POST'])
def onedrive():
valtoken=flask.request.args.get('validationToken')
valtok=valtoken.replace(':','%3a')
valt=valtok.replace(' ','+')
subscribe_url = f'https://062dece903f6.ngrok.io/notify?validationToken={valt} HTTP/1.1'
resp = flask.Response(status=200)
resp.headers['content-type']="plain/text"
resp.headers['token']=valt
resp.headers['location'] = subscribe_url
return resp
I am developing in Python. Anyone has done this before please share.
Thanks.

The content type should be text/plain. The validation token value should be returned as the response body and not a header. There's no need for a location header.
Also: I'm not sure why you are replacing characters but you should simply url decode and return as is.

valtoken=request.args.get('validationToken')
resp=app.response_class(valtoken,status=200,content_type="text/plain")
return resp

#app.route("/notify",methods=['POST'])
def onedrive():
valtoken=flask.request.args.get('validationToken')
resp=app.response_class(response=urllib.parse.unquote(valtoken),status=200,mimetype='plain/text')
return resp

Related

microsoft Graph API for subscription throwing wrong message and not creating subscription

I am using Microsoft graph API and trying to create a subscription on the Microsoft developer portal.
https://graph.microsoft.com/v1.0/subscriptions I am hitting this URL with post request call as shown below
`
import requests
access_token = "testtoken"
subscription_data = {
"changeType": "created,updated",
"notificationUrl": "WEBHOOK URL",
"resource": "me/contacts",
"expirationDateTime": '2023-01-16T16:58:00.0000000Z'
}
headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/xml'
}
try:
response = requests.post(f'https://graph.microsoft.com/v1.0/subscriptions', json=subscription_data, headers=headers)
except Exception as e:
print("error")
Above code is giving wrong message response as
`{
"error": {
"code": "InvalidRequest",
"message": "Could not process subscription creation payload. Are all property names spelled and camelCased properly?Also are the dateTimeOffest properties in a valid internet Date and Time format?",
"innerError": {
"date": "2023-01-14T19:09:17",
"request-id": "6d50105e-08b1-494d-8400-5fc32909a8d1",
"client-request-id": "c89e988f-783b-daf5-7d95-677002b0c22d"
}
}
}
`
As you see all property are in camelcase and date format is also in 8601 iso format,
still getting errors and not able to create a subscription . I also saw similar problem faced and discussed here https://github.com/microsoftgraph/microsoft-graph-docs/issues/3041 however this is also not giving explanations how to solve the problem

Add user in Azure AD using Microsoft Graph API

I am trying to add user using Microsoft graph API.
I have provided the consent for all the permissions required.
POST https://graph.microsoft.com/v1.0/users
Request body that is send to the post request.
{
"accountEnabled": true,
"displayName": "Adele Vance",
"mailNickname": "AdeleV",
"userPrincipalName": "AdeleV#contoso.onmicrosoft.com",
"passwordProfile": {
"forceChangePasswordNextSignIn": true,
"password": "xWwvJ]6NMw+bWH-d"
}
}
Error that is received in response
{
"error": {
"code": "",
"message": "No HTTP resource was found that matches the request URI 'https://outlook.office365.com:444/profile/v1.0/users('CID:0ff49e4749deeaf2')/profile?api-version=AGSV1-internal'.",
"innerError": {
"date": "2021-02-04T10:41:56",
"request-id": "025218e1-191c-464f-adf3-f0cdc5fcebfd",
"client-request-id": "c071d220-2f14-d7fa-956e-cd45ccbdc735"
}
}
}
Is there something that I am missing?
I have also gone through the docs for adding user provided by Microsoft.
https://learn.microsoft.com/en-us/graph/api/user-post-users?view=graph-rest-1.0&tabs=http
What you said in the comment is correct, the document has detailed instructions, it does not support Microsoft personal accounts.
You will have to check the end point are you using to authorize in order to obtain the token.
If you are using a tenant specific end point
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
Try replacing with the common endpoint
https://login.microsoftonline.com/common/oauth....

Create Team, 400 Bad Request, Required functionality is not supported

I'm trying to create a Microsoft Teams team in Migration mode via the Graph API. However I get a 400 response that I can't figure out. The query is shared in the link below.
Shared Query
For those that don't want to view it that way, here is my request:
POST https://graph.microsoft.com/beta/teams
Authorization: Bearer ...
Content-Type: application/json
{
"#microsoft.graph.teamCreationMode": "migration",
"template#odata.bind": "https://graph.microsoft.com/beta/teamsTemplates(\u0027standard\u0027)",
"displayName": "SlackMigrationTest",
"description": "testing slack migrations",
"createdDateTime": "2021-01-14T00:00:00.000Z"
}
I created this based on the microsoft doc here.
The reponse I get is:
The remote server returned an error: (400) Bad Request.
{
"error": {
"code": "BadRequest",
"message": "Required functionality is not supported.",
"innerError": {
"date": "2021-01-20T15:51:21",
"request-id": "dc4189cf-db4a-4a60-a271-f63b5d759a05",
"client-request-id": "dc4189cf-db4a-4a60-a271-f63b5d759a05"
}
}
}
I'm sure its something obvious that I'm missing but any help would be greatly appreciated.
Here you are using the User Context token and trying to make the call. This API call only works in Application context as shown in the below screenshot.
So use Client Credential flow and set Application permissions and then make a call.
As you can see below, it worked for me with App token.
You cannot test it in graph explorer because the Graph Explorer gets user token.

Creating a Microsoft Graph webhook subscription to security/alerts fails

When I attempt to create a Microsoft Graph webhook subscription to the security/alerts endpoint, the subscription creation fails with a generic message as shown below. Modifying the resource to 'me/messages' results in a successful webhook subscription created, so this appears to be specific to the security/alerts endpoint. How do I move past this?
The body of the request is as such:
{
"changeType": "created",
"notificationUrl": "https://xxxxxxxxx.azurewebsites.net/api/graphnotifications",
"resource": "security/alerts?$filter=vendorInformation/provider+eq+'ASC'",
"expirationDateTime": "2018-11-15T11:00:00.0000000Z",
"clientState": "secretClientValue"
}
Please use 'updated' for 'changeType'. Security/Alerts uses 'updated' for all new or updated alerts.
Wes, you didn't post the URL that you sent that request to. As per the documentation for Security Alerts.
You can use Microsoft Graph webhooks to subscribe to and receive notifications about updates to Microsoft Graph Security entities.
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/security-api-overview
On that page, it states posting a request and gives a sample like this
POST https://graph.microsoft.com/v1.0/subscriptions
Content-Type: application/json
{
"changeType": "created,updated",
"notificationUrl": "https://webhook.azurewebsites.net/notificationClient",
"resource": "/me/mailfolders('inbox')/messages",
"expirationDateTime": "2016-03-20T11:00:00.0000000Z",
"clientState": "SecretClientState"
}
https://developer.microsoft.com/en-us/graph/docs/concepts/webhooks
Are you posting that request body to that url?

Microsoft Graph API Beta: Subscribe to Event Notifications of another user

I created an app on https://apps.dev.microsoft.com
with the following Application Permissions:
Calendars.Read (Admin Only) Calendars.ReadWrite (Admin Only) User.Read.All (Admin Only)
Admin Consent
Admin consent was then successfully granted via this URL
https://login.microsoftonline.com/strixtechnology.onmicrosoft.com/adminconsent?client_id=bbb35336-faee-4c10-84b4-34136634db41&state=1234&redirect_uri=https%3A%2F%2Fdashmeetings.com%2Fmicrosoft%2Foauth
Get access token
An access token was then obtained from
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
with headers
Content-Type=application/x-www-form-urlencoded
and body with key-value pairs
grant_type=client_credentials
client_id=bbb35336-faee-4c10-84b4-34136634db41
client_secret=xxx
scope=https://graph.microsoft.com/.default
This returns an access token.
Subscribe to notifications
Using that access token, I then try to subscribe to the events on a certain resource mailbox:
POST https://graph.microsoft.com/beta/subscriptions
with headers
Content-Type=application/json
Authorization=Bearer <access_token_here>
and body
{
"changeType": "created,updated,deleted",
"notificationUrl": "https://dashmeetings.com/microsoft/notify",
"resource": "users/mahogany#strixtechnology.com/events",
"expirationDateTime":"2017-12-01T11:00:00.0000000Z",
"clientState":"1234"
}
This returns a 401 Unauthorized with
{
"error": {
"code": "ExtensionError",
"message": "Operation: Create; Exception: [Status Code: Unauthorized; Reason: Unauthorized]",
"innerError": {
"request-id": "98ce5e5e-1ce4-4417-8c35-456a3cc0e696",
"date": "2017-11-30T10:59:28"
}
}
}
This question seems similar to “Resource not found for the segment” using Graph subscription beta, but I follow the same steps without any luck
The admin consent URL had to be
https://login.microsoftonline.com/common/adminconsent?client‌​_id=bbb35336-faee-4c‌​10-84b4-34136634db41‌​&state=1234&redirect‌​_uri=https%3A%2F%2Fd‌​ashmeetings.com%2Fmi‌​crosoft%2Foauth
and the access token address:
https://login.microsoftonline.com/<tenant_id>/oauth2/v2.0/to‌​ken

Resources