Verify clientstate in MS Graph

APIPointNewbie 146 Reputation points
2021-11-05T15:03:59.037+00:00

Hello Community,

in MS Graph SDK (for ASP .Net Core), how to compare the ClientState in a notification with the ClientState used in the application ?

Greetings :-)

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,716 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Danstan Onyango 3,741 Reputation points Microsoft Employee
    2021-11-12T09:36:45.797+00:00

    You can just compare the value from the notification to what your value is. For example assuming this is your notification resource

    using System;
    using System.Text.Json.Serialization;
    
    namespace ms_graph_changenotifications.Models
    {
        public class Notifications
        {
            [JsonPropertyName("value")]
            public Notification[] Items { get; set; }
        }
    
        // A change notification.
        public class Notification
        {
            // The type of change.
            [JsonPropertyName("changeType")]
            public string ChangeType { get; set; }
    
            // The client state used to verify that the notification is from Microsoft Graph. Compare the value received with the notification to the value you sent with the subscription request.
            [JsonPropertyName("clientState")]
            public string ClientState { get; set; }
        }
    }
    

    Then in your controller you just to an if else case or whatever way to check that the client state in change matches your defines client state. This just means your client state should be shared for your controller to be able to access it to validate incoming change notifications.

    using (StreamReader reader = new StreamReader(Request.Body))
    {
        string content = await reader.ReadToEndAsync();
    
        var notifications = JsonSerializer.Deserialize<Notifications>(content);
    
        foreach (var notification in notifications.Items)
        {
            if (notification.ClientState == "my-app-secert") 
            {
                Console.WriteLine("Trust it");
            }
            else
            {
                Console.WriteLine("Dont trust it");
            }
        }
    }
    
    1 person found this answer helpful.
    0 comments No comments