/// <summary>
        /// Log in to azure active directory in non-interactive mode using organizational id credentials.
        /// </summary>
        /// <param name="clientId">The active directory client id for this application.</param>
        /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
        /// <param name="username">The organizational account user name, given in the form of a user principal name (e.g. [email protected]).</param>
        /// <param name="password">The organizational account password.</param>
        /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task <ServiceClientCredentials> LoginSilentAsync(string clientId, string domain, string username, string password,
                                                                             ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
        {
            var credentials           = new UserCredential(username, password);
            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);

            try
            {
                var authResult = await authenticationContext.AcquireTokenAsync(serviceSettings.TokenAudience.ToString(),
                                                                               clientId, credentials).ConfigureAwait(false);

                return
                    (new TokenCredentials(
                         new UserTokenProvider(authenticationContext, clientId, serviceSettings.TokenAudience,
                                               new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId)),
                         authResult.TenantId,
                         authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId));
            }
            catch (AdalException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
            catch (FormatException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
        }
Beispiel #2
0
 /// <summary>
 /// Log in to Azure active directory with both user account and authentication credentials provided by the user.  This call may display a
 /// credentials dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain,
                                                                          ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
                                       UserIdentifier.AnyUser, TokenCache.DefaultShared).ConfigureAwait(false));
 }
Beispiel #3
0
 /// <summary>
 /// Log in to Azure active directory with both user account and authentication credentials provided by the user.  This call may display a
 /// credentials dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain,
                                                                          ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
                                       UserIdentifier.AnyUser, cache));
 }
Beispiel #4
0
 /// <summary>
 /// Log in to Azure active directory using the given username with authentication provided by the user.  This call may display a credentials
 /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="username">The username to use for authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain,
                                                                          ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings, string username)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
                                       new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId), TokenCache.DefaultShared));
 }
Beispiel #5
0
        /// <summary>
        /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials
        /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
        /// </summary>
        /// <param name="domain">The domain to authenticate against.</param>
        /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
        /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
        /// <param name="userId">The userid of the desired credentials</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings,
                                                                                 ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache)
        {
            var           authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);
            TaskScheduler scheduler             = TaskScheduler.FromCurrentSynchronizationContext();
            var           task = new Task <AuthenticationResult>(() =>
            {
                try
                {
                    var result = authenticationContext.AcquireToken(
                        serviceSettings.TokenAudience.ToString(),
                        clientSettings.ClientId,
                        clientSettings.ClientRedirectUri,
                        clientSettings.PromptBehavior,
                        userId,
                        clientSettings.AdditionalQueryParameters);
                    return(result);
                }
                catch (Exception e)
                {
                    throw new AuthenticationException(
                        string.Format(CultureInfo.CurrentCulture, Resources.ErrorAcquiringToken,
                                      e.Message), e);
                }
            });

            task.Start(scheduler);
            var authResult = await task.ConfigureAwait(false);

            var newUserId = new UserIdentifier(authResult.UserInfo.DisplayableId,
                                               UserIdentifierType.RequiredDisplayableId);

            return(new TokenCredentials(new UserTokenProvider(authenticationContext, clientSettings.ClientId,
                                                              serviceSettings.TokenAudience, newUserId)));
        }
Beispiel #6
0
 /// <summary>
 /// Log in to azure active directory using device code authentication.
 /// </summary>
 /// <param name="clientId">The active directory client id for this application.</param>
 /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
 /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
 /// <param name="deviceCodeHandler">User provided callback to display device code request. if returns false no token will be acquired.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginByDeviceCodeAsync(
     string clientId,
     string domain,
     ActiveDirectoryServiceSettings serviceSettings,
     Func <DeviceCodeResult, bool> deviceCodeHandler)
 {
     return(await LoginByDeviceCodeAsync(clientId, domain, serviceSettings, TokenCache.DefaultShared, deviceCodeHandler));
 }
 private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return((cache == null)
             ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                         serviceSettings.ValidateAuthority)
             : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                         serviceSettings.ValidateAuthority,
                                         cache));
 }
 public void AzureEnvironmentDoesNotDuplicateSlash(string inputUri)
  {
      var testEnvironment = new ActiveDirectoryServiceSettings
      {
          ValidateAuthority = true,
          TokenAudience = new Uri("https://contoso.com/widgets/"),
          AuthenticationEndpoint = new Uri(inputUri)
      };
      Assert.Equal(inputUri, testEnvironment.AuthenticationEndpoint.ToString());
  }
        /// <summary>
        /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credential.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="certificate">The certificate associated with Active Directory application.</param>
        /// <param name="password">The certificate password.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, byte[] certificate, string password,
                                                                             ActiveDirectoryServiceSettings settings, TokenCache cache)
        {
#if !net452
            return(await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId, certificate, password),
                                          settings, cache));
#else
            return(await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId,
                                                                                 new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate)),
                                          settings, cache));
#endif
        }
Beispiel #10
0
        private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache, object ownerWindow)
        {
            var context = (cache == null
                ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                            serviceSettings.ValidateAuthority)
                : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                                            serviceSettings.ValidateAuthority, cache));

            if (ownerWindow != null)
            {
                context.OwnerWindow = ownerWindow;
            }

            return(context);
        }
        /// <summary>
        /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials
        /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
        /// </summary>
        /// <param name="domain">The domain to authenticate against.</param>
        /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
        /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
        /// <param name="userId">The userid of the desired credentials</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings,
                                                                                 ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache)
        {
            TaskScheduler scheduler;

            if (SynchronizationContext.Current != null)
            {
                scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            }
            else
            {
                scheduler = TaskScheduler.Current;
            }

            return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings, userId, cache, () => { return scheduler; }).ConfigureAwait(false));
        }
        /// <summary>
        /// Log in to azure active directory using device code authentication.
        /// </summary>
        /// <param name="clientId">The active directory client id for this application.</param>
        /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
        /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="deviceCodeHandler">User provided callback to display device code request. if returns false no token will be acquired.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task <ServiceClientCredentials> LoginByDeviceCodeAsync(
            string clientId,
            string domain,
            ActiveDirectoryServiceSettings serviceSettings,
            TokenCache cache,
            Func <DeviceCodeResult, bool> deviceCodeHandler)
        {
            if (deviceCodeHandler == null)
            {
                throw new ArgumentException("deviceCodeHandler");
            }

            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);

            try
            {
                DeviceCodeResult codeResult = await authenticationContext.AcquireDeviceCodeAsync(
                    serviceSettings.TokenAudience.ToString(),
                    clientId)
                                              .ConfigureAwait(false);

                if (deviceCodeHandler(codeResult))
                {
                    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenByDeviceCodeAsync(codeResult)
                                                                .ConfigureAwait(false);

                    return(new TokenCredentials(
                               new UserTokenProvider(
                                   authenticationContext,
                                   clientId,
                                   serviceSettings.TokenAudience,
                                   new UserIdentifier(authenticationResult.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId)),
                               authenticationResult.TenantId,
                               authenticationResult.UserInfo == null ? null : authenticationResult.UserInfo.DisplayableId));
                }

                return(null);
            }
            catch (AdalException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
            catch (FormatException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using client credentials.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="secret">The secret for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, string secret,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, new ClientCredential(clientId, secret), settings, cache));
 }
 /// <summary>
 /// Log in to azure active directory using device code authentication.
 /// </summary>
 /// <param name="clientId">The active directory client id for this application.</param>
 /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
 /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
 /// <param name="deviceCodeHandler">User provided callback to display device code request. if returns false no token will be acquired.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task<ServiceClientCredentials> LoginByDeviceCodeAsync(
     string clientId,
     string domain,
     ActiveDirectoryServiceSettings serviceSettings,
     Func<DeviceCodeResult, bool> deviceCodeHandler)
 {
     return await LoginByDeviceCodeAsync(clientId, domain, serviceSettings, TokenCache.DefaultShared, deviceCodeHandler);
 }
Beispiel #15
0
        /// <summary>
        /// For testing purposes only: allows testing token expiration.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId fo the application.</param>
        /// <param name="credentialProvider">A source for the secure secret for this application.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="expiration">The token expiration.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        internal static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                               IApplicationCredentialProvider credentialProvider, ActiveDirectoryServiceSettings settings, TokenCache cache, DateTimeOffset expiration)
        {
            var audience   = settings.TokenAudience.ToString();
            var context    = GetAuthenticationContext(domain, settings, cache);
            var credential = await credentialProvider.GetCredentialAsync(clientId);

            var authResult = await context.AcquireTokenAsync(audience, credential);

            return(new TokenCredentials(new ApplicationTokenProvider(context, audience, clientId,
                                                                     credentialProvider, authResult, expiration)));
        }
Beispiel #16
0
        /// <summary>
        /// Creates ServiceClientCredentials for authenticating requests as an active directory application.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                             IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings, TokenCache cache)
        {
            var audience   = settings.TokenAudience.ToString();
            var context    = GetAuthenticationContext(domain, settings, cache);
            var authResult = await authenticationProvider.AuthenticateAsync(clientId, audience, context);

            return(new TokenCredentials(new ApplicationTokenProvider(context, audience, clientId,
                                                                     authenticationProvider, authResult)));
        }
 /// <summary>
 /// For testing purposes only: allows testing token expiration.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <param name="expiration">The token expiration.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 internal static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
     IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings, TokenCache cache, DateTimeOffset expiration)
 {
     var audience = settings.TokenAudience.ToString();
     var context = GetAuthenticationContext(domain, settings, cache);
     var authResult = await authenticationProvider.AuthenticateAsync(clientId, audience, context);
     return new TokenCredentials(new ApplicationTokenProvider(context, audience, clientId,
             authenticationProvider, authResult, expiration));
 }
  /// <summary>
  /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential.
  /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
  /// for detailed instructions on creating an Azure Active Directory application.
  /// </summary>
  /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
  /// <param name="certificate">The certificate associated with Active Directory application.</param>
  /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
  /// <param name="cache">The token cache to target during authentication.</param>
  /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, ClientAssertionCertificate certificate,
      ActiveDirectoryServiceSettings settings, TokenCache cache)
  {
      return await LoginSilentAsync(domain, certificate.ClientId, 
          new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)), settings, cache);
  }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential. Uses the default token cache for authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentWithCertificateAsync(string domain, ClientAssertionCertificate certificate,
     ActiveDirectoryServiceSettings settings)
 {
     return await LoginSilentAsync(domain, certificate, settings, TokenCache.DefaultShared);
 }
Beispiel #20
0
 /// <summary>
 /// Log in to azure active directory in non-interactive mode using organizational id credentials and the default token cache.
 /// </summary>
 /// <param name="clientId">The active directory client id for this application.</param>
 /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
 /// <param name="username">The organizational account user name, given in the form of a user principal name (e.g. [email protected]).</param>
 /// <param name="password">The organizational account password.</param>
 /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string clientId, string domain, string username,
                                                                      string password, ActiveDirectoryServiceSettings serviceSettings)
 {
     return(await LoginSilentAsync(clientId, domain, username, password, serviceSettings, TokenCache.DefaultShared).ConfigureAwait(false));
 }
 /// <summary>
 /// Log in to azure active directory in non-interactive mode using organizational id credentials.
 /// </summary>
 /// <param name="clientId">The active directory client id for this application.</param>
 /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
 /// <param name="username">The organizational account user name, given in the form of a user principal name (e.g. [email protected]).</param>
 /// <param name="password">The organizational account password.</param>
 /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string clientId, string domain, string username, string password, 
     ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     var credentials = new UserCredential(username, password);
     var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);
     try
     {
         var authResult = await authenticationContext.AcquireTokenAsync(serviceSettings.TokenAudience.ToString(),
               clientId, credentials).ConfigureAwait(false);
         return
             new TokenCredentials(
                 new UserTokenProvider(authenticationContext, clientId,serviceSettings.TokenAudience, 
                         new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId)),
                 authResult.TenantId,
                 authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId);
     }
     catch (AdalException ex)
     {
         throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
     }
     catch(FormatException ex)
     {
         throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
     }
 }
 /// <summary>
 /// Create service client credentials using information cached from a previous login. Parameters are used to match existing tokens.
 /// </summary>
 /// <param name="clientId">The clientId to match when retrieving authentication tokens.</param>
 /// <param name="domain">The active directory domain or tenant id to match when retrieving authentication tokens.</param>
 /// <param name="username">The account username to match when retrieving authentication tokens.</param>
 /// <param name="serviceSettings">The active directory service settings, including token authority and audience to match when retrieving tokens.</param>
 /// <param name="cache">The token cache to target when retrieving tokens.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the retrieved credentials. If no 
 /// credentials can be retrieved, an authentication exception is thrown.</returns>
 public static async Task<ServiceClientCredentials> CreateCredentialsFromCache(string clientId, string domain, string username, 
     ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     var userId = new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId);
     var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);
     try
     {
         await authenticationContext.AcquireTokenSilentAsync(serviceSettings.TokenAudience.ToString(),
               clientId, userId).ConfigureAwait(false);
         return
             new TokenCredentials(new UserTokenProvider(authenticationContext, clientId,
                 serviceSettings.TokenAudience, userId));
     }
     catch (AdalException ex)
     {
         throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
     }
 }
 /// <summary>
 /// Create service client credentials using information cached from a previous login in the default token cache. Parameters are used to match 
 /// existing tokens.
 /// </summary>
 /// <param name="clientId">The clientId to match when retrieving authentication tokens.</param>
 /// <param name="domain">The active directory domain or tenant id to match when retrieving authentication tokens.</param>
 /// <param name="username">The account username to match when retrieving authentication tokens.</param>
 /// <param name="serviceSettings">The active directory service settings, including token authority and audience to match when retrieving tokens.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the retrieved credentials. If no 
 /// credentials can be retrieved, an authentication exception is thrown.</returns>
 public static async Task<ServiceClientCredentials> CreateCredentialsFromCache(string clientId, string domain,
     string username, ActiveDirectoryServiceSettings serviceSettings)
 {
     return await CreateCredentialsFromCache(clientId, domain, username, serviceSettings, TokenCache.DefaultShared);
 }
        /// <summary>
        /// Log in to azure active directory using device code authentication.
        /// </summary>
        /// <param name="clientId">The active directory client id for this application.</param>
        /// <param name="domain">The active directory domain or tenant id to authenticate with.</param>
        /// <param name="serviceSettings">The active directory service details, including authentication endpoints and the intended token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="deviceCodeHandler">User provided callback to display device code request. if returns false no token will be acquired.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task<ServiceClientCredentials> LoginByDeviceCodeAsync(
            string clientId, 
            string domain, 
            ActiveDirectoryServiceSettings serviceSettings, 
            TokenCache cache, 
            Func<DeviceCodeResult, bool> deviceCodeHandler)
        {
            if(deviceCodeHandler == null)
            {
                throw new ArgumentException("deviceCodeHandler");
            }

            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);

            try
            {
                DeviceCodeResult codeResult = await authenticationContext.AcquireDeviceCodeAsync(
                                                                                serviceSettings.TokenAudience.ToString(),
                                                                                clientId)
                                                                         .ConfigureAwait(false);

                if (deviceCodeHandler(codeResult))
                {
                    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenByDeviceCodeAsync(codeResult)
                                                                                           .ConfigureAwait(false);

                    return new TokenCredentials(
                        new UserTokenProvider(
                            authenticationContext,
                            clientId,
                            serviceSettings.TokenAudience,
                            new UserIdentifier(authenticationResult.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId)));
                }

                return null;
            }
            catch (AdalException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
            catch (FormatException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a client credential.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="credential">The client credential (client id and secret) for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, ClientCredential credential,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, credential.ClientId, new MemoryApplicationAuthenticationProvider(credential),
                                   settings, cache));
 }
 /// <summary>
 /// Log in to Azure active directory using the given username with authentication provided by the user.  This call may display a credentials 
 /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="username">The username to use for authentication.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task<ServiceClientCredentials> LoginWithPromptAsync(string domain,
     ActiveDirectoryClientSettings clientSettings,
     ActiveDirectoryServiceSettings serviceSettings, string username, TokenCache cache)
 {
     return await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
        new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId), cache);
 }
 /// <summary>
 /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials
 /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="taskScheduler">Scheduler needed to run the task</param>
 /// <returns></returns>
 public static async Task <ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings,
                                                                          ActiveDirectoryServiceSettings serviceSettings, Func <TaskScheduler> taskScheduler)
 {
     return(await LoginWithPromptAsync(domain, clientSettings, serviceSettings, UserIdentifier.AnyUser, TokenCache.DefaultShared, taskScheduler));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a client credential.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="credential">The client credential (client id and secret) for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, ClientCredential credential,
     ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return await LoginSilentAsync(domain, credential.ClientId, new MemoryApplicationAuthenticationProvider(credential),
        settings, cache);
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId fo the application.</param>
 /// <param name="credentialProvider">A source for the secure secret for this application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
     IApplicationCredentialProvider credentialProvider, ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     var audience = settings.TokenAudience.ToString();
     var context = GetAuthenticationContext(domain, settings, cache);
     var credential = await credentialProvider.GetCredentialAsync(clientId);
     var authResult = await context.AcquireTokenAsync(audience, credential);
     return new TokenCredentials(new ApplicationTokenProvider(context, audience, clientId,
             credentialProvider, authResult));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application. Uses the default shared token cache.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
     IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings)
 {
     return await LoginSilentAsync(domain, clientId, authenticationProvider, settings, TokenCache.DefaultShared);
 }
        public ServiceClientCredentials GetServiceClientCredentials(AzureContext context, AzureEnvironment.Endpoint targetEndpoint)
        {
            if (context.Account == null)
            {
                throw new ArgumentException(Resources.ArmAccountNotFound);
            }

            if (context.Account.Type == AzureAccount.AccountType.Certificate)
            {
                throw new NotSupportedException(AzureAccount.AccountType.Certificate.ToString());
            }

            if (context.Account.Type == AzureAccount.AccountType.AccessToken)
            {
                return new TokenCredentials(context.Account.GetProperty(AzureAccount.Property.AccessToken));
            }

            string tenant = null;

            if (context.Subscription != null && context.Account != null)
            {
                tenant = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                      .Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
                      .FirstOrDefault();
            }

            if (tenant == null && context.Tenant != null && context.Tenant.Id != Guid.Empty)
            {
                tenant = context.Tenant.Id.ToString();
            }

            if (tenant == null)
            {
                throw new ArgumentException(Resources.NoTenantInContext);
            }

            try
            {
                TracingAdapter.Information(Resources.UPNAuthenticationTrace,
                    context.Account.Id, context.Environment.Name, tenant);

                // TODO: When we will refactor the code, need to add tracing
                /*TracingAdapter.Information(Resources.UPNAuthenticationTokenTrace,
                    token.LoginType, token.TenantId, token.UserId);*/

                var env = new ActiveDirectoryServiceSettings
                {
                    AuthenticationEndpoint = context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ActiveDirectory),
                    TokenAudience = context.Environment.GetEndpointAsUri(context.Environment.GetTokenAudience(targetEndpoint)),
                    ValidateAuthority = !context.Environment.OnPremise
                };

                var tokenCache = AzureSession.TokenCache;

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    tokenCache = new TokenCache(context.TokenCache);
                }

                ServiceClientCredentials result = null;

                if (context.Account.Type == AzureAccount.AccountType.User)
                {
                    result = Rest.Azure.Authentication.UserTokenProvider.CreateCredentialsFromCache(
                        AdalConfiguration.PowerShellClientId,
                        tenant,
                        context.Account.Id,
                        env,
                        tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                }
                else if (context.Account.Type == AzureAccount.AccountType.ServicePrincipal)
                {
                    if (context.Account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
                    {
                        result = ApplicationTokenProvider.LoginSilentAsync(
                            tenant,
                            context.Account.Id,
                            new CertificateApplicationCredentialProvider(
                                context.Account.GetProperty(AzureAccount.Property.CertificateThumbprint)),
                            env,
                            tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                    }
                    else
                    {
                        result = ApplicationTokenProvider.LoginSilentAsync(
                            tenant,
                            context.Account.Id,
                            new KeyStoreApplicationCredentialProvider(tenant),
                            env,
                            tokenCache).ConfigureAwait(false).GetAwaiter().GetResult();
                    }
                }
                else
                {
                    throw new NotSupportedException(context.Account.Type.ToString());
                }

                if (context.TokenCache != null && context.TokenCache.Length > 0)
                {
                    context.TokenCache = tokenCache.Serialize();
                }

                return result;
            }
            catch (Exception ex)
            {
                TracingAdapter.Information(Resources.AdalAuthException, ex.Message);
                throw new ArgumentException(Resources.InvalidArmContext, ex);
            }
        }
 private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return (cache == null)
             ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                 serviceSettings.ValidateAuthority)
             : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                 serviceSettings.ValidateAuthority,
                 cache);
 }
Beispiel #33
0
 /// <summary>
 /// Create service client credentials using information cached from a previous login in the default token cache. Parameters are used to match
 /// existing tokens.
 /// </summary>
 /// <param name="clientId">The clientId to match when retrieving authentication tokens.</param>
 /// <param name="domain">The active directory domain or tenant id to match when retrieving authentication tokens.</param>
 /// <param name="username">The account username to match when retrieving authentication tokens.</param>
 /// <param name="serviceSettings">The active directory service settings, including token authority and audience to match when retrieving tokens.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the retrieved credentials. If no
 /// credentials can be retrieved, an authentication exception is thrown.</returns>
 public static async Task <ServiceClientCredentials> CreateCredentialsFromCache(string clientId, string domain,
                                                                                string username, ActiveDirectoryServiceSettings serviceSettings)
 {
     return(await CreateCredentialsFromCache(clientId, domain, username, serviceSettings, TokenCache.DefaultShared));
 }
        private static AuthenticationContext GetAuthenticationContext(string domain, ActiveDirectoryServiceSettings serviceSettings, TokenCache cache, object ownerWindow)
        {
            var context = (cache == null
                ? new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                    serviceSettings.ValidateAuthority)
                : new AuthenticationContext(serviceSettings.AuthenticationEndpoint + domain,
                    serviceSettings.ValidateAuthority, cache));
            if (ownerWindow != null)
            {
                context.OwnerWindow = ownerWindow;
            }

            return context;
        }
        //public async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId)
        //{
        //    return null;
        //}

        /// <summary>
        /// Creates ServiceClientCredentials for authenticating requests as an active directory application using client credentials.
        /// Uses the default token cache during authentication.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/"> Active Directory Quickstart for .Net</see>
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="secret">The secret for this active directory application.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, string secret,
                                                                             ActiveDirectoryServiceSettings settings)
        {
            return(await LoginSilentAsync(domain, clientId, secret, settings, TokenCache.DefaultShared));
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential. Uses the default token cache for authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentWithCertificateAsync(string domain, ClientAssertionCertificate certificate,
                                                                                     ActiveDirectoryServiceSettings settings)
 {
     return(await LoginSilentAsync(domain, certificate, settings, TokenCache.DefaultShared));
 }
        /// <summary>
        /// Log in to Azure active directory with credentials provided by the user.  This call may display a credentials 
        /// dialog, depending on the supplied client settings and the state of the token cache and user cookies.
        /// </summary>
        /// <param name="domain">The domain to authenticate against.</param>
        /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
        /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
        /// <param name="userId">The userid of the desired credentials</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
        public static async Task<ServiceClientCredentials> LoginWithPromptAsync(string domain, ActiveDirectoryClientSettings clientSettings, 
            ActiveDirectoryServiceSettings serviceSettings, UserIdentifier userId, TokenCache cache)
        {
            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);
            TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
            var task = new Task<AuthenticationResult>(() =>
            {
                try
                {
                    var result = authenticationContext.AcquireToken(
                        serviceSettings.TokenAudience.ToString(),
                        clientSettings.ClientId,
                        clientSettings.ClientRedirectUri,
                        clientSettings.PromptBehavior,
                        userId,
                        clientSettings.AdditionalQueryParameters);
                    return result;
                }
                catch (Exception e)
                {
                    throw new AuthenticationException(
                        string.Format(CultureInfo.CurrentCulture, Resources.ErrorAcquiringToken,
                            e.Message), e);
                }
            });

            task.Start(scheduler);
            var authResult = await task.ConfigureAwait(false);
            var newUserId = new UserIdentifier(authResult.UserInfo.DisplayableId,
                UserIdentifierType.RequiredDisplayableId);
            return new TokenCredentials(new UserTokenProvider(authenticationContext, clientSettings.ClientId,
                serviceSettings.TokenAudience, newUserId));
        }
Beispiel #38
0
        /// <summary>
        /// Create service client credentials using information cached from a previous login. Parameters are used to match existing tokens.
        /// </summary>
        /// <param name="clientId">The clientId to match when retrieving authentication tokens.</param>
        /// <param name="domain">The active directory domain or tenant id to match when retrieving authentication tokens.</param>
        /// <param name="username">The account username to match when retrieving authentication tokens.</param>
        /// <param name="serviceSettings">The active directory service settings, including token authority and audience to match when retrieving tokens.</param>
        /// <param name="cache">The token cache to target when retrieving tokens.</param>
        /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the retrieved credentials. If no
        /// credentials can be retrieved, an authentication exception is thrown.</returns>
        public static async Task <ServiceClientCredentials> CreateCredentialsFromCache(string clientId, string domain, string username,
                                                                                       ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
        {
            var userId = new UserIdentifier(username, UserIdentifierType.RequiredDisplayableId);
            var authenticationContext = GetAuthenticationContext(domain, serviceSettings, cache);

            try
            {
                await authenticationContext.AcquireTokenSilentAsync(serviceSettings.TokenAudience.ToString(),
                                                                    clientId, userId).ConfigureAwait(false);

                return
                    (new TokenCredentials(new UserTokenProvider(authenticationContext, clientId,
                                                                serviceSettings.TokenAudience, userId)));
            }
            catch (AdalException ex)
            {
                throw new AuthenticationException(Resources.ErrorAcquiringToken, ex);
            }
        }
        /// <summary>
        /// For testing purposes only: allows testing token expiration.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <param name="expiration">The token expiration.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        internal static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                               IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings, TokenCache cache, DateTimeOffset expiration)
        {
            var audience   = settings.TokenAudience.OriginalString;
            var context    = GetAuthenticationContext(domain, settings, cache);
            var authResult = await authenticationProvider.AuthenticateAsync(clientId, audience, context);

            return(new TokenCredentials(
                       new ApplicationTokenProvider(context, audience, clientId, authenticationProvider, authResult, expiration),
                       authResult.TenantId,
                       authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId));
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credentials.
 /// Uses the default token cache during authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/"> Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="password">The certificate password.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, byte[] certificate, string password,
                                                                      ActiveDirectoryServiceSettings settings)
 {
     return(await LoginSilentAsync(domain, clientId, certificate, password, settings, TokenCache.DefaultShared));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a client credential. Uses the default token cache for authentication.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="credential">The client credential (client id and secret) for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, ClientCredential credential,
                                                                      ActiveDirectoryServiceSettings settings)
 {
     return(await LoginSilentAsync(domain, credential, settings, TokenCache.DefaultShared).ConfigureAwait(false));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using client credentials.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="secret">The secret for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, string secret,
    ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return await LoginSilentAsync(domain, new ClientCredential(clientId, secret), settings, cache);
 }
        /// <summary>
        /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credential.
        /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
        /// for detailed instructions on creating an Azure Active Directory application.
        /// </summary>
        /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
        /// <param name="clientId">The active directory clientId for the application.</param>
        /// <param name="certificate">The certificate associated with Active Directory application.</param>
        /// <param name="password">The certificate password.</param>
        /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
        /// <param name="cache">The token cache to target during authentication.</param>
        /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
        public static async Task<ServiceClientCredentials> LoginSilentAsync(
            string domain, string clientId, byte[] certificate, string password,
           ActiveDirectoryServiceSettings settings, TokenCache cache)
        {
#if PORTABLE
            return await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId, certificate, password), 
                settings, cache);
#else
            return await LoginSilentAsync(domain, new ClientAssertionCertificate(clientId, 
                new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate)),
                settings, cache);
#endif
        }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using a certificate credential.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, ClientAssertionCertificate certificate,
                                                                      ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     return(await LoginSilentAsync(domain, certificate.ClientId,
                                   new CertificateAuthenticationProvider((clientId) => Task.FromResult(certificate)), settings, cache));
 }
 /// <summary>
 /// Log in to Azure active directory with both user account and authentication credentials provided by the user.  This call may display a 
 /// credentials dialog, depending on the supplied client settings and the state of the token cache and user cookies.
 /// </summary>
 /// <param name="domain">The domain to authenticate against.</param>
 /// <param name="clientSettings">The client settings to use for authentication. These determine when a dialog will be displayed.</param>
 /// <param name="serviceSettings">The settings for ad service, including endpoint and token audience</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can be used to authenticate http requests using the given credentials.</returns>
 public static async Task<ServiceClientCredentials> LoginWithPromptAsync(string domain,
     ActiveDirectoryClientSettings clientSettings,
     ActiveDirectoryServiceSettings serviceSettings, TokenCache cache)
 {
     return await LoginWithPromptAsync(domain, clientSettings, serviceSettings,
        UserIdentifier.AnyUser, cache);
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application. Uses the default shared token cache.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see>
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task <ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
                                                                      IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings)
 {
     return(await LoginSilentAsync(domain, clientId, authenticationProvider, settings, TokenCache.DefaultShared));
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using client credentials. 
 /// Uses the default token cache during authentication. 
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/"> Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="secret">The secret for this active directory application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, string secret,
     ActiveDirectoryServiceSettings settings)
 {
     return await LoginSilentAsync(domain, clientId, secret, settings, TokenCache.DefaultShared);
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application using certificate credentials. 
 /// Uses the default token cache during authentication. 
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/"> Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="certificate">The certificate associated with Active Directory application.</param>
 /// <param name="password">The certificate password.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId, byte[] certificate, string password,
     ActiveDirectoryServiceSettings settings)
 {
     return await LoginSilentAsync(domain, clientId, certificate, password, settings, TokenCache.DefaultShared);
 }
 /// <summary>
 /// Creates ServiceClientCredentials for authenticating requests as an active directory application.
 /// See <see href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/">Active Directory Quickstart for .Net</see> 
 /// for detailed instructions on creating an Azure Active Directory application.
 /// </summary>
 /// <param name="domain">The active directory domain or tenantId to authenticate with.</param>
 /// <param name="clientId">The active directory clientId for the application.</param>
 /// <param name="authenticationProvider">A source for the secure secret for this application.</param>
 /// <param name="settings">The active directory service side settings, including authority and token audience.</param>
 /// <param name="cache">The token cache to target during authentication.</param>
 /// <returns>A ServiceClientCredentials object that can authenticate http requests as the given application.</returns>
 public static async Task<ServiceClientCredentials> LoginSilentAsync(string domain, string clientId,
     IApplicationAuthenticationProvider authenticationProvider, ActiveDirectoryServiceSettings settings, TokenCache cache)
 {
     var audience = settings.TokenAudience.ToString();
     var context = GetAuthenticationContext(domain, settings, cache);
     var authResult = await authenticationProvider.AuthenticateAsync(clientId, audience, context);
     return new TokenCredentials(
         new ApplicationTokenProvider(context, audience, clientId,authenticationProvider, authResult),
         authResult.TenantId,
         authResult.UserInfo == null ? null : authResult.UserInfo.DisplayableId);
 }