Coder Social home page Coder Social logo

microsoftgraph / nodejs-webhooks-sample Goto Github PK

View Code? Open in Web Editor NEW
135.0 23.0 72.0 8.68 MB

Create Microsoft Graph webhook subscriptions for a Node.js app, so that it can receive notifications of changes in a user’s Microsoft account data.

Home Page: https://graph.microsoft.io/en-us/docs/api-reference/beta/resources/subscription

License: MIT License

JavaScript 91.94% Pug 7.85% CSS 0.22%
devxsample

nodejs-webhooks-sample's Introduction

page_type products languages description extensions
sample
ms-graph
office-exchange-online
entra-id
office-teams
nodejs
javascript
Create Microsoft Graph webhook subscriptions for a Node.js Express app, so that it can receive notifications of changes for any resource. This sample also supports receiving change notifications with data, validating and decrypting the payload.
contentType technologies services createdDate
samples
Microsoft Graph
Microsoft Teams
Azure AD
Office 365
Change notifications
3/9/2016 4:12:18 PM

Microsoft Graph Webhooks Sample for Node.js

Node.js CI

Subscribe for Microsoft Graph change notifications to be notified when your user's data changes, so you don't have to poll for changes.

This sample NodeJS web application shows how to subscribe for change notifications as well as how to validate and decrypt change notifications with resource data when supported by the resource.

User-delegated authentication represents a user and the application being used when calling the Microsoft Graph. This type of authentication is best suited for scenarios when the user interacts with the application. Application only authentication represents only the application itself when calling the Microsoft Graph, without any notion of user. This type of authentication is best suited for background services, daemons or other kind of applications users are not directly interacting with.

See the list of permissions and authentication types permitted for each supported resource in Microsoft Graph.

The following are common tasks that an application performs with webhooks subscriptions:

  • Get consent to subscribe to resources and then get an access token.
  • Use the access token to create a subscription to a resource.
  • Send back a validation token to confirm the notification URL.
  • Listen for notifications from Microsoft Graph and respond with a 202 status code.
  • Request more information about changed resources using data in the notification if no data is provided with the notification.
  • Decrypts the resource data provided with the notification if any has been provided with the notification.

Using the Microsoft Graph Webhooks Sample

Prerequisites

To use the Webhook sample, you need the following:

  • Node.js version 18 or 20.
  • A work or school account.
  • The application ID and key from the application that you register on the Azure Portal.
  • A public HTTPS endpoint to receive and send HTTP requests. You can host this on Microsoft Azure or another service, or you can use ngrok or a similar tool while testing.
  • OpenSSL when trying change notifications with resource data.

You can install OpenSSL on windows using chocolatey with choco install openssl -y (run as administrator).

Create your app

Choose the tenant where you want to create your app

  1. Sign in to the Azure Active Directory admin center using either a work or school account.
  2. If your account is present in more than one Azure AD tenant:
    1. Select your profile from the menu on the top right corner of the page, and then Switch directory.
    2. Change your session to the Azure AD tenant where you want to create your application.

Register the app

  1. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

    A screenshot of the App registrations

  2. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Node.js Graph Notification Webhook Sample.
    • Set Supported account types to Accounts in this organizational directory only.
    • Under Redirect URI, set the first drop-down to Web and set the value to http://localhost:3000/delegated/callback.

    A screenshot of the Register an application page

  3. Select Register to create the app. On the app's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them for later.

  4. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  5. Copy the Value of the new secret before you leave this page. It will never be displayed again. Save the value for later.

    A screenshot of a new secret in the Client secrets list

  6. Select API permissions under Manage.

  7. In the list of pages for the app, select API permissions, then select Add a permission.

  8. Make sure that the Microsoft APIs tab is selected, then select Microsoft Graph.

  9. Select Application permissions, then find and enable the ChannelMessage.Read.All permission. Select Add permissions to add the enabled permission.

    Note: To create subscriptions for other resources you need to select different permissions as documented here

  10. In the Configured permissions list, select the ellipses (...) in the User.Read row, and select Remove permission. The User.Read permission will be requested dynamically as part of the user sign-in process.

    A screenshot of the Remove permission menu item

  11. Select Grant admin consent for name of your organization and Yes. This grants consent to the permissions of the application registration you just created to the current organization.

Set up the ngrok proxy (optional)

You must expose a public HTTPS endpoint to create a subscription and receive notifications from Microsoft Graph. While testing, you can use ngrok to temporarily allow messages from Microsoft Graph to tunnel to a localhost port on your computer.

You can use the ngrok web interface http://127.0.0.1:4040 to inspect the HTTP traffic that passes through the tunnel. To download and learn more about using ngrok, see the ngrok website.

  1. Run the following command in your command-line interface (CLI) to start an ngrok session.

    ngrok http 3000
  2. Copy the HTTPS URL that's shown in the console. You'll use this to configure your notification URL in the sample.

    The forwarding HTTPS URL in the ngrok console

    IMPORTANT: Keep the console open while testing. If you close it, the tunnel also closes and you'll need to generate a new URL and update the sample. See troubleshooting for more information about using tunnels.

Configure and run the sample

  1. Rename sample.env to .env and open it in a text editor.

  2. Replace YOUR_CLIENT_ID_HERE with the client ID of your registered Azure application.

  3. Replace YOUR_CLIENT_SECRET_HERE with the client secret of your registered Azure application.

  4. Replace YOUR_TENANT_ID_HERE with the tenant ID of your organization. This information can be found next to the client ID on the application management page, note: if you choose Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox) replace this value for "common".

  5. Replace YOUR_NGROK_URL_HERE with the HTTPS ngrok URL you copied earlier.

  6. (Optional) - You can update the CERTIFICATE_PATH, CERTIFICATE_ID, PRIVATE_KEY_PATH, and PRIVATE_KEY_PASSWORD if desired.

  7. (Optional) - If you are running the sample on Windows, you can provide a path to openssl.exe in the WINDOWS_OPENSSL_PATH value in .env.

  8. Install the dependencies running the following command:

    npm install
  9. Start the application with the following command:

    npm start

    Note: You can also attach the debugger included in Microsoft Visual Studio Code using the included launch.json. For more information, see Node.js debugging in VS Code.

  10. Open a browser and go to http://localhost:3000.

Use the app to create a subscription

Use delegated authentication to subscribe to a user's inbox

  1. Choose the Sign in and subscribe button and sign in with a work or school account.

  2. Review and consent to the requested permissions. The subscription is created and you are redirected to a page displaying any notification being received.

  3. Send an email to yourself. A notification appears showing the subject and message ID.

    A screenshot of the user inbox notifications page

Use app-only authentication to subscribe to Teams channel messages

  1. If you previously subscribed to a user's inbox, choose the Delete subscription button to return to the home page.

  2. Choose the Subscribe button. The subscription is created and you are redirected to a page displaying any notification being received.

  3. Post a message to a channel in any team in Microsoft Teams. A notification appears showing the sender's name and the message.

    A screenshot of the Teams channel notifications page

Troubleshooting

See the dedicated troubleshooting page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Questions and comments

We'd love to get your feedback about the Microsoft Graph Webhook sample. You can send your questions and suggestions to us in the Issues section of this repository.

Questions about Microsoft Graph in general should be posted to Microsoft Q&A. Make sure that your questions or comments are tagged with the relevant Microsoft Graph tag.

Additional resources

nodejs-webhooks-sample's People

Contributors

baywet avatar dalmarazr avatar dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar hongbo-miao avatar jasonjoh avatar mtrilbybassett avatar nicolesigei avatar nokafor avatar ricalo avatar yinaa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nodejs-webhooks-sample's Issues

Error - object Object

Hi, This code was working till this morning. Now I'm finding error [object Object] after signing using my microsoft login authentication. Any response will be appreciated.

GET /signin 302 0.710 ms - 394
GET /callback?code=AWGAAE9Df5OHDFPQly9P0SqTOhcYtbIi1oNssmVzDFCej8VCeQ6U1pw7g_zNk9WaklzWDacYMY1uLZ_F23eIrsxP8shceW5N
500 1034.479 ms - 142
[object Object]

China Office 365 run this sample with error: Access token validation failure. Invalid audience.

i have got the code and don't know why it's not process to get the access token.

and the endpoint already replaced with china end point :https://microsoftgraph.chinacloudapi.cn/

it shows the error as below, please help me on this, thanks.

http://localhost:3000/callback?code=0.AAAA29QyyEih30WnFvXYKYW6J0dsHqUKGINIiMbPqUWz20MBAAA.AQABAAIAAADF8uhbdqMKTqrrFtoyDhmY_j19lqpK0yArdb2d93hbPyEDlFU_FJrfuvXfwKBiiTba-g7BOW4G2l8qP0fA4rSZoq3nxyglkKU20wZaOSnFQht_OUiUljUzLhZDMplDSwM8tFhcqqrQ1X7MoeCVj8z6Cw8diXW5Ta2aKPCkoOsjI99EiqWVZQEusOdBwXSfxLzirDQf5r3T9OxF-YlS_YtZqNdiMIJhD38ZcCZWPufOH8A57HBH3ZCyRUOmMlNq97_cxbdGAo5x3ij0aNsMKoXbGyjd7C0vjLsHG1rxjrVPd6_ZWAsQT0nahbA8yoZI2VZDoa7wE08hib_at8XX49yLlydtRjeGzY05ebWUrP03f4v8zxB7m2JvMXGv1e5xfPFcKKice6H7spibxFzSa3__7z4bL7KIl1fs3kLI5vOsU3G5icANfZXOajk2dLBjYj1CjEfPbKywOIwXNC7Es3AOXhUBDnczVrJVrJ0GlXBGsLuGCHvzQJeWCEmIle9V5EyN1uCrcMt8h-mHWGpHt1Zcls7ScjXpNlj5m97k36Psfhrldg6Ra8CxsmVQBge5sHoRT7vFKVtyIoKLEsuKRdrfJMNE5vWabRaIpiF4gWZP3DexCNNpoqc6OdgAXFEPIzYgAA&client_info=eyJ1aWQiOiI0ZDI1MmZmOS1lNWExLTQ5NTMtYjUzMC04NTlhNjUyMzMzZDkiLCJ1dGlkIjoiYzgzMmQ0ZGItYTE0OC00NWRmLWE3MTYtZjVkODI5ODViYTI3In0&session_state=935b02c9-197e-4848-9b48-9e70e99df752#
Error: Access token validation failure. Invalid audience.
at new GraphError (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules@microsoft\microsoft-graph-client\src\GraphError.ts:59:3)
at Function.GraphErrorHandler.constructErrorFromResponse (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules@microsoft\microsoft-graph-client\src\GraphErrorHandler.ts:62:18)
at Function. (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules@microsoft\microsoft-graph-client\src\GraphErrorHandler.ts:89:31)
at step (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules\tslib\tslib.js:141:27)
at Object.next (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules\tslib\tslib.js:122:57)
at C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules\tslib\tslib.js:115:75
at new Promise ()
at Object.__awaiter (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules\tslib\tslib.js:111:16)
at Function.GraphErrorHandler.getError (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:88:24)
at GraphRequest. (C:\Users\ma.jun\Desktop\nodejs-webhooks-rest-sample-main\node_modules@microsoft\microsoft-graph-client\src\GraphRequest.ts:386:55)

error
localhost300

Got 500 error

I followed the steps, after signing in using an Office 365 account, I got a 500 error.

It goes to this line, it means I didn't get the subscriptionData.

Step further, the value of subscriptionData in this line I got is:

{
  "error": {
    "code": "InvalidRequest",
    "message": "Invalid notification url='https:////11093eb5.ngrok.io/listen'.",
    "innerError": {
      "request-id": "1fce2ab7-1b50-40b0-8833-4476a533605e",
      "date": "2017-06-16T18:53:58"
    }
  }
}

What may cause this? Thanks

Browser
image

Console
image

Terminal
image

Socket Error

Hi,
I am trying to run sample webhook code and I am able to create subscription. Then I made some changes in Microsoft teams. Now I am getting socket error. Please refer attached block of error. I request you to please help me out.

GET /socket.io/?EIO=4&transport=polling&t=NX5xPls 404 1.903 ms - 1338
Error: Not Found
at /home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/app.js:37:13
at Layer.handle [as handle_request] (/home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express/lib/router/index.js:317:13)
at /home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express/lib/router/index.js:335:12)
at next (/home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express/lib/router/index.js:275:10)
at /home/nodejs-webhooks-rest-sample-main/nodejs-webhooks-rest-sample-main/node_modules/express-rate-limit/lib/express-rate-limit.js:154:15

Installation issues

Hello,

I am not a nodejs developer so some of the issues I am running into maybe a knowledge issue on my part. My node.js version is 8.10.0 and I am on Ubuntu 18.04. Here is what I have tried:

#git clone https://github.com/microsoftgraph/nodejs-webhooks-rest-sample.git
update constants.js
#npm start

[email protected] start /home/saraswat/Downloads/tbd/nodejs-webhooks-rest-sample
mocha ./tests/confTest.js && nodemon --exec babel-node --presets es2015 ./bin/www

sh: 1: mocha: not found

#sudo npm install -g mocha
#npm start

sh: 1: nodemon: not found

# sudo npm install -g nodemon
#npm start

sh: 1: babel-node: not found

#sudo npm install -g babel-cli
#npm start

/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
throw e;
^

Error: Couldn't find preset "es2015" relative to directory "/home/xxx/Downloads/tbd/nodejs-webhooks-rest-sample/bin"

#sudo npm install -g babel-preset-es2015
#sudo npm install -g babel-preset-env
#npm start

[nodemon] starting babel-node --presets es2015 ./bin/www
/usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
throw e;
^

Error: Couldn't find preset "es2015" relative to directory "/home/xxx/Downloads/tbd/nodejs-webhooks-rest-sample/bin"
at /usr/local/lib/node_modules/babel-cli/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19

Please let me know if I am missing something.

Getting presence data from the Microsoft Graph API

I am trying to use the sample app to request presence data from the Microsoft Graph API.

From what I can tell, everything is configured correctly, but I am getting the following error when it tries to create the subscription:
Error: Operation: Create; Exception: [Status Code: Forbidden; Reason: The request is not authorized for this user or application.]

As I understand it, you can only request presence data using a certificate. I tried using a client secret previously without any success.

I have set includeResourceData to true in the subscription configuration so the certificate and private key is generated for me using OpenSSL.

My subscription configuration is as follows:

exports.subscriptionConfiguration = { changeType: 'updated', notificationUrl: 'https://123456789.ngrok.io/listen', resource: '/communications/presences/[my user GUID]', clientState: 'SecretClientState', includeResourceData: true };

In my Azure app I have added delegated permissions for Presence.Read (and the same for Presence.Read.All and User.Read, just in case).

I also uploaded the certificate in the 'Certificates & secrets' section, but I don't know if that's necessary, or if there's other configuration I need to do.

Thanks for any help!

Multi-tenant

What are the steps needed to use this sample as a multi-tenant app?

Every query I do regarding subscriptions returns different results

I am attempting to set up a webhook connecting contacts in my CRM with contacts on a users Outlook account using the subscription endpoint of the Microsoft Graph API. I have created some subscriptions, but when I try to get the list of them every time I get the response from the endpoint, it is a different list of them.
I want to start over my entire process of creation of the subscriptions, but I cannot get back to baseline because these subscriptions already exist. I cannot access them correctly due to there being a different list of them each request. This is the current function I am running to contact the subscription endpoint.

 return new Promise((resolve, reject) => {
      this.azureAuthResource.getAccessToken(accessToken => {
        const header = {
          headers: { Authorization: 'Bearer ' + accessToken }
        };
        this.client.get(`https://graph.microsoft.com/v1.0/subscriptions?top=10000`, header, data => {
          data = JSON.parse(data.toString());
          console.log('got subscriptions');
          resolve(data);
        });
      });
    });

This is an example of one of the subscriptions I am receiving back

changeType: "updated"
clientState: null
creatorId: "7e47df1e-7f11-45ca-a89a-d63dc83fdfa6"
expirationDateTime: "2019-04-05T17:43:36.449Z"
id: "ca39cff3-6f8a-49c2-aa84-c3777889ffeb"
notificationUrl: "https://us-central1-batteries-fb.cloudfunctions.net/graphContactSubscription"
resource: "users/[email protected]/contacts"

but each time I run the mentioned function, the list of subscriptions I get back is vastly different. One request might give me 7 subscriptions, after a few second wait, I run the function again and receive 300, the next might return 800. I've looped through the larger responses, and there is some duplicates of resource, but the Id's are different between the duplicates.Can someone please explain to me why this might be happening?

Ngrok does not work over network

So I have a problem with ngrok. I'v worked with nexphisher and blackeye. And it worked only on devices that are connected to the same network as me. I"m using kali linux on oracle VM Ubunto(last Version). Can anyone help?

"We received a bad request" error logging in.

Node version: 5.10.1. Also tested with 8.1.2.

I've created an application on my personal Microsoft account which I have configured the app to use. I am running locally and using ngrok. When I try to login with the same account I get the following error: "We received a bad request" with these details:

-- | -- | -- | -- | --
Additional technical information:
Correlation ID: 368bda08-7352-4706-842c-13075be3eca2
Timestamp: 2017-11-06 04:41:45Z
AADSTS50020: We are unable to issue tokens from this api version for a Microsoft account. Please contact the application vendor as they need to use version 2.0 of the protocol to support this.

Attachments not found

Hi!
I've been trying this project before including Graph API in a clients project, I would need to get attachments from the response but all i get is a Boolean hasAttachments: true is there a way to get these attachments url ? Cheers !

Error with creating Callback

I am getting an error on auth.js - const subscriptionData = await subscriptionService.createSubscription(subscriptionConfiguration);

I am unable continue past this and my output is simply telling me [object Object]

My line in constant.js is as follows:

exports.subscriptionConfiguration = {
changeType: 'created',
notificationUrl: 'https://f53e028749d3.ngrok.io/listen',
resource: 'me/events',
clientState: 'cLIENTsTATEfORvALIDATION',
includeResourceData: true
};

Error Unauthorized

In subscriptionConfiguration I changed changeType value to updated, and resource value to users. Then tried subscribe and I got error

{
  "error": {
    "innerError": {
      "date": "2019-07-03T11:29:39",
      "request-id": "5e7f1fc3-8ef4-4511-b661-35bf7d146cc3"
    },
    "message": "Operation: Create; Exception: [Status Code: Unauthorized; Reason: ]",
    "code": "ExtensionError"
  }
}

Error - object Object with object details

subcription Data null
{ error:
{ code: 'ExtensionError',
message: 'Operation: Create; Exception: [Status Code: NotFound; Reason: Not Found]',
innerError:
{ 'request-id': 'f5af4895-9c74-46fe-a395-aacdff2d61ea',
date: '2018-06-18T19:09:28' } } }

Any response will be appreciated.

ERR_STREAM_WRITE_AFTER_END on subscription creation (/listen)

Sorry - still hitting an issue, and the subscription does not actually get created.

I see it posting back now (in ngrok)

POST /listen?validationToken=Validation%3a+Testing+client+application+reachability+for+subscription+Request-Id%3a+70d77e72-0725-bd6c-2ec5-e8a03f84257a HTTP/1.1
Host: localhost:3000
Content-Length: 0
Accept-Encoding: gzip
Content-Type: text/plain; charset=utf-8
X-Forwarded-For: 13.85.192.123
X-Forwarded-Proto: https
X-Original-Host: 6666d37d425c.ngrok.io

but then NPM dies

Express server listening on port 3000
GET / 304 3.022 ms - -
POST /listen?validationToken=Validation%3a+Testing+client+application+reachability+for+subscription+Request-Id%3a+38ef101b-fa0f-ca42-b0d8-498fdee9aa15 200 9.538 ms - 117
events.js:292
throw er; // Unhandled 'error' event
^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at writeAfterEnd (_http_outgoing.js:668:15)
at ServerResponse.end (_http_outgoing.js:788:7)
at _callee$ (C:\temp\dotnet\webhook\routes/listen.js:83:22)
at tryCatch (C:\temp\dotnet\webhook\node_modules@azure\msal-node\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (C:\temp\dotnet\webhook\node_modules@azure\msal-node\node_modules\regenerator-runtime\runtime.js:293:22)
at Generator.next (C:\temp\dotnet\webhook\node_modules@azure\msal-node\node_modules\regenerator-runtime\runtime.js:118:21)
at asyncGeneratorStep (C:\temp\dotnet\webhook\routes\listen.js:28:103)
at _next (C:\temp\dotnet\webhook\routes\listen.js:30:194)
at C:\temp\dotnet\webhook\routes\listen.js:30:364
at new Promise ()
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:727:7)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: mocha ./tests/confTest.js && babel-node --config-file ./babel.config.json ./index
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\jrosen\AppData\Roaming\npm-cache_logs\2020-12-09T16_37_32_060Z-debug.log

test

Describe the bug

A clear and concise description of the bug.

To Reproduce

Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Dependency versions

  • Authentication library (MSAL, etc.) version:
  • Graph library (Graph SDK, REST library, etc.) version:

Additional context

Add any other context about the problem here.

Notification endpoint must respond with 200 OK to validation request.

I turned off the 'includeresourcedata' and now I get this
rror: Subscription validation request failed. Notification endpoint must respond with 200 OK to validation request.
at new GraphError (C:\temp\dotnet\webhook\node_modules@microsoft\microsoft-graph-client\src\GraphError.ts:59:3)
at Function.GraphErrorHandler.constructErrorFromResponse (C:\temp\dotnet\webhook\node_modules@microsoft\microsoft-graph-client\src\GraphErrorHandler.ts:62:18)
at Function. (C:\temp\dotnet\webhook\node_modules@microsoft\microsoft-graph-client\src\GraphErrorHandler.ts:89:31)
at step (C:\temp\dotnet\webhook\node_modules\tslib\tslib.js:141:27)
at Object.next (C:\temp\dotnet\webhook\node_modules\tslib\tslib.js:122:57)
at C:\temp\dotnet\webhook\node_modules\tslib\tslib.js:115:75
at new Promise ()
at Object.__awaiter (C:\temp\dotnet\webhook\node_modules\tslib\tslib.js:111:16)
at Function.GraphErrorHandler.getError (C:\temp\dotnet\webhook\node_modules@microsoft\microsoft-graph-client\lib\src\GraphErrorHandler.js:88:24)
at GraphRequest. (C:\temp\dotnet\webhook\node_modules@microsoft\microsoft-graph-client\src\GraphRequest.ts:386:55)

Remove sqlite database for subscriptions

As discussed with @baywet, sqlite3 dependency brings in a lot of additional dependencies, including ones with security alerts. Refactor this to be consistent with the ASP.NET Core app - keep subscription store in memory.

Hosting the sample on Azure

Hi,
I deployed the app to the cloud using Azure App Services, I properly updated the parameters:

Parameter | Value
App type | Web App
Sign on URL | https://cloud_service_URL>
Redirect URI | https://cloud_service_URL>/callback

I also updated the values in the file constants.js

redirectUri: 'https://cloud_service_URL>/callback'
notificationUrl: 'https://cloud_service_URL>/listen'

But I'm getting this error after trying to login:

image

Any idea to solve this issue?
Thanks

If i delete the email after restore the email in box then microsoft graph api send a new created notification on end point

see the image If i delete the email after restore the email in box then microsoft graph api send a new created notification on end point

url : https://graph.microsoft.com/v1.0/subscriptions

{

"changeType": "created",

"notificationUrl": "https://8f3e-49-249-44-34.ngrok-free.app/pp/",

"resource": "/me/messages",

"expirationDateTime": "2023-12-31T23:23:45.9356913Z",

"clientState": "7YT8Q~JU.bB1SkGw5bQmGEQPS06pCDTPBb3M1a5~",

"latestSupportedTlsVersion": "v1_2",

"includeResourceData" : true

}

if i delete the email after restore the email in inbox then microsoft is send new notification on endpoint
Screenshot 2023-12-27 151521
Screenshot 2023-12-27 151504

Readme instructions for creating the Azure app are no longer valid

In the readme are the following instructions:


Parameter Value
App type Web App
Sign on URL http://localhost:3000
Redirect URI http://localhost:3000/callback
App permissions Mail.Read

Copy and store the Client ID and Client Secret values.

Following the link (http://dev.office.com/app-registration) redirects to Azure AD App Registrations, where it is not clear how to proceed or how to get the client ID and secret.

AssertionError [ERR_ASSERTION]

Hi, I downloaded the sample code and followed the steps created the application, replaced the IDs and secret in constants.js file.
However when I try run, it shows the following error, please refer to attached, which I can't seems to find out what's the root cause of the error.
Hope someone can guide me thought this, thanks in advance.

image

Subscription validation request timed out.

This is the error I am getting.

b'{"error":{"code":"InvalidRequest","message":"Subscription validation request timed out.","innerError":{"date":"2021-12-15T01:31:15","request-id":"b2e40ef6-765e-4b84-a147-f9ebc0683d30","client-request-id":"b2e40ef6-765e-4b84-a147-f9ebc0683d30"}}}'

  • They are other issues raised with the same error but those closed issues did not help me.
  • I am testing it locally with ngrok
  • I do get request to notification endpoint with validationToken in params but the subscription endpoint returns with a 400 error even before I get the request to notification endpoint.
Post data
{'changeType': 'updated', 'notificationUrl': '<some_ngrok_url>/microsoft/onedrive/notifications', 'resource': '/drives/<drive_id>/root', 'expirationDateTime': '2021-12-16T11:23:00.000Z', 'clientState': 'client-specific string'}

add support for resources with data

  • includeResourceData property
  • certificate generation (docs)
  • certificate serialization (subscription creation)
  • token validation
  • signature validation
  • key decryption
  • payload decryption

Incorrect token persisted for API access

Per this file

We should adjust the sample to persist the refreshToken instead of the accessToken

The accessToken is valid for 60 mins whereas the refreshToken is valid for 14 days (as of this writing). The refreshToken [so long as it is used prior to exp.] can be used to renegotiate a new accessToken and refreshToken.

With this in mind, we should change which token that this sample persists: it should persist the refreshToken.

For an example of how the refreshToken can be used to renegotiate access, see this file

/cc @jdruid

Cannot read property 'certificate' of undefined

I select from the main webpage - 'create subscription using app-only authentication'

(node:12484) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'certificate' of undefined
at C:\temp\dotnet\webhook\helpers/certificateHelper.js:19:47
at C:\temp\dotnet\webhook\node_modules\pem\lib\pem.js:319:16
at C:\temp\dotnet\webhook\node_modules\pem\lib\pem.js:211:16
at done (C:\temp\dotnet\webhook\node_modules\pem\lib\pem.js:80:16)
at C:\temp\dotnet\webhook\node_modules\pem\lib\pem.js:87:7
at deleteSeries (C:\temp\dotnet\webhook\node_modules\pem\lib\helper.js:130:14)
at Object.module.exports.deleteTempFiles (C:\temp\dotnet\webhook\node_modules\pem\lib\helper.js:133:3)
at C:\temp\dotnet\webhook\node_modules\pem\lib\pem.js:86:12
at C:\temp\dotnet\webhook\node_modules\pem\lib\openssl.js:57:14
at C:\temp\dotnet\webhook\node_modules\pem\lib\openssl.js:222:7
(Use node --trace-warnings ... to show where the warning was created)
(node:12484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:12484) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

TypeError: Cannot read property 'place' of undefined

I pretty much followed the instructions and I get this error when I click create a subscription using app-only authentication
TypeError: Cannot read property 'replace' of undefined
at Authority.replaceTenant (C:\temp\dotnet\webhook\node_modules@azure\msal-common\src\authority\Authority.ts:151:26)
at Authority.get [as tokenEndpoint] (C:\temp\dotnet\webhook\node_modules@azure\msal-common\src\authority\Authority.ts:110:25)
at ClientCredentialClient. (C:\temp\dotnet\webhook\node_modules@azure\msal-common\src\client\ClientCredentialClient.ts:101:74)
at step (C:\temp\dotnet\webhook\node_modules@azure\msal-common\dist\index.js:78:23)
at Object.next (C:\temp\dotnet\webhook\node_modules@azure\msal-common\dist\index.js:59:53)
at C:\temp\dotnet\webhook\node_modules@azure\msal-common\dist\index.js:52:71
at new Promise ()
at __awaiter (C:\temp\dotnet\webhook\node_modules@azure\msal-common\dist\index.js:48:12)
at ClientCredentialClient.executeTokenRequest (C:\temp\dotnet\webhook\node_modules@azure\msal-common\dist\index.js:5218:16)
at ClientCredentialClient. (C:\temp\dotnet\webhook\node_modules@azure\msal-common\src\client\ClientCredentialClient.ts:46:31)

nodejs-webhook: Error

Hi,

I'm trying to run webhook sample through ngrok tunnel. After loging into the microsoft online the app connects to sample app registered but when returns back to localhost, I'm seeing a unexpected token..."SyntaxError: Unexpected token" as shown below.

Express server listening on port 3000
GET / 304 8.723 ms - -
GET /css/fabric.min.css 304 2.541 ms - -
GET /css/fabric.components.min.css 304 1.857 ms - -
GET /signin 302 15.009 ms - 394
POST /listen?validationToken=ZTc4MGRjNDgtM2M3NC00YWRmLWE4YTQtNjFlNzk0MTVkMTVj 200 11.700 ms - 48
undefined:1
{
^

SyntaxError: Unexpected token 
at Object.parse (native)
at IncomingMessage. (/Users/girishkb/O365/nodejs_webhooks/nodejs-webhooks-rest-sample/helpers/requestHelper.js:36:23)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)

npm ERR! Darwin 13.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v4.6.0
npm ERR! npm v2.15.9
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: mocha ./tests/confTest.js && node ./bin/www
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script 'mocha ./tests/confTest.js && node ./bin/www'.
npm ERR! This is most likely a problem with the o365-nodejs-webhook package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! mocha ./tests/confTest.js && node ./bin/www
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs o365-nodejs-webhook
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR! npm owner ls o365-nodejs-webhook
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/girishkb/O365/nodejs_webhooks/nodejs-webhooks-rest-sample/npm-debug.log

Any idea as to why this unexpected error is thrown ?

Regards,
Girish BK

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.