Coder Social home page Coder Social logo

microsoftgraph / aspnet-webhooks-rest-sample Goto Github PK

View Code? Open in Web Editor NEW
42.0 42.0 36.0 3.38 MB

Webhooks in Microsoft Graph notify your web application about changes in user data. You can create a webhook subscription to get notified about changes in user's data. This sample uses the Azure AD endpoint to obtain an access token for work or school accounts.

License: MIT License

C# 5.89% CSS 0.11% ASP 0.02% JavaScript 92.14% HTML 1.85%
devxsample

aspnet-webhooks-rest-sample's People

Contributors

anujab avatar baywet avatar darrelmiller avatar elinorw avatar irvinesunday avatar jasonjoh avatar nokafor avatar o365devx avatar panjkov avatar rexxmagnus avatar ricalo avatar supernova-eng avatar venkateshchepuru 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

Watchers

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

aspnet-webhooks-rest-sample's Issues

Subscription validation request timed out

This is the ruby code I'm using to create a subscription in microsoft graph:

        subscribe_endpoint = URI("https://graph.microsoft.com/v1.0/subscriptions")
        http = Net::HTTP.new(subscribe_endpoint.host, subscribe_endpoint.port)
        http.use_ssl = true
        tomorrow = Date.today + 1

        subscribe_request = "{
          \"changeType\": \"created,updated\",
          \"notificationUrl\": \"https://my_url/api/v1/outlook/o365notification\",
          \"resource\": \"/users/#{params[:o365account_id]}/events?$filter=Extensions/any(f:f/id eq 'Microsoft.OutlookServices.OpenTypeExtension.meeteor_event')\",
          \"expirationDateTime\": #{(Time.now + 1.day).to_json},
          \"clientState\": \"SecretClientState\"
        }"

        subscribe_response = http.post(
            "/v1.0/subscriptions",
            subscribe_request,
            'Authorization' => "Bearer #{params[:o365account_access_token]}",
            'Content-Type' => 'application/json'
        )

it worked great, but suddenly today I'm getting a Subscription validation request timed out response. Altough when I'm doing a POST to https://my_url/api/v1/outlook/o365notification it's just working fine.

Any ideas why it stopped working when nothing changed on my side?

Could it be that, because my_url points on my dev environment and is often offline, the domain got banned?

Confusing/erroneous instructions, plus sign-in loop

In the section where it asks to use the Office 365 app registration tool, the parameters for the tool do not match the parameters in the instructions. For example, the properties on the main page for a registered app in Azure AD only show:

  • Display Name
  • Application Type
  • Home Page
  • Application ID
  • Object ID

The bigger problem though is that the instructions state to "copy and store the returned Client ID and Client Secret values". Where is Client Secret? Is it Object ID? Does Client ID = Application ID? Those are the values I've used for the keys in the web.config file. However, when I run the app I get a repeating loop: Create Registration -> Signin -> Create Registration, etc. It never gets to the stage that displays the 'Watch for notifications' button. I am using ngrok and have edited web.config accordingly:

<add key="ida:NotificationUrl" value="https://4ca0d7a8.ngrok.io:44300/notification/listen" />

Does that URL have to be used in the app registration parameters? What am I doing wrong?

Also, is it not required that permissions to Microsoft Graph be added to the app via the registration page in Azure? Wouldn't "Read mail in all mailboxes" be required?

Cannot build project - NuGet packages won't restore

After forking the project, updating the client ID/secret/URL, F5 errors:

Error		This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props.	GraphWebhooks	C:\Users\jasonjoh\Source\Repos\microsoftgraph\aspnet-webhooks-rest-sample\GraphWebhooks\GraphWebhooks.csproj	274	
Warning		The referenced component 'System.Data' could not be found.	GraphWebhooks			
Warning		The referenced component 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform' could not be found.	GraphWebhooks			
Warning		The referenced component 'System.Web.Mvc' could not be found.	GraphWebhooks
...

Right-clicking the solution and choosing "Restore NuGet Packages" does not fix the error.

Issue while sign-in to application on organization id

AADSTS90130: Application 'f560adfe-a116-4c52-b897-af5b2ca5e8c8' (WebhooksAPI) is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint. Trace ID: a733c9b9-bcd6-4a58-a298-a7da35739800 Correlation ID: dd7c866d-7f6e-4d01-9183-8d005bd70f27

Authority: $"https://login.microsoftonline.com/{tenanct}/v2.0".

Please help ,I'm struck for long time. I changed multi-tenant to true ,but still no luck

Sample does not work

I believe someone else already raised this issue, but it looks like this sample project is not being updated. The CreateSubscription fails with some unknown error.

Create; Exception: [A task was canceled.] Inner error

Microsoft Graph WebHooks was working fine till yesterday but i got problem today while creating subscription

Code: ExtensionError Message: Operation: Create; Exception: [A task
was canceled.] Inner error

Following is code

    [Authorize]
        public async Task<ActionResult> CreateSubscription()
        {
            string baseUrl = $"{Request.Url.Scheme}://{Request.Url.Authority}";

            try
            {
                var subscription = await SubscriptionHelper.CreateSubscription(baseUrl);

                SubscriptionViewModel viewModel = new SubscriptionViewModel()
                {
                    Subscription = subscription
                };

                return View("Subscription", viewModel);
            }
            catch (Exception e)
            {
                ViewBag.Message = BuildErrorMessage(e);
                return View("Error", e);
            }
        }

Following is the stack trace

" at Microsoft.Graph.HttpProvider.d__19.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
Microsoft.Graph.BaseRequest.d__36.MoveNext()\r\n---
End of stack trace from previous location where exception was thrown
---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
Microsoft.Graph.BaseRequest.d__321.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()\r\n at
GraphWebhooks.Helpers.SubscriptionHelper.d__2.MoveNext()
in
C:\Users\alias\Downloads\aspnet-webhooks-rest-sample-master\aspnet-webhooks-rest-sample-master\GraphWebhooks\Helpers\SubscriptionHelper.cs:line
32\r\n--- End of stack trace from previous location where exception
was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at
GraphWebhooks.Controllers.SubscriptionController.d__1.MoveNext()
in
C:\Users\alias\Downloads\aspnet-webhooks-rest-sample-master\aspnet-webhooks-rest-sample-master\GraphWebhooks\Controllers\SubscriptionController.cs:line
30"

Following is the image
https://i.stack.imgur.com/RDESj.png

https://i.stack.imgur.com/AviYX.png
Please Help me out as soon as possible i have to publish this task

Fobidden error

I cannot get this to work. I have a registered app at azure portal as well as I granted ALL permissions, but I receive forbidden message:
untitled

Microsoft Graph - Asp.net Webhooks Rest Sample - Subscription response error

Hi,

I am following the steps mentioned in the given forum: https://github.com/microsoftgraph/aspnet-webhooks-rest-sample.

I am using ngrok for the localhost endpoints. I have updated the keys like client id, client secret key, notificaiton url in the web.config. The app is registered in Azure Active Directory.

While sending request to the microsoft graph to subscribe to users email,
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, subscriptionsEndpoint);
Subscription subscription = new Subscription
{
Resource = "me/mailFolders('Inbox')/messages",
//Resource = "me/events",
ChangeType = "created",
NotificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"],
ClientState = Guid.NewGuid().ToString(),
//ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 4230, 0) // current maximum timespan for messages
ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 15, 0) // shorter duration useful for testing
};

I am getting below error:
An error occurred while processing your request.
NotFound
{
"error": {
"code": "ExtensionError",
"message": "Operation: Create; Exception: [Status Code: NotFound; Reason: Not Found]",
"innerError": {
"request-id": "de7d32c4-b634-4193-b06e-adb614b86ec7",
"date": "2018-04-09T18:02:45"
}
}
}

When i inspect in the ngrok web interface: http://127.0.0.1:4040/inspect/http
I see below response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: plain/text; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcV29ya1xhc3BuZXQtd2ViaG9va3MtcmVzdC1zYW1wbGUtbWFzdGVyXGFzcG5ldC13ZWJob29rcy1yZXN0LXNhbXBsZS1tYXN0ZXJcR3JhcGhXZWJob29rc1xub3RpZmljYXRpb25cbGlzdGVu?=
X-Powered-By: ASP.NET
Date: Mon, 09 Apr 2018 18:00:13 GMT
Content-Length: 48

NjE3MTc4MjItZDllNi00ZDcwLThiZDYtYmU1YTlkMDUzZTAz - This is the validation token

How to fix this error ? What am i doing wrong in this ?

Subscription error

Hi everyone!

I receive the following error after clicking the 'Create Subscription' button:
image

It is worth to mention, that I followed exactly after the above instructions, including giving the 'Read user mail' delegation.

Any help?

Thanks

impersonation

Can the login user impersonate as other users and subscribe other user's events?

Subscription does not seem to work with App-Only permissions

Hi There, Things work great with Delegated permissions, but using app-only (using x509 cert to login to azure ad), I cannot seem to get things to work. I get bad request.

I have a valid token, and can perform all sorts of multi-tenant app-only operations, however when trying to do something like this

string subscriptionsEndpoint = "https://graph.microsoft.com/beta/subscriptions/";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, subscriptionsEndpoint);
var subscription = new Subscription
{
Resource = "/Users/" + user.UserPrincipleName + "/mailFolders('Inbox')/messages",
ChangeType = "created",
NotificationUrl = ConfigurationManager.AppSettings["ida:NotificationUrl"],
ClientState = Guid.NewGuid().ToString(),
ExpirationDateTime = DateTime.UtcNow + new TimeSpan(0, 0, 4230, 0)
};

It does not work. Does subscriptions not allow for app-only to use it?

Not getting any callbacks

I’m trying to setup a similar web app that receives Graph notifications when the logged in user receives new emails. The app has Mail.Read permission (can access me/messages successfully) and the subscription seems to be created, or at least I get this response back from the Graph:

{"@odata.context":"https://graph.microsoft.com/v1.0/$metadata#subscriptions/$entity", "id":"<hidden>", "resource":"me/messages", "changeType":"created", "clientState":" subscription-identifier", "notificationUrl":"<my-public-api-endpoint>", "expirationDateTime":"2016-07 -13T18:23:45.9356913Z"}, "status":201, … "statusText":"Created"}

but I don’t get any notification / calls to my API when the user that created the subscription receives new emails. Is there any way to monitor existing subscriptions or see when POST calls are made by Graph? Or what would be a good approach to debug this? The app itself is hosted on Azure, is there anything I need to enable in app settings for this to work? I assume CORS is not required.

The code in my API controller, handling POSTs, just logs incoming calls – it gets called when creating the subscription, but doesn’t receive any notifications:

public async Task<HttpResponseMessage> Post()
        {
            string validationToken = Request.GetQueryNameValuePairs()
                .SingleOrDefault(x => x.Key == "validationToken").Value;
            if (validationToken != null)
            {
                Trace.Write("Controller -- received validation token:" + validationToken + "\n");
                var response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(validationToken, Encoding.UTF8, "text/plain");
                return response;
            }
            else
            {
              Trace.Write("Controller: POST\n"); // Never called

              var incomingData = await Request.Content.ReadAsAsync<JObject>();
              if (incomingData != null)
              {
                  Trace.Write("Controller data:" + incomingData.ToString());
              }
            }
            return Request.CreateResponse(HttpStatusCode.OK, "OK");
        }

Client sometimes does not update

Sometimes the notification is received, and the retrieved message is sent to NotificationService, but the SignalR client doesn't update. When this happens, it's usually the first notification after the subscription Is created.

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.