public override void AddPromptBehaviorQueryParameter(IPlatformParameters parameters, DictionaryRequestParameters authorizationRequestParameters)
        {
            PlatformParameters authorizationParameters = (parameters as PlatformParameters);

            if (authorizationParameters == null)
            {
                throw new ArgumentException("parameters should be of type PlatformParameters", "parameters");
            }

            PromptBehavior promptBehavior = authorizationParameters.PromptBehavior;

            // ADFS currently ignores the parameter for now.
            switch (promptBehavior)
            {
            case PromptBehavior.Always:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login;
                break;

            case PromptBehavior.RefreshSession:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession;
                break;

            case PromptBehavior.Never:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.AttemptNone;
                break;
            }
        }
 /// <summary>
 /// Acquires the graph token.
 /// </summary>
 /// <param name="tenantId">The tenant identifier.</param>
 /// <param name="promptBehavior">The prompt behavior.</param>
 /// <param name="userIdentifier">Optional user for which token is to be fetched.</param>
 /// <returns>AAD authentication result.</returns>
 private AuthenticationResult AcquireGraphToken(string tenantId, PromptBehavior promptBehavior = PromptBehavior.Never, UserIdentifier userIdentifier = null)
 {
     try
     {
         if (userIdentifier == null)
         {
             return(new AuthenticationContext(AADLoginAuthority + tenantId, false, TokenCache.DefaultShared).AcquireTokenAsync(
                        AzureAADResource,
                        PSClientId,
                        PSRedirectUrl,
                        new PlatformParameters(promptBehavior)).ConfigureAwait(false).GetAwaiter().GetResult());
         }
         else
         {
             return(new AuthenticationContext(AADLoginAuthority + tenantId, false, TokenCache.DefaultShared).AcquireTokenAsync(
                        AzureAADResource,
                        PSClientId,
                        PSRedirectUrl,
                        new PlatformParameters(promptBehavior),
                        userIdentifier).ConfigureAwait(false).GetAwaiter().GetResult());
         }
     }
     catch (Exception ex)
     {
         Logger.LogError(CallInfo.Site(), ex, "Failed to acquire token for tenant Id '{0}'", tenantId);
         throw;
     }
 }
示例#3
0
        private static string GetInteractiveClientToken(PACClientInfo clientInfo, PromptBehavior behavior)
        {
            // Dummy endpoint just to get unauthorized response
            var client  = new HttpClient();
            var query   = $"{clientInfo.ServiceUrl}/api/status/4799049A-E623-4B2A-818A-3A674E106DE5";
            var request = new HttpRequestMessage(HttpMethod.Get, new Uri(query));

            using (var response = client.SendAsync(request).GetAwaiter().GetResult())
            {
                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    // Method below found here: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/Acquiring-tokens-interactively---Public-client-application-flows
                    var authParams  = AuthenticationParameters.CreateFromUnauthorizedResponseAsync(response).GetAwaiter().GetResult();
                    var authContext = new AuthenticationContext(authParams.Authority);
                    var authResult  = authContext.AcquireTokenAsync(
                        resourceUrl,
                        clientInfo.ClientId.ToString(),
                        new Uri(redirectUrl),
                        new PlatformParameters(behavior)).GetAwaiter().GetResult();
                    return(authResult.AccessToken);
                }
                else
                {
                    throw new Exception($"Unable to connect to the service for authorization information. {response.ReasonPhrase}");
                }
            }
        }
示例#4
0
        async Task <AuthenticationResult> AcquireToken(string tenantId, PromptBehavior promptBehavior, string userUniqueId = null, bool useGraphAuth = false)
        {
            var authUrl = authBaseUrl + tenantId;

            if (Uri.IsWellFormedUriString(tenantId, UriKind.Absolute))
            {
                authUrl = tenantId;
            }
            var ac       = new AuthenticationContext(authUrl, fileCache);
            var tokenUrl = useGraphAuth ? graphBaseUrl : armBaseUrl;

            AuthenticationResult result = null;

            try
            {
                if (!string.IsNullOrWhiteSpace(userUniqueId))
                {
                    result = await ac.AcquireTokenAsync(tokenUrl,
                                                        powershellAppId, powershellReturnUrl,
                                                        new PlatformParameters(promptBehavior),
                                                        new UserIdentifier(userUniqueId, UserIdentifierType.UniqueId)).ConfigureAwait(false);
                }
                else
                {
                    result = await ac.AcquireTokenAsync(tokenUrl, powershellAppId,
                                                        powershellReturnUrl, new PlatformParameters(promptBehavior)).ConfigureAwait(false);
                }
            }
            catch (HttpRequestException exn)
            {
            }

            return(result);
        }
示例#5
0
        private Program(string[] args)
        {
            if (args.Length < 1 || (args.Length > 0 && string.CompareOrdinal(args[0], "-h") == 0))
            {
                Console.WriteLine($@"
Usage:
  {Process.GetCurrentProcess().ProcessName} <environmentUrl> [<usernameOrAppId> [ <secret> ]]

options:
    Without username and password cmd line arguments, MSAL's AAD login dialog will prompt interactively.
    Instead of passing the secret as the third parameter, set an environment variable 'PP_BT_ENV_SECRET' with that secret
");
                Environment.Exit(1);
            }
            EnvUrl = new Uri(args[0]);

            if (args.Length > 1)
            {
                UserNameOrAppId = args[1];
                IsAppUser       = Guid.TryParse(UserNameOrAppId, out var _);
            }

            Secret = args.Length > 2 ? args[2] : Environment.GetEnvironmentVariable("PP_BT_ENV_SECRET");
            if (!string.IsNullOrWhiteSpace(Secret))
            {
                PromptBehavior = PromptBehavior.Never;
            }
        }
示例#6
0
        /// <summary>
        /// Authenticates with the currently set environment parameters.
        /// </summary>
        /// <param name="promptBehavior">The ADAL prompt behavior (default is "Auto")</param>
        /// <returns>The authentication result.</returns>
        /// <exception cref="AdalException">If authentication fails</exception>
        internal static SdkAuthResult Auth(PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            // If there have been no successful logins with the module and the PromptBehavior is anything other than "Never", force an interactive window
            if (LatestAdalAuthResult == null && promptBehavior != PromptBehavior.Never)
            {
                promptBehavior = PromptBehavior.SelectAccount;
            }

            // Get the environment parameters
            EnvironmentParameters environmentParameters = AuthUtils.CurrentEnvironmentParameters;

            // Create auth context that we will use to connect to the AAD endpoint
            AuthenticationContext authContext = new AuthenticationContext(environmentParameters.AuthUrl);

            // Get the AuthenticationResult from AAD
            AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(
                environmentParameters.ResourceId,
                environmentParameters.AppId,
                new Uri(environmentParameters.RedirectLink),
                new PlatformParameters(promptBehavior))
                                                        .GetAwaiter().GetResult();

            // Convert the auth result into our own type
            SdkAuthResult authResult = authenticationResult.ToSdkAuthResult();

            // Save the auth result
            AuthUtils.LatestAdalAuthResult = authResult;

            return(authResult);
        }
        public override void AddPromptBehaviorQueryParameter(IPlatformParameters parameters, DictionaryRequestParameters authorizationRequestParameters)
        {
            PlatformParameters authorizationParameters = (parameters as PlatformParameters);

            if (authorizationParameters == null)
            {
                throw new ArgumentException("parameters should be of type PlatformParameters", "parameters");
            }

            PromptBehavior promptBehavior = authorizationParameters.PromptBehavior;

            switch (promptBehavior)
            {
            case PromptBehavior.Always:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.Login;
                break;

            case PromptBehavior.SelectAccount:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.SelectAccount;
                break;

            case PromptBehavior.RefreshSession:
                authorizationRequestParameters[OAuthParameter.Prompt] = PromptValue.RefreshSession;
                break;
            }
        }
示例#8
0
        //see: https://azure.microsoft.com/en-us/resources/samples/data-lake-analytics-dotnet-auth-options/
        private static ServiceClientCredentials GetCreds_User_Popup(
            string tenant,
            System.Uri tokenAudience,
            string clientId,
            PromptBehavior promptBehavior = PromptBehavior.Auto)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var clientSettings = new ActiveDirectoryClientSettings
            {
                ClientId          = clientId,
                ClientRedirectUri = new System.Uri("urn:ietf:wg:oauth:2.0:oob"),
                PromptBehavior    = promptBehavior
            };

            var serviceSettings = ActiveDirectoryServiceSettings.Azure;

            serviceSettings.TokenAudience = tokenAudience;

            var creds = UserTokenProvider.LoginWithPromptAsync(
                tenant,
                clientSettings,
                serviceSettings).GetAwaiter().GetResult();

            return(creds);
        }
示例#9
0
 public static HttpClient GetClient(PACClientInfo clientInfo, PromptBehavior behavior)
 {
     if (clientInfo.ClientId.Equals(Guid.Empty))
     {
         throw new ArgumentNullException("clientId");
     }
     if (string.IsNullOrEmpty(clientInfo.Token))
     {
         if (!clientInfo.TenantId.Equals(Guid.Empty) && !string.IsNullOrEmpty(clientInfo.ClientSec))
         {
             clientInfo.Token = GetApplicationClientToken(clientInfo);
         }
         else if (!string.IsNullOrEmpty(clientInfo.ServiceUrl))
         {
             clientInfo.Token = GetInteractiveClientToken(clientInfo, behavior);
         }
     }
     if (!string.IsNullOrEmpty(clientInfo.Token))
     {
         var client = new HttpClient();
         client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", clientInfo.Token);
         client.DefaultRequestHeaders.Add("accept", "application/json,application/x-ms-sarif-v2");
         client.DefaultRequestHeaders.Add("x-ms-tenant-id", clientInfo.TenantId.ToString());
         return(client);
     }
     throw new ArgumentException("Not enough parameters to connect PAC Client");
 }
示例#10
0
        private static IPlatformParameters GetPlatformParametersInstance(string promptBehaviorString)
        {
            IPlatformParameters platformParameters = null;
            PromptBehavior      pb = PromptBehavior.Auto;

            if (!string.IsNullOrEmpty(promptBehaviorString))
            {
                pb = (PromptBehavior)Enum.Parse(typeof(PromptBehavior), promptBehaviorString, true);
            }

#if __ANDROID__
            platformParameters = new PlatformParameters(this);
#else
#if __IOS__
            platformParameters = new PlatformParameters(this);
#else
#if (WINDOWS_UWP || WINDOWS_APP)
            platformParameters = new PlatformParameters(PromptBehavior.Always, false);
#else
            //desktop
            platformParameters = new PlatformParameters(pb, null);
#endif
#endif
#endif
            return(platformParameters);
        }
        public static bool Login(string tenantName, string destUrl, PromptBehavior behavior)
        {
            if (Helper == null)
            {
                Helper = new SPOServiceHelper();
            }

            if (string.IsNullOrEmpty(tenantName) && !string.IsNullOrEmpty(SpecifiedTenantName))
            {
                tenantName = SpecifiedTenantName;
            }

            if (!string.IsNullOrEmpty(destUrl) && !destUrl.StartsWith("/"))
            {
                destUrl = "/" + destUrl;
            }

            var baseLogin = string.Format(baseFormat, tenantName);
            var destSite  = new Uri(string.Format(subFormat, tenantName, destUrl));

            try
            {
                var service = Helper.InstantiateSPOService(destSite, baseLogin, null, COMMON_AUTH_URL, behavior);
                SP1 = service.Context;
            }
            catch
            {
                return(false);
            }
            SpecifiedTenantName = tenantName;
            return(Connected);
        }
        private AuthenticationResult DoAcquireToken(AdalConfiguration config, PromptBehavior promptBehavior, string userId,
                                                    SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            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.OptionalDisplayableId),
                                                  AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return(result);
        }
示例#13
0
        private string GetToken(string tenantId, PromptBehavior promptBehavior, bool updateUI = false)
        {
            //"d94647e7-c4ff-4a93-bbe0-d993badcc5b8"
            AuthenticationContext context = new AuthenticationContext(ServiceUrls.GetLoginUrl(app.Default.AzureAuth) + tenantId);

            AuthenticationResult result = null;

            try
            {
                result = context.AcquireToken(ServiceUrls.GetServiceManagementUrl(app.Default.AzureAuth), app.Default.ClientId, new Uri(app.Default.ReturnURL), promptBehavior);
                if (result == null)
                {
                    throw new InvalidOperationException("Failed to obtain the token");
                }
                if (updateUI)
                {
                    // lblSignInText.Text = $"Signed in as {result.UserInfo.DisplayableId}";
                }

                return(result.AccessToken);
            }
            catch (Exception exception)
            {
                DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
示例#14
0
 public AzureContext(AzureRetriever azureRetriever, TargetSettings targetSettings, PromptBehavior defaultPromptBehavior = PromptBehavior.Always)
 {
     _AzureRetriever      = azureRetriever;
     _TargetSettings      = targetSettings;
     _LogProvider         = azureRetriever.LogProvider;
     _StatusProvider      = azureRetriever.StatusProvider;
     _LoginPromptBehavior = defaultPromptBehavior;
 }
 public Task<IAuthenticationResult> AcquireTokenAsync(
     string resource,
     string clientId,
     Uri redirectUri,
     PromptBehavior promptBehavior,
     UserIdentifier userIdentifier)
 {
     return Task.FromResult(this.AcquireTokenAsyncCallback(resource, clientId, redirectUri, userIdentifier));
 }
        public IWebUI Create(PromptBehavior promptBehavior, object ownerWindow)
        {
            InitializeFactoryMethod();

            object[] parameters = { promptBehavior };
            IWebUI dialog = (IWebUI)dialogFactory.Invoke(null, parameters);
            dialog.OwnerWindow = ownerWindow;
            return dialog;
        }
 public Task <IAuthenticationResult> AcquireTokenAsync(
     string resource,
     string clientId,
     Uri redirectUri,
     PromptBehavior promptBehavior,
     UserIdentifier userIdentifier)
 {
     return(Task.FromResult(this.AcquireTokenAsyncCallback(resource, clientId, redirectUri, userIdentifier)));
 }
        /// <summary>
        /// Use to refresh expired tokens. Technically this is not using the refresh token, as ADAL (v3?) is fine with just using AcquireToken and not AcquireTokenByRefreshToken
        /// </summary>
        /// <returns></returns>
        public static AuthenticationResult GetAccessToken(bool silent)
        {
            // Create the authentication context (ADAL)
            using (Log.VerboseCall())
            {
                AuthenticationResult result = null;
                try
                {
                    //Authority e.g.: https://login.microsoftonline.com/common/mydomain.onmicrosoft.com/
                    var authenticationContext = new AuthenticationContext(Authority);

                    PromptBehavior promptBehavior = PromptBehavior.Auto;

                    //These settings don't seem to change any behaviour; remove for now
                    //switch (Settings.Default.LoginMode)
                    //{
                    //    case "Always":
                    //        promptBehavior = PromptBehavior.Always;
                    //        break;
                    //    case "Automatic":
                    //        promptBehavior = PromptBehavior.Auto;
                    //        break;
                    //    case "Refresh":
                    //        promptBehavior = PromptBehavior.RefreshSession;
                    //        break;
                    //    default:
                    //        promptBehavior = PromptBehavior.RefreshSession;
                    //        break;
                    //}

                    // Get the access token
                    if (silent)
                    {
                        result = authenticationContext.AcquireToken(GraphResource, ClientId, RedirectUri);
                    }
                    else
                    {
                        result = authenticationContext.AcquireToken(GraphResource, ClientId, RedirectUri, promptBehavior);
                    }
                    if (result != null)
                    {
                        TokenExpiresAt = result.ExpiresOn;
                        Log.InfoFormat(
                            "Access token retrieved: {0} (AccessTokenType: {1}; ExpiresOn: {2}; IdToken: {3}; RefreshToken: {4}; TenantID: {5}; User: {6}",
                            result.AccessToken, result.AccessTokenType, result.ExpiresOn, result.IdToken,
                            result.RefreshToken, result.TenantId, result.UserInfo?.DisplayableId);
                    }
                }
                catch (Exception ex)
                {
                    //Watch for {"authentication_canceled: User canceled authentication"}; or when cancelling final step: {"AADSTS65004: The resource owner or authorization server denied the request.\r\nTrace ID: e5e00775-0f74-4d61-9e0e-38398cd768da\r\nCorrelation ID: edce93a1-20d7-41da-b672-12ef1c2c2644\r\nTimestamp: 2016-12-14 19:33:17Z"}
                    Log.Error(ex);
                }

                return(result);
            }
        }
示例#19
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();
                }

                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);
        }
示例#20
0
        public WebUI(IPlatformParameters parameters)
        {
            if (!(parameters is PlatformParameters))
            {
                throw new ArgumentException("parameters should be of type PlatformParameters", "parameters");
            }

            this.promptBehavior = ((PlatformParameters)parameters).PromptBehavior;
            this.useCorporateNetwork = ((PlatformParameters)parameters).UseCorporateNetwork;
        }
        public IWebUI Create(PromptBehavior promptBehavior, object ownerWindow)
        {
            InitializeFactoryMethod();

            object[] parameters = { promptBehavior };
            IWebUI   dialog     = (IWebUI)dialogFactory.Invoke(null, parameters);

            dialog.OwnerWindow = ownerWindow;
            return(dialog);
        }
示例#22
0
        public WebUI(IPlatformParameters parameters)
        {
            if (!(parameters is PlatformParameters))
            {
                throw new ArgumentException("parameters should be of type PlatformParameters", "parameters");
            }

            this.promptBehavior      = ((PlatformParameters)parameters).PromptBehavior;
            this.useCorporateNetwork = ((PlatformParameters)parameters).UseCorporateNetwork;
        }
示例#23
0
        public async override void HandleMessage(Message msg)
        {
            PromptBehavior       promptBehavior = (PromptBehavior)msg.What;
            AuthenticationResult result         = await manager.Authenticate(activity, promptBehavior);

            // If we were able to get an access token, return to the main view
            if (result != null && result.AccessToken != null)
            {
                listener.OnSignedIn(result);
            }
        }
        /// <summary>
        /// Authenticates the user using <see cref="AuthenticationContext.AcquireTokenAsync(string, string, Uri, PromptBehavior, UserIdentifier)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientId">The client ID of the application.</param>
        /// <param name="redirectUri">The redirect URI of the application.</param>
        /// <param name="promptBehavior">The <see cref="PromptBehavior"/> for authentication.</param>
        /// <param name="userIdentifier">The <see cref="UserIdentifier"/> for authentication.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public async Task<IAuthenticationResult> AcquireTokenAsync(
            string resource,
            string clientId,
            Uri redirectUri,
            PromptBehavior promptBehavior,
            UserIdentifier userIdentifier)
        {
            var result = await this.authenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, promptBehavior, userIdentifier);

            return result == null ? null : new AuthenticationResultWrapper(result);
        }
示例#25
0
        /// <summary>
        /// Authenticates the user using <see cref="AuthenticationContext.AcquireTokenAsync(string, string, Uri, PromptBehavior, UserIdentifier)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientId">The client ID of the application.</param>
        /// <param name="redirectUri">The redirect URI of the application.</param>
        /// <param name="promptBehavior">The <see cref="PromptBehavior"/> for authentication.</param>
        /// <param name="userIdentifier">The <see cref="UserIdentifier"/> for authentication.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public async Task <IAuthenticationResult> AcquireTokenAsync(
            string resource,
            string clientId,
            Uri redirectUri,
            PromptBehavior promptBehavior,
            UserIdentifier userIdentifier)
        {
            var result = await this.authenticationContext.AcquireTokenAsync(resource, clientId, redirectUri, promptBehavior, userIdentifier);

            return(result == null ? null : new AuthenticationResultWrapper(result));
        }
        /// <summary>
        /// Authenticates the user.
        /// </summary>
        /// <param name="behavior">The ADAL prompt behavior.</param>
        /// <returns>The authentication result.</returns>
        public async Task <AuthenticationResult> Authenticate(PromptBehavior behavior)
        {
            // Check initial authentication values.
            if (_clientID.Equals(_placeholderClientID) || _redirectURI.Equals(_placeholderRedirectURI))
            {
                Toast.MakeText(Android.App.Application.Context, "Please update the authentication values for your application.", ToastLength.Long).Show();
                Log.Info(_logTagAuth, "Authentication cancelled. Authentication values need to be updated with user provided values." +
                         " Client ID = " + _clientID + " Redirect URI = " + _redirectURI);
                return(null);
            }

            if (!Uri.IsWellFormedUriString(_redirectURI, UriKind.RelativeOrAbsolute))
            {
                Toast.MakeText(Android.App.Application.Context, "Please correct the redirect URI for your application.", ToastLength.Long).Show();
                Log.Info(_logTagAuth, "Authentication cancelled. Redirect URI needs to be corrected with a well-formed value." +
                         " Redirect URI = " + _redirectURI);
                return(null);
            }

            AuthenticationResult result = null;

            // Register the callback to capture ADAL logs.
            LoggerCallbackHandler.LogCallback       = ADALLog;
            LoggerCallbackHandler.PiiLoggingEnabled = true;

            // Attempt to sign the user in silently.
            result = await SignInSilent(_resourceID, null);

            // If the user cannot be signed in silently, prompt the user to manually sign in.
            if (result == null)
            {
                result = await SignInWithPrompt(new PlatformParameters((Activity)Forms.Context, false, behavior));
            }

            // If auth was successful, cache the values and log the success.
            if (result != null && result.AccessToken != null)
            {
                _cachedUPN   = result.UserInfo.DisplayableId;
                _cachedAADID = result.UserInfo.UniqueId;

                Log.Info(_logTagAuth, "Authentication succeeded. UPN = " + _cachedUPN);

                // Register the account for MAM
                // See: https://docs.microsoft.com/en-us/intune/app-sdk-android#account-authentication
                // This app requires ADAL authentication prior to MAM enrollment so we delay the registration
                // until after the sign in flow.
                IMAMEnrollmentManager mgr = MAMComponents.Get <IMAMEnrollmentManager>();
                mgr.RegisterAccountForMAM(_cachedUPN, _cachedAADID, result.TenantId);
            }

            return(result);
        }
        public override bool GetCacheLoadPolicy(IPlatformParameters parameters)
        {
            PlatformParameters authorizationParameters = (parameters as PlatformParameters);

            if (authorizationParameters == null)
            {
                throw new ArgumentException("parameters should be of type PlatformParameters", "parameters");
            }

            PromptBehavior promptBehavior = authorizationParameters.PromptBehavior;

            return(promptBehavior != PromptBehavior.Always && promptBehavior != PromptBehavior.RefreshSession);
        }
示例#28
0
 // Interactive Modern Authentication Sign-In
 internal void SignIn(string resourceUrl, PromptBehavior behavior, string clientId = DEFAULT_CLIENT_ID, string redirectUri = DEFAULT_REDIRECT_URI)
 {
     AuthResult       = null;
     this.resourceUrl = null;
     try
     {
         AuthResult = AuthContext.AcquireToken(resourceUrl, clientId,
                                               new Uri(redirectUri), behavior);
         this.resourceUrl = resourceUrl;
     }
     catch (AdalException)
     {
         throw new AuthenticationException("OAuth couldn't sign: " + resourceUrl);
     }
 }
 internal static IWebUI CreateAuthenticationDialog(PromptBehavior promptBehavior)
 {
     switch (promptBehavior)
     {
         case PromptBehavior.Auto:
             return new InteractiveWebUI();
         case PromptBehavior.Always:
         case PromptBehavior.RefreshSession:
             return new InteractiveWebUI();
         case PromptBehavior.Never:
             return new SilentWebUI();
         default:
             throw new InvalidOperationException();
     }
 }
示例#30
0
        private string GetToken(string tenantId, PromptBehavior promptBehavior, bool updateUI = false, string AuthType = "AzureAuth")
        {
            lblStatus.Text = "BUSY: Authenticating...";
            //"d94647e7-c4ff-4a93-bbe0-d993badcc5b8"
            AuthenticationContext context = new AuthenticationContext(ServiceUrls.GetLoginUrl(app.Default.AzureAuth) + tenantId);

            AuthenticationResult result = null;
            string AuthUri = null;

            if (AuthType == "AzureAuth")
            {
                AuthUri = ServiceUrls.GetServiceManagementUrl(app.Default.AzureAuth);
            }
            else
            {
                AuthUri = ServiceUrls.GetServiceManagementUrl(app.Default.GraphAuth);
            }

            try
            {
                if (_userId == null)
                {
                    result  = context.AcquireToken(AuthUri, app.Default.ClientId, new Uri(app.Default.ReturnURL), promptBehavior);
                    _userId = new UserIdentifier(result.UserInfo.DisplayableId, UserIdentifierType.RequiredDisplayableId);
                }
                else
                {
                    result = context.AcquireToken(AuthUri, app.Default.ClientId, new Uri(app.Default.ReturnURL), PromptBehavior.Never, _userId);
                    // result = context.AcquireTokenSilent(ServiceUrls.GetServiceManagementUrl(app.Default.GraphAuth), app.Default.ClientId, _userId)
                }

                if (result == null)
                {
                    throw new InvalidOperationException("Failed to obtain the token");
                }
                if (updateUI)
                {
                    lblSignInText.Text = $"Signed in as {result.UserInfo.DisplayableId}";
                }

                return(result.AccessToken);
            }
            catch (Exception exception)
            {
                DialogResult dialogresult = MessageBox.Show(exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
示例#31
0
        public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, bool callSync)
            : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException("redirectUri");
            }

            if (!string.IsNullOrWhiteSpace(redirectUri.Fragment))
            {
                var ex = new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri");
                Logger.LogException(this.CallState, ex);
                throw ex;
            }

            this.redirectUri = redirectUri;

            this.SetRedirectUriRequestParameter();

            if (userId == null)
            {
                var ex = new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
                Logger.LogException(this.CallState, ex);
                throw ex;
            }

            this.userId = userId;

            this.promptBehavior = promptBehavior;

            if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&')
            {
                extraQueryParameters = extraQueryParameters.Substring(1);
            }

            this.extraQueryParameters = extraQueryParameters;

            this.webUi = webUI;

            this.UniqueId           = userId.UniqueId;
            this.DisplayableId      = userId.DisplayableId;
            this.UserIdentifierType = userId.Type;

            this.LoadFromCache = (tokenCache != null && this.promptBehavior != PromptBehavior.Always && this.promptBehavior != PromptBehavior.RefreshSession);

            this.SupportADFS = true;
        }
示例#32
0
        /// <summary>
        /// Authenticates the user.
        /// </summary>
        /// <param name="activity">The calling activity.</param>
        /// <param name="behavior">The ADAL prompt behavior.</param>
        /// <returns>The authentication result.</returns>
        public async Task <AuthenticationResult> Authenticate(Activity activity, PromptBehavior behavior)
        {
            // Check initial authentication values.
            if (_clientID.Equals(_placeholderClientID) || _redirectURI.Equals(_placeholderRedirectURI))
            {
                Toast.MakeText(Application.Context, "Please update the authentication values for your application.", ToastLength.Long).Show();
                Log.Info(_logTagAuth, "Authentication cancelled. Authentication values need to be updated with user provided values." +
                         " Client ID = " + _clientID + " Redirect URI = " + _redirectURI);
                return(null);
            }

            if (!Uri.IsWellFormedUriString(_redirectURI, UriKind.RelativeOrAbsolute))
            {
                Toast.MakeText(Application.Context, "Please correct the redirect URI for your application.", ToastLength.Long).Show();
                Log.Info(_logTagAuth, "Authentication cancelled. Redirect URI needs to be corrected with a well-formed value." +
                         " Redirect URI = " + _redirectURI);
                return(null);
            }

            AuthenticationResult result = null;

            // Register the callback to capture ADAL logs.
            LoggerCallbackHandler.LogCallback       = ADALLog;
            LoggerCallbackHandler.PiiLoggingEnabled = true;

            // Attempt to sign the user in silently.
            result = await SignInSilent(_resourceID, null);

            // If the user cannot be signed in silently, prompt the user to manually sign in.
            if (result == null)
            {
                result = await SignInWithPrompt(new PlatformParameters(activity, false, behavior));
            }

            // If auth was successful, cache the values and log the success.
            if (result != null && result.AccessToken != null)
            {
                _cachedUPN   = result.UserInfo.DisplayableId;
                _cachedAADID = result.UserInfo.UniqueId;

                Log.Info(_logTagAuth, "Authentication succeeded. UPN = " + _cachedUPN);
            }

            return(result);
        }
示例#33
0
        public async Task<AuthenticationResult> Login(string resourceUrl, PromptBehavior promptBehavior = PromptBehavior.Always)
        {
            _LogProvider.WriteLog("LoginAzureProvider", "Start token request");
            _LogProvider.WriteLog("GetToken", " - Resource Url: " + resourceUrl);
            _LogProvider.WriteLog("GetToken", " - Prompt Behavior: " + promptBehavior.ToString());

            PlatformParameters platformParams = new PlatformParameters(promptBehavior, null);
            AuthenticationResult authenticationResult = await _AuthenticationContext.AcquireTokenAsync(resourceUrl, strClientId, new Uri(strReturnUrl), platformParams);

            if (authenticationResult == null)
                _LastUserInfo = null;
            else
                _LastUserInfo = authenticationResult.UserInfo;

            _LogProvider.WriteLog("LoginAzureProvider", "End token request");

            return authenticationResult;
        }
        internal static IWebUI CreateAuthenticationDialog(PromptBehavior promptBehavior)
        {
            switch (promptBehavior)
            {
            case PromptBehavior.Auto:
                return(new InteractiveWebUI());

            case PromptBehavior.Always:
            case PromptBehavior.RefreshSession:
                return(new InteractiveWebUI());

            case PromptBehavior.Never:
                return(new SilentWebUI());

            default:
                throw new InvalidOperationException();
            }
        }
示例#35
0
        public AsAzureProfile Login(AsAzureContext asAzureContext, SecureString password)
        {
            PromptBehavior promptBehavior = password == null ? PromptBehavior.Always : PromptBehavior.Auto;

            var resourceUri = new UriBuilder(Uri.UriSchemeHttps, GetResourceUriSuffix(asAzureContext.Environment.Name)).ToString();

            resourceUri = resourceUri.TrimEnd('/');
            _asAzureAuthenticationProvider.GetAadAuthenticatedToken(asAzureContext, password, promptBehavior, AsAzureClientId, resourceUri, RedirectUri);

            _profile.Context.TokenCache = AsAzureClientSession.TokenCache.Serialize();

            if (!_profile.Environments.ContainsKey(asAzureContext.Environment.Name))
            {
                _profile.Environments.Add(asAzureContext.Environment.Name, asAzureContext.Environment);
            }

            return(_profile);
        }
        public AcquireTokenInteractiveHandler(Authenticator authenticator, TokenCache tokenCache, string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters, IWebUI webUI, bool callSync)
            : base(authenticator, tokenCache, resource, new ClientKey(clientId), TokenSubjectType.User, callSync)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException("redirectUri");
            }

            if (!string.IsNullOrWhiteSpace(redirectUri.Fragment))
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriContainsFragment, "redirectUri");
            }

            this.redirectUri = redirectUri;

            this.SetRedirectUriRequestParameter();

            if (userId == null)
            {
                throw new ArgumentNullException("userId", AdalErrorMessage.SpecifyAnyUser);
            }

            this.userId = userId;

            this.promptBehavior = promptBehavior;

            if (!string.IsNullOrEmpty(extraQueryParameters) && extraQueryParameters[0] == '&')
            {
                extraQueryParameters = extraQueryParameters.Substring(1);
            }

            this.extraQueryParameters = extraQueryParameters;

            this.webUi = webUI;

            this.UniqueId = userId.UniqueId;
            this.DisplayableId = userId.DisplayableId;
            this.UserIdentifierType = userId.Type;

            this.LoadFromCache = (tokenCache != null && this.promptBehavior != PromptBehavior.Always && this.promptBehavior != PromptBehavior.RefreshSession);

            this.SupportADFS = true;
        }
 public PlatformParameters(PromptBehavior promptBehavior, bool useCorporateNetwork)
 {
     this.PromptBehavior = promptBehavior;
     this.UseCorporateNetwork = useCorporateNetwork;
 }
        private AuthenticationResult DoAcquireToken(AdalConfiguration config, PromptBehavior promptBehavior, string userId, 
            SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            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.OptionalDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return result;
        }
 public IWebUI Create(PromptBehavior promptBehavior, bool useCorporateNetwork)
 {
     return new WebUI(promptBehavior, useCorporateNetwork);
 }
示例#40
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 ReplayerWebUI(PromptBehavior promptBehavior, bool useCorporateNetwork)
 {
 }
        /// <summary>
        /// Authenticates the user silently using <see cref="AuthenticationContext.AcquireToken(string, string, Uri, PromptBehavior)"/>.
        /// </summary>
        /// <param name="resource">The resource to authenticate against.</param>
        /// <param name="clientId">The client ID of the application.</param>
        /// <param name="redirectUri">The redirect URI of the application.</param>
        /// <param name="promptBehavior">The <see cref="PromptBehavior"/> for authentication.</param>
        /// <returns>The <see cref="IAuthenticationResult"/>.</returns>
        public IAuthenticationResult AcquireToken(string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior)
        {
            var result = this.authenticationContext.AcquireToken(resource, clientId, redirectUri, promptBehavior);

            return result == null ? null : new AuthenticationResultWrapper(result);
        }
 private async Task<AuthenticationResult> AcquireTokenCommonAsync(string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters = null, bool callSync = false)
 {
     var handler = new AcquireTokenInteractiveHandler(this.Authenticator, this.TokenCache, resource, clientId, redirectUri, promptBehavior, userId, extraQueryParameters, this.CreateWebAuthenticationDialog(promptBehavior), callSync);
     return await handler.RunAsync();
 }
 /// <summary>
 /// Acquires security token from the authority.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientId">Identifier of the client requesting the token.</param>
 /// <param name="promptBehavior">If <see cref="PromptBehavior.Always"/>, asks service to show user the authentication page which gives them chance to authenticate as a different user.</param>
 /// <param name="userId">Identifier of the user token is requested for. If created from DisplayableId, this parameter will be used to pre-populate the username field in the authentication form. Please note that the end user can still edit the username field and authenticate as a different user. 
 /// If you want to be notified of such change with an exception, create UserIdentifier with type RequiredDisplayableId. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <param name="extraQueryParameters">This parameter will be appended as is to the query string in the HTTP authentication request to the authority. The parameter can be null.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns>
 public IAsyncOperation<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters)
 {
     return RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), promptBehavior, userId, extraQueryParameters));
 }
 private IWebUI CreateWebAuthenticationDialog(PromptBehavior promptBehavior)
 {
     return NetworkPlugin.WebUIFactory.Create(promptBehavior, this.UseCorporateNetwork);
 }
 public IAsyncOperation<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior)
 {
     return RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, GetRedirectUri(redirectUri), promptBehavior, UserIdentifier.AnyUser));
 }
 public IWebUI Create(PromptBehavior promptBehavior, object ownerWindow)
 {
     return new RecorderWebUI(promptBehavior, ownerWindow);
 }
 public RecorderWebUI(PromptBehavior promptBehavior, object ownerWindow)
 {
     this.internalWebUI = (new WebUIFactory()).Create(promptBehavior, ownerWindow);
 }
 /// <summary>
 /// Acquires security token from the authority.
 /// </summary>
 /// <param name="resource">Identifier of the target resource that is the recipient of the requested token.</param>
 /// <param name="clientId">Identifier of the client requesting the token.</param>
 /// <param name="redirectUri">Address to return to upon receiving a response from the authority.</param>
 /// <param name="promptBehavior">If <see cref="PromptBehavior.Always"/>, asks service to show user the authentication page which gives them chance to authenticate as a different user.</param>
 /// <param name="userId">Identifier of the user token is requested for. If created from DisplayableId, this parameter will be used to pre-populate the username field in the authentication form. Please note that the end user can still edit the username field and authenticate as a different user. 
 /// If you want to be notified of such change with an exception, create UserIdentifier with type RequiredDisplayableId. This parameter can be <see cref="UserIdentifier"/>.Any.</param>
 /// <param name="extraQueryParameters">This parameter will be appended as is to the query string in the HTTP authentication request to the authority. The parameter can be null.</param>
 /// <returns>It contains Access Token, Refresh Token and the Access Token's expiration time.</returns>
 public IAsyncOperation<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId, string extraQueryParameters)
 {
     return RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, redirectUri, promptBehavior, userId, extraQueryParameters));
 }
 public IAsyncOperation<AuthenticationResult> AcquireTokenAsync(string resource, string clientId, Uri redirectUri, PromptBehavior promptBehavior, UserIdentifier userId)
 {
     return RunTaskAsAsyncOperation(this.AcquireTokenCommonAsync(resource, clientId, redirectUri ?? Constant.SsoPlaceHolderUri, promptBehavior, userId));
 }
 public WebUI(PromptBehavior promptBehavior, bool useCorporateNetwork)
 {
     this.promptBehavior = promptBehavior;
     this.useCorporateNetwork = useCorporateNetwork;
 }