Class storing the configuration information needed for ADAL to request token from the right AD tenant depending on environment.
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     if (credentialType == AzureAccount.AccountType.User)
     {
         throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
     }
     return new ServicePrincipalAccessToken(config, AcquireTokenWithSecret(config, userId, password), this.RenewWithSecret, userId);
 }
 public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string clientId, string certificateThumbprint, AzureAccount.AccountType credentialType)
 {
     if (credentialType == AzureAccount.AccountType.User)
     {
         throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
     }
     return new ServicePrincipalAccessToken(config, AcquireTokenWithCertificate(config, clientId, certificateThumbprint), 
         (adalConfig, appId) => this.RenewWithCertificate(adalConfig, appId, certificateThumbprint), clientId);
 }
        private AuthenticationResult AcquireTokenWithSecret(AdalConfiguration config, string appId, SecureString appKey)
        {
            if (appKey == null)
            {
                return RenewWithSecret(config, appId);
            }

            StoreAppKey(appId, config.AdDomain, appKey);
            var credential = new ClientCredential(appId, appKey);
            var context = GetContext(config);
            return context.AcquireToken(config.ResourceClientUri, credential);
        }
        private AuthenticationResult AcquireTokenWithCertificate(AdalConfiguration config, string appId,
            string thumbprint)
        {
            var certificate = AzureSession.DataStore.GetCertificate(thumbprint);
            if (certificate == null)
            {
                throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, thumbprint));
            }

            var context = GetContext(config);
            return context.AcquireToken(config.ResourceClientUri, new ClientAssertionCertificate(appId, certificate));
        }
 private AuthenticationResult RenewWithSecret(AdalConfiguration config, string appId)
 {
     TracingAdapter.Information(Resources.SPNRenewTokenTrace, appId, config.AdDomain, config.AdEndpoint, 
         config.ClientId, config.ClientRedirectUri);
    using (SecureString appKey = LoadAppKey(appId, config.AdDomain))
     {
         if (appKey == null)
         {
             throw new KeyNotFoundException(string.Format(Resources.ServiceKeyNotFound, appId));
         }
         return AcquireTokenWithSecret(config, appId, appKey);
     }
 }
Пример #6
0
 public IAccessToken GetAccessTokenWithCertificate(
     AdalConfiguration config,
     string clientId,
     string certificate,
     AzureAccount.AccountType credentialType)
 {
     switch (credentialType)
     {
         case AzureAccount.AccountType.ServicePrincipal:
             return servicePrincipalTokenProvider.GetAccessTokenWithCertificate(config, clientId, certificate, credentialType);
         default:
             throw new ArgumentException(string.Format(Resources.UnsupportedCredentialType, credentialType), "credentialType");
     }
 }
Пример #7
0
        public IAccessToken GetAccessToken(
            AdalConfiguration config,
            string promptBehavior,
            Action <string> promptAction,
            string userId,
            SecureString password,
            string credentialType)
        {
            if (credentialType != AzureAccount.AccountType.User)
            {
                throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
            }

            return(new AdalAccessToken(AcquireToken(config, promptBehavior, promptAction, userId, password), this, config));
        }
Пример #8
0
 public IAccessToken GetAccessTokenWithCertificate(
     AdalConfiguration config,
     string clientId,
     string certificateThumbprint,
     AzureAccount.AccountType credentialType)
 {
     if (credentialType == AzureAccount.AccountType.User)
     {
         throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
     }
     return(new ServicePrincipalAccessToken(
                config,
                AcquireTokenWithCertificate(config, clientId, certificateThumbprint),
                (adalConfig, appId) => this.RenewWithCertificate(adalConfig, appId, certificateThumbprint), clientId));
 }
        private AuthenticationResult AcquireTokenWithCertificate(
            AdalConfiguration config,
            string appId,
            string thumbprint)
        {
            var certificate = AzureSession.Instance.DataStore.GetCertificate(thumbprint);

            if (certificate == null)
            {
                throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, thumbprint));
            }

            var context = GetContext(config);

            return(context.AcquireToken(config.ResourceClientUri, new ClientAssertionCertificate(appId, certificate)));
        }
Пример #10
0
        // We have to run this in a separate thread to guarantee that it's STA. This method
        // handles the threading details.
        private AuthenticationResult AcquireToken(
            AdalConfiguration config,
            string promptBehavior,
            Action <string> promptAction,
            string userId,
            SecureString password)
        {
            AuthenticationResult result = null;
            Exception            ex     = null;

            if (promptBehavior == ShowDialog.Never)
            {
                result = SafeAquireToken(config, promptBehavior, promptAction, userId, password, out ex);
            }
            else
            {
                var thread = new Thread(() =>
                {
                    result = SafeAquireToken(config, promptBehavior, promptAction, userId, password, out ex);
                });

                thread.SetApartmentState(ApartmentState.STA);
                thread.Name = "AcquireTokenThread";
                thread.Start();
                thread.Join();
            }

            if (ex != null)
            {
                var adex = ex as AdalException;
                if (adex != null)
                {
                    if (adex.ErrorCode == AdalError.AuthenticationCanceled)
                    {
                        throw new AadAuthenticationCanceledException(adex.Message, adex);
                    }
                }
                if (ex is AadAuthenticationException)
                {
                    throw ex;
                }
                throw new AadAuthenticationFailedException(GetExceptionMessage(ex), ex);
            }

            return(result);
        }
Пример #11
0
        private AuthenticationResult AcquireTokenWithCertificate(
            AdalConfiguration config,
            string appId,
            string thumbprint)
        {
            var certificate = AzureSession.Instance.DataStore.GetCertificate(thumbprint);

            if (certificate == null)
            {
                throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, thumbprint));
            }

            var context = GetContext(config);

            return(context.AcquireTokenAsync(config.ResourceClientUri, new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate(appId, certificate))
                   .ConfigureAwait(false).GetAwaiter().GetResult());
        }
Пример #12
0
        private AuthenticationResult AcquireTokenWithSecret(AdalConfiguration config, string appId, SecureString appKey)
        {
            if (appKey == null)
            {
                return RenewWithSecret(config, appId);
            }

            StoreAppKey(appId, config.AdDomain, appKey);
            var context = GetContext(config);
#if !NETSTANDARD
            var credential = new ClientCredential(appId, appKey);
            return context.AcquireToken(config.ResourceClientUri, credential);
#else
            var credential = new ClientCredential(appId, ConversionUtilities.SecureStringToString(appKey));
            return context.AcquireTokenAsync(config.ResourceClientUri, credential).ConfigureAwait(false).GetAwaiter().GetResult();
#endif
        }
Пример #13
0
 public IAccessToken GetAccessToken(
     AdalConfiguration config,
     ShowDialog promptBehavior,
     string userId,
     SecureString password,
     AzureAccount.AccountType credentialType)
 {
     switch (credentialType)
     {
         case AzureAccount.AccountType.User:
             return userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         case AzureAccount.AccountType.ServicePrincipal:
             return servicePrincipalTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         default:
             throw new ArgumentException(Resources.UnknownCredentialType, "credentialType");
     }
 }
        private AuthenticationResult DoAcquireToken(
            AdalConfiguration config,
            string userId,
            SecureString password,
            Action <string> promptAction,
            bool renew = false)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(
                Resources.UPNAcquireTokenContextTrace,
                context.Authority,
                context.CorrelationId,
                context.ValidateAuthority);
            TracingAdapter.Information(
                Resources.UPNAcquireTokenConfigTrace,
                config.AdDomain,
                config.AdEndpoint,
                config.ClientId,
                config.ClientRedirectUri);
            if (promptAction == null || renew)
            {
                result = context.AcquireTokenSilentAsync(config.ResourceClientUri, config.ClientId,
                                                         new UserIdentifier(userId, UserIdentifierType.OptionalDisplayableId))
                         .ConfigureAwait(false).GetAwaiter().GetResult();
            }
            else if (string.IsNullOrEmpty(userId) || password == null)
            {
                var code = context.AcquireDeviceCodeAsync(config.ResourceClientUri, config.ClientId)
                           .ConfigureAwait(false).GetAwaiter().GetResult();
                promptAction(code?.Message);

                result = context.AcquireTokenByDeviceCodeAsync(code)
                         .ConfigureAwait(false).GetAwaiter().GetResult();
            }
            else
            {
                UserCredential credential = new UserCredential(userId);
                result = context.AcquireTokenAsync(config.ResourceClientUri, config.ClientId, credential)
                         .ConfigureAwait(false).GetAwaiter().GetResult();
            }

            return(result);
        }
Пример #15
0
        private AuthenticationResult SafeAquireToken(
            AdalConfiguration config,
            string showDialog,
            Action <string> promptAction,
            string userId,
            SecureString password,
            out Exception ex)
        {
            try
            {
                ex = null;
                var promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                return(DoAcquireToken(config, promptBehavior, promptAction, userId, password));
            }
            catch (AdalException adalEx)
            {
                if (adalEx.ErrorCode == AdalError.UserInteractionRequired ||
                    adalEx.ErrorCode == AdalError.MultipleTokensMatched)
                {
                    string message = Resources.AdalUserInteractionRequired;
                    if (adalEx.ErrorCode == AdalError.MultipleTokensMatched)
                    {
                        message = Resources.AdalMultipleTokens;
                    }

                    ex = new AadAuthenticationFailedWithoutPopupException(message, adalEx);
                }
                else if (adalEx.ErrorCode == AdalError.MissingFederationMetadataUrl ||
                         adalEx.ErrorCode == AdalError.FederatedServiceReturnedError)
                {
                    ex = new AadAuthenticationFailedException(Resources.CredentialOrganizationIdMessage, adalEx);
                }
                else
                {
                    ex = adalEx;
                }
            }
            catch (Exception threadEx)
            {
                ex = threadEx;
            }
            return(null);
        }
        public IAccessToken GetAccessToken(
            AdalConfiguration config,
            string promptBehavior,
            string userId,
            SecureString password,
            string credentialType)
        {
            switch (credentialType)
            {
            case AzureAccount.AccountType.User:
                return(userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType));

            case AzureAccount.AccountType.ServicePrincipal:
                return(servicePrincipalTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType));

            default:
                throw new ArgumentException(Resources.UnknownCredentialType, "credentialType");
            }
        }
Пример #17
0
        private AuthenticationResult AcquireTokenWithCertificate(
            AdalConfiguration config,
            string appId,
            string thumbprint)
        {
            var certificate = AzureSession.Instance.DataStore.GetCertificate(thumbprint);
            if (certificate == null)
            {
                throw new ArgumentException(string.Format(Resources.CertificateNotFoundInStore, thumbprint));
            }

            var context = GetContext(config);
#if !NETSTANDARD
            return context.AcquireToken(config.ResourceClientUri, new ClientAssertionCertificate(appId, certificate));
#else
            return context.AcquireTokenAsync(config.ResourceClientUri, new ClientAssertionCertificate(appId, certificate))
                          .ConfigureAwait(false).GetAwaiter().GetResult();
#endif
        }
Пример #18
0
        private AuthenticationResult RenewWithSecret(AdalConfiguration config, string appId)
        {
            TracingAdapter.Information(Resources.SPNRenewTokenTrace, appId, config.AdDomain, config.AdEndpoint,
                config.ClientId, config.ClientRedirectUri);
#if !NETSTANDARD
            using (SecureString appKey = LoadAppKey(appId, config.AdDomain))
            {
#else
                var appKey = LoadAppKey(appId, config.AdDomain);
#endif
                if (appKey == null)
                {
                    throw new KeyNotFoundException(string.Format(Resources.ServiceKeyNotFound, appId));
                }
                return AcquireTokenWithSecret(config, appId, appKey);
#if !NETSTANDARD
            }
#endif
        }
Пример #19
0
        private AuthenticationResult DoAcquireToken(AdalConfiguration config, PromptBehavior promptBehavior, string userId,
                                                    SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(Resources.UPNAcquireTokenContextTrace, context.Authority, context.CorrelationId,
                                       context.ValidateAuthority);
            TracingAdapter.Information(Resources.UPNAcquireTokenConfigTrace, config.AdDomain, config.AdEndpoint,
                                       config.ClientId, config.ClientRedirectUri);
            if (string.IsNullOrEmpty(userId))
            {
                if (promptBehavior != PromptBehavior.Never)
                {
                    ClearCookies();
                }

                result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                                              config.ClientRedirectUri, promptBehavior,
                                              UserIdentifier.AnyUser, AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                if (password == null)
                {
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId,
                                                  config.ClientRedirectUri, promptBehavior,
                                                  new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId),
                                                  AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return(result);
        }
 private AuthenticationContext CreateContext(AdalConfiguration config)
 {
     return(new AuthenticationContext(config.AdEndpoint + config.AdDomain,
                                      config.ValidateAuthority, config.TokenCache));
 }
Пример #21
0
 public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string clientId, string certificate, AzureAccount.AccountType credentialType)
 {
     throw new NotImplementedException();
 }
Пример #22
0
 public IAccessToken GetAccessTokenWithCertificate(
     AdalConfiguration config,
     string clientId,
     string certificate,
     AzureAccount.AccountType credentialType)
 {
     throw new NotImplementedException();
 }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
 public AdalAccessToken(AuthenticationResult authResult, UserTokenProvider tokenProvider, AdalConfiguration configuration)
 {
     AuthResult         = authResult;
     this.tokenProvider = tokenProvider;
     Configuration      = configuration;
 }
Пример #25
0
        // We have to run this in a separate thread to guarantee that it's STA. This method
        // handles the threading details.
        private AuthenticationResult AcquireToken(AdalConfiguration config, ShowDialog promptBehavior, string userId,
            SecureString password)
        {
            AuthenticationResult result = null;
            Exception ex = null;
            if (promptBehavior == ShowDialog.Never)
            {
                result = SafeAquireToken(config, promptBehavior, userId, password, out ex);
            }
            else
            {
                var thread = new Thread(() =>
                {
                    result = SafeAquireToken(config, promptBehavior, userId, password, out ex);
                });

                thread.SetApartmentState(ApartmentState.STA);
                thread.Name = "AcquireTokenThread";
                thread.Start();
                thread.Join();
            }

            if (ex != null)
            {
                var adex = ex as AdalException;
                if (adex != null)
                {
                    if (adex.ErrorCode == AdalError.AuthenticationCanceled)
                    {
                        throw new AadAuthenticationCanceledException(adex.Message, adex);
                    }
                }
                if (ex is AadAuthenticationException)
                {
                    throw ex;
                }
                throw new AadAuthenticationFailedException(GetExceptionMessage(ex), ex);
            }

            return result;
        }
 private AuthenticationContext GetContext(AdalConfiguration config)
 {
     string authority = config.AdEndpoint + config.AdDomain;
     return new AuthenticationContext(authority, config.ValidateAuthority, config.TokenCache);
 }
Пример #27
0
        private AuthenticationResult SafeAquireToken(
            AdalConfiguration config,
            ShowDialog showDialog,
            string userId,
            SecureString password,
            out Exception ex)
        {
            try
            {
                ex = null;
                var promptBehavior = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), showDialog.ToString());

                return DoAcquireToken(config, promptBehavior, userId, password);
            }
            catch (AdalException adalEx)
            {
                if (adalEx.ErrorCode == AdalError.UserInteractionRequired ||
                    adalEx.ErrorCode == AdalError.MultipleTokensMatched)
                {
                    string message = Resources.AdalUserInteractionRequired;
                    if (adalEx.ErrorCode == AdalError.MultipleTokensMatched)
                    {
                        message = Resources.AdalMultipleTokens;
                    }

                    ex = new AadAuthenticationFailedWithoutPopupException(message, adalEx);
                }
                else if (adalEx.ErrorCode == AdalError.MissingFederationMetadataUrl)
                {
                    ex = new AadAuthenticationFailedException(Resources.CredentialOrganizationIdMessage, adalEx);
                }
                else
                {
                    ex = adalEx;
                }
            }
            catch (Exception threadEx)
            {
                ex = threadEx;
            }
            return null;
        }
Пример #28
0
        private AuthenticationResult DoAcquireToken(
            AdalConfiguration config,
            PromptBehavior promptBehavior,
            string userId,
            SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(
                Resources.UPNAcquireTokenContextTrace,
                context.Authority,
                context.CorrelationId,
                context.ValidateAuthority);
            TracingAdapter.Information(
                Resources.UPNAcquireTokenConfigTrace,
                config.AdDomain,
                config.AdEndpoint,
                config.ClientId,
                config.ClientRedirectUri);
            if (string.IsNullOrEmpty(userId))
            {
                if (promptBehavior != PromptBehavior.Never)
                {
                    AdalTokenCache.ClearCookies();
                }

                result = context.AcquireToken(
                    config.ResourceClientUri,
                    config.ClientId,
                    config.ClientRedirectUri,
                    promptBehavior,
                    UserIdentifier.AnyUser,
                    AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                if (password == null)
                {
                    result = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return result;
        }
 public ServicePrincipalAccessToken(AdalConfiguration configuration, AuthenticationResult authResult, Func<AdalConfiguration, string, AuthenticationResult> tokenRenewer, string appId)
 {
     Configuration = configuration;
     AuthResult = authResult;
     this.tokenRenewer = tokenRenewer;
     this.appId = appId;
 }
Пример #30
0
 public AdalAccessToken(AuthenticationResult authResult, UserTokenProvider tokenProvider, AdalConfiguration configuration)
 {
     AuthResult = authResult;
     this.tokenProvider = tokenProvider;
     Configuration = configuration;
 }
Пример #31
0
 private AuthenticationContext CreateContext(AdalConfiguration config)
 {
     return new AuthenticationContext(config.AdEndpoint + config.AdDomain, config.ValidateAuthority, config.TokenCache)
     {
         OwnerWindow = parentWindow
     };
 }
 public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string principalId, string certificateThumbprint, string credentialType)
 {
     throw new NotImplementedException();
 }
 IAccessToken ITokenProvider.GetAccessTokenWithCertificate(AdalConfiguration config, string principalId, string certificateThumbprint,
     AzureAccount.AccountType credentialType)
 {
     return GetAccessTokenWithCertificate(config, principalId, certificateThumbprint, credentialType);
 }
        private AuthenticationContext GetContext(AdalConfiguration config)
        {
            string authority = config.AdEndpoint + config.AdDomain;

            return(new AuthenticationContext(authority, config.ValidateAuthority, config.TokenCache));
        }
 private AuthenticationResult RenewWithCertificate(AdalConfiguration config, string appId,
     string thumbprint)
 {
     TracingAdapter.Information(Resources.SPNRenewTokenTrace, appId, config.AdDomain, config.AdEndpoint, 
         config.ClientId, config.ClientRedirectUri);
     return AcquireTokenWithCertificate(config, appId, thumbprint);
 }
 public IAccessToken GetAccessTokenWithCertificate(AdalConfiguration config, string principalId, string certificateThumbprint, AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
Пример #37
0
        private AuthenticationResult DoAcquireToken(
            AdalConfiguration config,
            PromptBehavior promptBehavior,
            Action <string> promptAction,
            string userId,
            SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(
                Resources.UPNAcquireTokenContextTrace,
                context.Authority,
                context.CorrelationId,
                context.ValidateAuthority);
            TracingAdapter.Information(
                Resources.UPNAcquireTokenConfigTrace,
                config.AdDomain,
                config.AdEndpoint,
                config.ClientId,
                config.ClientRedirectUri);
            if (string.IsNullOrEmpty(userId))
            {
                if (promptBehavior != PromptBehavior.Never)
                {
                    AdalTokenCache.ClearCookies();
                }

                Guid tempGuid = Guid.Empty;
                if (!string.Equals(config.AdDomain, "Common", StringComparison.OrdinalIgnoreCase) && !Guid.TryParse(config.AdDomain, out tempGuid))
                {
                    var tempResult = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        UserIdentifier.AnyUser,
                        AdalConfiguration.EnableEbdMagicCookie);
                    config.AdDomain = tempResult.TenantId;
                    context         = CreateContext(config);
                    promptBehavior  = PromptBehavior.Never;
                }

                result = context.AcquireToken(
                    config.ResourceClientUri,
                    config.ClientId,
                    config.ClientRedirectUri,
                    promptBehavior,
                    UserIdentifier.AnyUser,
                    AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                if (password == null)
                {
                    result = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return(result);
        }