Пример #1
0
 public ManageSubscriptions(IConfiguration config, IMsalAccountActivityStore msalAccountActivityStore, IServiceProvider serviceProvider, IMsalTokenCacheProvider msalTokenCacheProvider)
 {
     _config = config;
     _msalAccountActivityStore = msalAccountActivityStore;
     _serviceProvider          = serviceProvider;
     _msalTokenCacheProvider   = msalTokenCacheProvider;
 }
Пример #2
0
 public Connect(ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient,
                IConfiguration config, IMsalAccountActivityStore msalAccountActivityStore, IMsalTokenCacheProvider msalTokenCacheProvider)
 {
     _tokenAcquisition         = tokenAcquisition;
     _graphServiceClient       = graphServiceClient;
     _config                   = config;
     _msalAccountActivityStore = msalAccountActivityStore;
     _msalTokenCacheProvider   = msalTokenCacheProvider;
 }
Пример #3
0
        private static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Application started! \n");

                // SQL SERVER CONFIG, this should match that of the WebApi
                _serviceProvider = new ServiceCollection()
                                   .AddLogging()
                                   .AddDistributedMemoryCache()
                                   .AddDistributedSqlServerCache(options =>
                {
                    options.ConnectionString         = config.TokenCacheDbConnStr;
                    options.SchemaName               = "dbo";
                    options.TableName                = "TokenCache";
                    options.DefaultSlidingExpiration = TimeSpan.FromHours(2);
                })
                                   .AddDbContext <IntegratedTokenCacheDbContext>(options => options.UseSqlServer(config.TokenCacheDbConnStr))
                                   //.AddSingleton<IMsalTokenCacheProvider, BackgroundWorkerTokenCacheAdapter>()
                                   .AddScoped <IMsalAccountActivityStore, SqlServerMsalAccountActivityStore>()
                                   .BuildServiceProvider();

                // REDIS CONFIG, this should match that of the WebApi
                //_serviceProvider = new ServiceCollection()
                //    .AddLogging()
                //    .AddDistributedMemoryCache()
                //    .AddStackExchangeRedisCache(options =>
                //    {
                //        options.Configuration = config.TokenCacheRedisConnStr;
                //        options.InstanceName = config.TokenCacheRedisInstaceName;
                //    })
                //    .AddSingleton<IMsalTokenCacheProvider, MsalDistributedTokenCacheAdapter>()
                //    .AddDbContext<IntegratedTokenCacheDbContext>(options => options.UseSqlServer(config.TokenCacheDbConnStr))
                //    .AddScoped<IMsalAccountActivityStore, SqlServerMsalAccountActivityStore>()
                //    .BuildServiceProvider();

                _msalAccountActivityStore = _serviceProvider.GetRequiredService <IMsalAccountActivityStore>();

                RunAsync().GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ResetColor();
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Пример #4
0
        internal static async Task ManageSubscription(SubscriptionActivity currentSubscriptionActivity, string oid, string tid, string upn, IConfiguration config, IMsalAccountActivityStore msalAccountActivityStore, GraphServiceClient _graphServiceClient, IMsalTokenCacheProvider msalTokenCacheProvider)
        {
            string subscriptionId  = null;
            string changeToken     = null;
            string notiticationUrl = config.GetValue <string>("Files:SubscriptionService");
            int    subscriptionLifeTimeInMinutes = config.GetValue <int>("Files:SubscriptionLifeTime");

            if (subscriptionLifeTimeInMinutes == 0)
            {
                subscriptionLifeTimeInMinutes = 15;
            }

            // Load the current subscription (if any)
            var currentSubscriptions = await _graphServiceClient.Subscriptions.Request().GetAsync();

            var currentOneDriveSubscription = currentSubscriptions.FirstOrDefault(p => p.Resource == "me/drive/root");

            // If present and still using the same subscription host then update the subscription expiration date
            if (currentOneDriveSubscription != null && currentOneDriveSubscription.NotificationUrl.Equals(notiticationUrl, StringComparison.InvariantCultureIgnoreCase))
            {
                // Extend the expiration of the current subscription
                subscriptionId = currentOneDriveSubscription.Id;
                currentOneDriveSubscription.ExpirationDateTime = DateTimeOffset.UtcNow.AddMinutes(subscriptionLifeTimeInMinutes);
                currentOneDriveSubscription.ClientState        = Constants.FilesSubscriptionServiceClientState;
                await _graphServiceClient.Subscriptions[currentOneDriveSubscription.Id].Request().UpdateAsync(currentOneDriveSubscription);

                // Check if the last change token was populated
                if (currentSubscriptionActivity == null)
                {
                    currentSubscriptionActivity = await msalAccountActivityStore.GetSubscriptionActivityForUserSubscription(oid, tid, upn, subscriptionId);
                }

                if (currentSubscriptionActivity != null)
                {
                    changeToken = currentSubscriptionActivity.LastChangeToken;
                }
            }
            else
            {
                // Add a new subscription
                var newSubscription = await _graphServiceClient.Subscriptions.Request().AddAsync(new Subscription()
                {
                    ChangeType                = "updated",
                    NotificationUrl           = notiticationUrl,
                    Resource                  = "me/drive/root",
                    ExpirationDateTime        = DateTimeOffset.UtcNow.AddMinutes(subscriptionLifeTimeInMinutes),
                    ClientState               = Constants.FilesSubscriptionServiceClientState,
                    LatestSupportedTlsVersion = "v1_2"
                });

                subscriptionId = newSubscription.Id;
            }

            // Store the user principal name with the subscriptionid as that's the mechanism needed to connect change event with tenant/user
            var cacheEntriesToRemove = await msalAccountActivityStore.UpdateSubscriptionId(subscriptionId, oid, tid, upn);

            // If we've found old MSAL cache entries for which we've removed the respective MsalActivity records we should also
            // drop these from the MSAL cache itself
            if (cacheEntriesToRemove.Any())
            {
                foreach (var cacheEntry in cacheEntriesToRemove)
                {
                    await(msalTokenCacheProvider as IntegratedTokenCacheAdapter).RemoveKeyFromCache(cacheEntry);
                }
            }

            if (changeToken == null)
            {
                // Initialize the subscription and get the latest change token, to avoid getting back all the historical changes
                IDriveItemDeltaCollectionPage deltaCollection = await _graphServiceClient.Me.Drive.Root.Delta("latest").Request().GetAsync();

                var deltaLink = deltaCollection.AdditionalData["@odata.deltaLink"];
                if (!string.IsNullOrEmpty(deltaLink.ToString()))
                {
                    changeToken = ProcessChanges.GetChangeTokenFromUrl(deltaLink.ToString());
                }
            }

            // Store a record per user/subscription to track future delta queries
            if (currentSubscriptionActivity == null)
            {
                currentSubscriptionActivity = new SubscriptionActivity(oid, tid, upn)
                {
                    SubscriptionId  = subscriptionId,
                    LastChangeToken = changeToken
                };
            }

            currentSubscriptionActivity.LastChangeToken = changeToken;
            currentSubscriptionActivity.SubscriptionId  = subscriptionId;

            await msalAccountActivityStore.UpsertSubscriptionActivity(currentSubscriptionActivity);
        }
Пример #5
0
 public ProcessChanges(IConfiguration config, IMsalAccountActivityStore msalAccountActivityStore, IServiceProvider serviceProvider)
 {
     _config = config;
     _msalAccountActivityStore = msalAccountActivityStore;
     _serviceProvider          = serviceProvider;
 }