private void ExecBaseFeatureActivated(Microsoft.SharePoint.SPFeatureReceiverProperties properties)
 {
     // Wrapper function for base FeatureActivated.
     // Used because base keywork can lead to unverifiable code inside lambda expression
     base.FeatureActivated(properties);
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         try
         {
             ClaimsProviderLogging svc = ClaimsProviderLogging.Local;
             ClaimsProviderLogging.Log($"[{AzureCP._ProviderInternalName}] Activating farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\"", TraceSeverity.High, EventSeverity.Information, ClaimsProviderLogging.TraceCategory.Configuration);
             AzureCPConfig existingConfig = AzureCPConfig.GetConfiguration(ClaimsProviderConstants.CONFIG_NAME);
             if (existingConfig == null)
             {
                 AzureCPConfig.CreateDefaultConfiguration();
             }
             else
             {
                 ClaimsProviderLogging.Log($"[{AzureCP._ProviderInternalName}] Use configuration \"{ClaimsProviderConstants.CONFIG_NAME}\" found in the configuration database", TraceSeverity.High, EventSeverity.Information, ClaimsProviderLogging.TraceCategory.Configuration);
             }
         }
         catch (Exception ex)
         {
             ClaimsProviderLogging.LogException(AzureCP._ProviderInternalName, $"activating farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\"", ClaimsProviderLogging.TraceCategory.Configuration, ex);
         }
     });
 }
Example #2
0
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            using (GetAccessTokenLock.Lock())
            {
                bool getAccessToken = false;
                if (AuthNResult == null)
                {
                    getAccessToken = true;
                }
                else if (DateTime.Now.ToUniversalTime().Ticks > AuthNResult.ExpiresOn.UtcDateTime.Subtract(TimeSpan.FromMinutes(1)).Ticks)
                {
                    // Access token already expired or will expire within 1 min, let's renew it
                    ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Access token for tenant '{Tenant}' expired, renewing it...", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Core);
                    getAccessToken = true;
                }

                if (getAccessToken)
                {
                    bool success = await GetAccessToken(false);
                }

                if (AuthNResult != null && !String.IsNullOrEmpty(AuthNResult.AccessToken))
                {
                    request.Headers.Add("Authorization", $"Bearer {AuthNResult.AccessToken}");
                }
            }
        }
Example #3
0
        public async Task <bool> GetAccessToken(bool throwExceptionIfFail)
        {
            ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Getting new access token for tenant '{Tenant}'", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Core);
            bool      success = true;
            Stopwatch timer   = new Stopwatch();

            timer.Start();
            int timeout = this.Timeout;

            try
            {
                AuthContext = new AuthenticationContext(AuthorityUri);
                Creds       = new ClientCredential(ClientId, ClientSecret);
                Task <AuthenticationResult> acquireTokenTask = AuthContext.AcquireTokenAsync(ClaimsProviderConstants.GraphAPIResource, Creds);
                AuthNResult = await TaskHelper.TimeoutAfter <AuthenticationResult>(acquireTokenTask, new TimeSpan(0, 0, 0, 0, timeout));

                TimeSpan duration = new TimeSpan(AuthNResult.ExpiresOn.UtcTicks - DateTime.Now.ToUniversalTime().Ticks);
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Got new access token for tenant '{Tenant}', valid for {Math.Round((duration.TotalHours), 1)} hour(s) and retrieved in {timer.ElapsedMilliseconds.ToString()} ms", TraceSeverity.High, EventSeverity.Information, TraceCategory.Core);
            }
            catch (AdalServiceException ex)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Unable to get access token for tenant '{Tenant}': {ex.Message}", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Core);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw ex;
                }
            }
            catch (TimeoutException ex)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Could not get access token before timeout of {timeout.ToString()} ms for tenant '{Tenant}'", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Core);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                ClaimsProviderLogging.LogException(ClaimsProviderName, $"while getting access token for tenant '{Tenant}'", TraceCategory.Lookup, ex);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw ex;
                }
            }
            finally
            {
                timer.Stop();
            }
            return(success);
        }
 public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         try
         {
             ClaimsProviderLogging.Log($"[{AzureCP._ProviderInternalName}] Deactivating farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\": Removing claims provider from the farm (but not its configuration)", TraceSeverity.High, EventSeverity.Information, ClaimsProviderLogging.TraceCategory.Configuration);
             base.RemoveClaimProvider(AzureCP._ProviderInternalName);
         }
         catch (Exception ex)
         {
             ClaimsProviderLogging.LogException(AzureCP._ProviderInternalName, $"deactivating farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\"", ClaimsProviderLogging.TraceCategory.Configuration, ex);
         }
     });
 }
 public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         try
         {
             ClaimsProviderLogging.Log($"[{AzureCP._ProviderInternalName}] Uninstalling farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\": Deleting configuration from the farm", TraceSeverity.High, EventSeverity.Information, ClaimsProviderLogging.TraceCategory.Configuration);
             AzureCPConfig.DeleteConfiguration(ClaimsProviderConstants.CONFIG_NAME);
             ClaimsProviderLogging.Unregister();
         }
         catch (Exception ex)
         {
             ClaimsProviderLogging.LogException(AzureCP._ProviderInternalName, $"deactivating farm-scoped feature for claims provider \"{AzureCP._ProviderInternalName}\"", ClaimsProviderLogging.TraceCategory.Configuration, ex);
         }
     });
 }
Example #6
0
        public async Task <bool> GetAccessToken(bool throwExceptionIfFail)
        {
            bool      success = true;
            Stopwatch timer   = new Stopwatch();

            timer.Start();
            int timeout = this.Timeout;

            try
            {
                ConfidentialClientApplicationBuilder appBuilder = ConfidentialClientApplicationBuilder.Create(ClientId).WithAuthority(this.CloudInstance, this.Tenant);
                IConfidentialClientApplication       app        = null;
                if (!String.IsNullOrWhiteSpace(ClientSecret))
                {
                    // Get bearer token using a client secret
                    ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Getting new access token for tenant '{Tenant}' on cloud instance '{CloudInstance}' using client ID {ClientId} and a client secret.", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Core);
                    app = appBuilder.WithClientSecret(ClientSecret).Build();
                }
                else
                {
                    // Get bearer token using a client certificate
                    ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Getting new access token for tenant '{Tenant}' on cloud instance '{CloudInstance}' using client ID {ClientId} and a client certificate with thumbprint {ClientCertificate.Thumbprint}.", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Core);
                    app = appBuilder.WithCertificate(ClientCertificate).Build();
                }
                // Acquire bearer token
                Task <AuthenticationResult> acquireTokenTask = app.AcquireTokenForClient(this.Scopes).ExecuteAsync();
                AuthNResult = await TaskHelper.TimeoutAfter <AuthenticationResult>(acquireTokenTask, new TimeSpan(0, 0, 0, 0, timeout)).ConfigureAwait(false);

                TimeSpan duration = new TimeSpan(AuthNResult.ExpiresOn.UtcTicks - DateTime.Now.ToUniversalTime().Ticks);
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Got new access token for tenant '{Tenant}' on cloud instance '{CloudInstance}', valid for {Math.Round((duration.TotalHours), 1)} hour(s) and retrieved in {timer.ElapsedMilliseconds.ToString()} ms", TraceSeverity.High, EventSeverity.Information, TraceCategory.Core);
            }
            catch (MsalServiceException ex)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Unable to get access token for tenant '{Tenant}' on cloud instance '{CloudInstance}': {ex.Message}", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Core);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw;
                }
            }
            catch (TimeoutException)
            {
                ClaimsProviderLogging.Log($"[{ClaimsProviderName}] Could not get access token before timeout of {timeout.ToString()} ms for tenant '{Tenant}' on cloud instance '{CloudInstance}'", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Core);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                ClaimsProviderLogging.LogException(ClaimsProviderName, $"while getting access token for tenant '{Tenant}' on cloud instance '{CloudInstance}'", TraceCategory.Lookup, ex);
                success = false;
                if (throwExceptionIfFail)
                {
                    throw;
                }
            }
            finally
            {
                timer.Stop();
            }
            return(success);
        }