예제 #1
0
        /// <summary>
        /// Intializes OneDrive service.
        /// </summary>
        /// <param name="appClientId">Client Id.</param>
        /// <param name="scopes">Permission scopes.</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <returns>True or false.</returns>
        public virtual bool Initialize(string appClientId, string[] scopes, UIParent uiParent = null, string redirectUri = null)
        {
#if WINRT
            if (ServicePlatformInitializer == null)
            {
                ServicePlatformInitializer = new Uwp.OneDriveServicePlatformInitializer();
            }

            Provider.AuthenticationModel = MicrosoftGraphEnums.AuthenticationModel.V2;
#endif
            ServicePlatformService = ServicePlatformInitializer.CreateOneDriveServicePlatformInstance(this);

            AppClientId   = appClientId;
            Scopes        = scopes;
            IsInitialized = true;

            Provider.Initialize(appClientId, MicrosoftGraphEnums.ServicesToInitialize.OneDrive, scopes, uiParent, redirectUri);

            if (Provider.Authentication == null)
            {
                Provider.Authentication = new MicrosoftGraphAuthenticationHelper(Scopes);
            }

            return(true);
        }
예제 #2
0
 public IWebUI CreateAuthenticationDialog(UIParent parent, RequestContext requestContext)
 {
     return(new WebUI(parent)
     {
         RequestContext = requestContext
     });
 }
        /// <summary>
        /// Authenticates the microsoft user.
        /// see the following article ->
        ///     https://blog.xamarin.com/enterprise-apps-made-easy-updated-libraries-apis/
        ///     https://github.com/AzureAD/microsoft-authentication-library-for-dotnet
        /// </summary>
        public async Task AuthenticateMicrosoftUser(Action <string> tokenCallBack)
        {
            var identityClientApp = new PublicClientApplication(CoreSettings.Config.SocialMedia.MicrosoftAppId);

            identityClientApp.RedirectUri = $"msal{CoreSettings.Config.SocialMedia.MicrosoftAppId}://auth";
            string[] scopes   = { "User.Read", "User.ReadBasic.All ", "Mail.Send" };
            UIParent uiParent = null;

#if __ANDROID__
            if (Xamarin.Forms.Device.RuntimePlatform == "Android")
            {
                uiParent = new UIParent(CrossCurrentActivity.Current.Activity as Android.App.Activity);
            }
#endif
            try
            {
                var Client = new GraphServiceClient("https://graph.microsoft.com/v1.0",
                                                    new DelegateAuthenticationProvider(async(requestMessage) =>
                {
                    var tokenRequest = await identityClientApp.AcquireTokenAsync(scopes, uiParent).ConfigureAwait(false);
                    tokenCallBack?.Invoke(tokenRequest.AccessToken);
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
                }));

                var userInfo = await Client.Me.Request().GetAsync();
            }
            catch (MsalException ex)
            {
                Log.LogException(ex);
                tokenCallBack?.Invoke(ex.Message);
            }
        }
        /// <summary>
        /// Get a Microsoft Graph access token using the v2.0 Endpoint.
        /// </summary>
        /// <param name="appClientId">Application client ID</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <param name="loginHint">UPN</param>
        /// <returns>An oauth2 access token.</returns>
        internal async Task <string> GetUserTokenV2Async(string appClientId, UIParent uiParent = null, string redirectUri = null, string loginHint = null)
        {
            if (_identityClient == null)
            {
                _identityClient = new MSAL.PublicClientApplication(appClientId);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                _identityClient.RedirectUri = redirectUri;
            }

            var upnLoginHint = string.Empty;

            if (!string.IsNullOrEmpty(loginHint))
            {
                upnLoginHint = loginHint;
            }

            MSAL.AuthenticationResult authenticationResult = null;

            var user = _identityClient.Users.FirstOrDefault();

            authenticationResult = user != null ? await _identityClient.AcquireTokenSilentAsync(DelegatedPermissionScopes, user) : await _identityClient.AcquireTokenAsync(DelegatedPermissionScopes, upnLoginHint, uiParent);

            return(authenticationResult?.AccessToken);
        }
예제 #5
0
        public async Task <AuthenticationResult> AcquireTokenAsync()
        {
            if (UiParent == null)
            {
                Activity currentActivity = null;

                try
                {
                    currentActivity = CurrentActivityHelper.GetCurrentActivity();
                    UiParent        = new UIParent(currentActivity);
                }
                catch (Exception ex)
                {
                    logger.Log(ex, "Error getting current activity");
                }
            }
            AuthenticationResult res = null;

            try
            {
                res = await publicClientApplication.AcquireTokenAsync(AuthConfig.Scopes, UiParent);
            }
            catch (Exception ex1)
            {
                logger.Log(ex1, "Error aquiring token");
            }
            return(res);
        }
예제 #6
0
        public async Task <AuthenticationResult> AcquireTokenInteractiveAsync(
            IEnumerable <string> scopes,
            UIBehavior uiBehavior,
            string extraQueryParams,
            UIParent uiParent)
        {
            CreateOrUpdatePublicClientApp(InteractiveAuthority, ApplicationId);

            AuthenticationResult result;

            if (CurrentUser != null)
            {
                result = await PublicClientApplication.AcquireTokenAsync(
                    scopes,
                    CurrentUser,
                    uiBehavior,
                    extraQueryParams,
                    uiParent).ConfigureAwait(false);
            }
            else
            {
                result = await PublicClientApplication.AcquireTokenAsync(
                    scopes,
                    LoginHint,
                    uiBehavior,
                    extraQueryParams,
                    uiParent).ConfigureAwait(false);
            }

            CurrentUser = result.Account;
            return(result);
        }
예제 #7
0
        public async Task <bool> LoginInteractiveAsync(Func <StoryNode> lazynode)
        {
            var node = lazynode();

            Initialize();
            var ret = false;

            try
            {
                authResult = await clientApp
                             .AcquireTokenInteractive(scopes)
                             .WithPrompt(Prompt.SelectAccount)
                             .WithParentActivityOrWindow(UIParent?.Invoke())
                             .ExecuteAsync();

                IsAuthenticated = true;
                ret             = true;
            }
            catch (MsalException msalex)
            {
                authResult = null;
                node.MessageBuffer?.WriteLine($"Acquiring Token Interactive");
                node.MessageBuffer?.WriteLine(msalex.Message);
                node.MessageBuffer?.WriteLine("(E102)");
            }
            catch (Exception ex)
            {
                authResult = null;
                node.MessageBuffer?.WriteLine($"Acquiring Token Interactive");
                node.MessageBuffer?.WriteLine(ex.Message);
                node.MessageBuffer?.WriteLine("(E101)");
            }
            return(ret);
        }
예제 #8
0
 private void Awake()
 {
     if (instance != null && instance != this)
     {
         Destroy(gameObject);
     }
     instance = this;
 }
예제 #9
0
 public IWebUI CreateAuthenticationDialog(UIParent parent, RequestContext requestContext)
 {
     //there is no need to pass UIParent.
     return(new WebUI()
     {
         RequestContext = requestContext
     });
 }
        public void UIParent_EmptyCtor()
        {
            UIParent uiParent = new UIParent();

            Assert.IsFalse(uiParent.UseHiddenBrowser);
            Assert.IsNotNull(uiParent.CoreUIParent);
            Assert.IsNull(uiParent.CoreUIParent.OwnerWindow);
            Assert.IsFalse(uiParent.CoreUIParent.UseHiddenBrowser);
        }
    // On click select the correct tab, and setup the category picker
    private void OnNavigateButtonClicked()
    {
        clicksWhileSelected++;

        // If this is the second click while selected then navigate to the bookmark
        if (clicksWhileSelected >= 2)
        {
            UIParent.NavigateToBookmark(bookmark);
        }
    }
예제 #12
0
 private void Awake()
 {
     if (Main == null)
     {
         Main = this;
     }
     else
     {
         Destroy(this);
     }
 }
예제 #13
0
        public IWebUI CreateAuthenticationDialog(UIParent parent, RequestContext requestContext)
        {
            if (parent.UseHiddenBrowser)
            {
                return(new SilentWebUI {
                    OwnerWindow = parent?.OwnerWindow, RequestContext = requestContext
                });
            }

            return(new InteractiveWebUI {
                OwnerWindow = parent?.OwnerWindow, RequestContext = requestContext
            });
        }
        public void UIParent_NetstndardCtor()
        {
            object   parent   = "parent";
            UIParent uiParent = new UIParent(parent, true);

            Assert.IsFalse(uiParent.UseHiddenBrowser);
            Assert.IsFalse(uiParent.CoreUIParent.UseHiddenBrowser);

            uiParent.UseHiddenBrowser = true;

            Assert.IsTrue(uiParent.UseHiddenBrowser);
            Assert.IsTrue(uiParent.CoreUIParent.UseHiddenBrowser);
            Assert.AreSame(parent, uiParent.CoreUIParent.OwnerWindow);
        }
예제 #15
0
 public AuthorizationService(string appId, string authorityUrl, string editUrl,
                             string resetUrl, string redirectUrl, string[] scopes, UIParent uiParent)
 {
     ApplicationId            = appId;
     AuthorityUrl             = authorityUrl;
     EditUrl                  = editUrl;
     ResetUrl                 = resetUrl;
     RedirectUrl              = redirectUrl;
     Scopes                   = scopes;
     UiParent                 = uiParent;
     _publicClientApplication = new PublicClientApplication(ApplicationId, AuthorityUrl)
     {
         RedirectUri = RedirectUrl
     };
 }
예제 #16
0
        /// <summary>
        /// Initialize Microsoft Graph.
        /// </summary>
        /// <param name='appClientId'>Azure AD's App client id</param>
        /// <param name="servicesToInitialize">A combination of value to instanciate different services</param>
        /// <param name="delegatedPermissionScopes">Permission scopes for MSAL v2 endpoints</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <returns>Success or failure.</returns>
        public bool Initialize(string appClientId, ServicesToInitialize servicesToInitialize = ServicesToInitialize.Message | ServicesToInitialize.UserProfile | ServicesToInitialize.Event, string[] delegatedPermissionScopes = null, UIParent uiParent = null, string redirectUri = null)
        {
            if (string.IsNullOrEmpty(appClientId))
            {
                throw new ArgumentNullException(nameof(appClientId));
            }

            _redirectUri              = redirectUri;
            _uiParent                 = uiParent;
            AppClientId               = appClientId;
            GraphProvider             = CreateGraphClientProvider(appClientId);
            ServicesToInitialize      = servicesToInitialize;
            IsInitialized             = true;
            DelegatedPermissionScopes = delegatedPermissionScopes;
            return(true);
        }
예제 #17
0
        public AzureB2CJwtTokenManager()
        {
            //TODO _uiParent is required for Android
            _uiParent = null;
            var authorityBase = $"{B2CAuthorityBase}{B2CTenant}/";

            _policySignUpSignIn     = B2CSignUpSignInPolicy;
            _authority              = $"{authorityBase}{_policySignUpSignIn}";
            _authorityPasswordReset = $"{authorityBase}{B2CResetPasswordPolicy}";

            //TODO new here?
            _pca = new PublicClientApplication(B2ClientId, _authority)
            {
                RedirectUri = $"{B2CRedirectPrefix}{B2ClientId}{B2CRedirectSuffix}"
            };
        }
예제 #18
0
 /// <summary>
 /// Constructs a new <see cref="InteractiveAuthenticationProvider"/>
 /// </summary>
 /// <param name="publicClientApplication">A <see cref="IPublicClientApplication"/> to pass to <see cref="DeviceCodeProvider"/> for authentication.</param>
 /// <param name="scopes">Scopes required to access a protected API.</param>
 /// <param name="uiBehavior">Designed interactive experience for the user. Defaults to <see cref="UIBehavior.SelectAccount"/>.</param>
 /// <param name="uiParent">Object containing a reference to the parent window/activity. REQUIRED for Xamarin.Android only.</param>
 public InteractiveAuthenticationProvider(
     IPublicClientApplication publicClientApplication,
     string[] scopes,
     UIBehavior?uiBehavior = null,
     UIParent uiParent     = null)
     : base(scopes)
 {
     ClientApplication = publicClientApplication ?? throw new AuthenticationException(
                                   new Error
     {
         Code    = ErrorConstants.Codes.InvalidRequest,
         Message = string.Format(ErrorConstants.Message.NullValue, "publicClientApplication")
     });
     UIBehavior = uiBehavior ?? UIBehavior.SelectAccount;
     UIParent   = uiParent;
 }
예제 #19
0
        public App(UIParent uiParent)
        {
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(Constants.SyncFusionLicenseKey);

            AppCenter.Start(Constants.AppCenterLicenseKey, typeof(Analytics), typeof(Crashes));

            InitializeComponent();

            AuthorizationService = new AuthorizationService(Constants.B2C.ApplicationId, Constants.B2C.Authority,
                                                            Constants.B2C.Edit, Constants.B2C.Reset, Constants.B2C.RedirectUrl, Constants.B2C.Scopes, uiParent);

            var task = Task.Run(LoginUser);

            task.Wait();

            InitializeNewsPages();

            MainPage = new NavigationPage(new MainPage(task.Result));
        }
예제 #20
0
        /// <summary>
        /// Intializes OneDrive service.
        /// </summary>
        /// <typeparam name="T">Concrete instance of type IOneDriveServicePlatformInitializer</typeparam>
        /// <typeparam name="U">Concrete instance of type IMicrosoftGraphUserServicePhotos</typeparam>
        /// <param name="appClientId">Client Id.</param>
        /// <param name="scopes">Permission scopes.</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <returns>True or false.</returns>
        public virtual bool Initialize <T, U>(string appClientId, string[] scopes, UIParent uiParent = null, string redirectUri = null)
            where T : IOneDriveServicePlatformInitializer, new()
            where U : IMicrosoftGraphUserServicePhotos, new()
        {
            ServicePlatformInitializer = new T();
            ServicePlatformService     = ServicePlatformInitializer.CreateOneDriveServicePlatformInstance(this);

            AppClientId   = appClientId;
            Scopes        = scopes;
            IsInitialized = true;

            Provider.Initialize <U>(appClientId, MicrosoftGraphEnums.ServicesToInitialize.OneDrive, scopes, uiParent, redirectUri);

            if (Provider.Authentication == null)
            {
                Provider.Authentication = new MicrosoftGraphAuthenticationHelper(Scopes);
            }

            return(true);
        }
예제 #21
0
    public void SetupSoundEvents()
    {
        // Make all general dropdowns play the dropdown sound
        GeneralDropdown[] dropdowns = UIParent.GetComponentsInChildren <GeneralDropdown>(true);
        foreach (GeneralDropdown dropdown in dropdowns)
        {
            dropdown.OnDropdownEnabled.AddListener(PlayDropdownSound);
        }

        // Add the expanded states of all tmp dropdowns to the list
        TMP_Dropdown[] tmpDropdowns = UIParent.GetComponentsInChildren <TMP_Dropdown>(true);
        foreach (TMP_Dropdown tmpDropdown in tmpDropdowns)
        {
            expandedStates.Add(new PreviousExpandedState()
            {
                dropdown = tmpDropdown,
                previousExpandedState = tmpDropdown.IsExpanded
            });
        }
    }
예제 #22
0
        /// <summary>
        /// Get a Microsoft Graph access token using the v2.0 Endpoint.
        /// </summary>
        /// <param name="appClientId">Application client ID</param>
        /// <param name="uiParent">UiParent instance - required for Android</param>
        /// <param name="redirectUri">Redirect Uri - required for Android</param>
        /// <param name="loginHint">UPN</param>
        /// <returns>An oauth2 access token.</returns>
        public async Task <string> GetUserTokenV2Async(string appClientId, UIParent uiParent = null, string redirectUri = null, string loginHint = null)
        {
            if (_identityClient == null)
            {
                _identityClient = new MSAL.PublicClientApplication(appClientId);
            }

            if (!string.IsNullOrEmpty(redirectUri))
            {
                _identityClient.RedirectUri = redirectUri;
            }

            var upnLoginHint = string.Empty;

            if (!string.IsNullOrEmpty(loginHint))
            {
                upnLoginHint = loginHint;
            }

            MSAL.AuthenticationResult authenticationResult = null;

            try
            {
                IAccount account = (await _identityClient.GetAccountsAsync()).FirstOrDefault();
                authenticationResult = await _identityClient.AcquireTokenSilentAsync(DelegatedPermissionScopes, account);
            }
            catch (MsalUiRequiredException)
            {
                try
                {
                    authenticationResult = await _identityClient.AcquireTokenAsync(DelegatedPermissionScopes, upnLoginHint, uiParent);
                }
                catch (MsalException)
                {
                    throw;
                }
            }

            return(authenticationResult?.AccessToken);
        }
 public async Task <AuthenticationResult> AuthenticateAsync(string authority, string policy, List <string> scopes, bool forceRefresh, UIParent uiParent)
 {
     return(await AuthenticateAsync(authority, GetUserByPolicy(PublicClientApplication.Users, policy), scopes, forceRefresh, uiParent));
 }
예제 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MicrosoftGraphService"/> class.
 /// </summary>
 /// <param name='appClientId'>Azure AD's App client id</param>
 /// <param name="servicesToInitialize">A combination of value to instanciate different services</param>
 /// <param name="delegatedPermissionScopes">Permission scopes for MSAL v2 endpoints</param>
 /// <param name="uiParent">UiParent instance - required for Android</param>
 /// <param name="redirectUri">Redirect Uri - required for Android</param>
 /// <returns>Success or failure.</returns>
 public MicrosoftGraphService(string appClientId, ServicesToInitialize servicesToInitialize = ServicesToInitialize.Message | ServicesToInitialize.UserProfile | ServicesToInitialize.Event, string[] delegatedPermissionScopes = null, UIParent uiParent = null, string redirectUri = null)
 {
     Initialize(appClientId, servicesToInitialize, delegatedPermissionScopes, uiParent, redirectUri);
 }
 public async Task <AuthenticationResult> AuthenticateAsync(List <string> scopes, bool forceRefresh, UIParent uiParent)
 {
     return(await AuthenticateAsync(Authority, AuthenticatePolicy, scopes, forceRefresh, uiParent));
 }
 public async Task <AuthenticationResult> AuthenticateAsync(string policy, List <string> scopes, UIParent uiParent)
 {
     return(await AuthenticateAsync(Authority, GetUserByPolicy(PublicClientApplication.Users, policy), scopes, false, uiParent));
 }
예제 #27
0
 public WebUI(UIParent parent, RequestContext requestContext)
 {
     useCorporateNetwork = parent.UseCorporateNetwork;
     silentMode          = parent.UseHiddenBrowser;
 }
 public async Task <AuthenticationResult> AuthenticateAsync(string authority, IUser user, List <string> scopes, bool forceRefresh, UIParent uiParent)
 {
     try
     {
         return(await AuthenticateSilentlyAsync(authority, user, scopes, forceRefresh));
     }
     catch (Exception ex)
     {
         try
         {
             return(await AuthenticateWithCredentialsAsync(user, scopes, uiParent));
         }
         catch (Exception ex1)
         {
             throw ex1;
         }
     }
 }
 /// <summary>
 /// Creates an instance of the <see cref="AADLoginProvider"/>
 /// </summary>
 /// <param name="client">The <see cref="IPublicClientApplication"/></param>
 /// <param name="parent">The <see cref="UIParent"/>. Only used on Android</param>
 /// <param name="options">The <see cref="IAADOptions"/></param>
 public AADLoginProvider(IPublicClientApplication client, UIParent parent, IAADOptions options)
     : base(client, parent, options)
 {
 }
 public async Task <AuthenticationResult> AuthenticateAsync(string authority, IUser user, List <string> scopes, UIParent uiParent)
 {
     return(await AuthenticateAsync(authority, user, scopes, false, UiParent));
 }