/// <summary>
        /// Initializes an new instance of the LiveAuthClientCore class.
        /// </summary>
        public LiveAuthClientCore(
            string clientId,
            IDictionary<int, string> clientSecretMap, 
            IRefreshTokenHandler refreshTokenHandler,
            LiveAuthClient authClient)
        {
            Debug.Assert(!string.IsNullOrEmpty(clientId));
            Debug.Assert(clientSecretMap != null && clientSecretMap.Count > 0);
            Debug.Assert(authClient != null);

            this.clientId = clientId;
            this.clientSecrets = clientSecretMap;
            this.refreshTokenHandler = refreshTokenHandler;
            this.publicAuthClient = authClient;

            // Get latest version
            int largestIndex = clientSecretMap.Keys.First();
            if (clientSecretMap.Count > 1)
            {
                foreach (int index in clientSecretMap.Keys)
                {
                    if (index > largestIndex)
                    {
                        largestIndex = index;
                    }
                }
            }

            this.clientSecret = clientSecretMap[largestIndex];
        }
예제 #2
0
        private  async void loginButton_Click(object sender, RoutedEventArgs e)//登录
        {
            try
            {
                msgText.Text = "亲:正在登录";
                var authClient = new LiveAuthClient();

                LiveLoginResult result = await authClient.LoginAsync(new string[] { "wl.signin", "wl.skydrive" });

                if (result.Status == LiveConnectSessionStatus.Connected)
                {

                    var connectClient = new LiveConnectClient(result.Session);
                    var meResult = await connectClient.GetAsync("me");
                    msgText.Text = "亲爱的:" + meResult.Result["name"].ToString() + "  您已成功登录OneDrive!";
                }
                updateButton.Visibility = Visibility.Visible;
                uploadButton.Visibility = Visibility.Visible;
                downButton.Visibility = Visibility.Visible;


            }
            catch (LiveAuthException ex)
            {
                msgText.Text = ex.Message;
            }
            catch (LiveConnectException ex)
            {
                msgText.Text = ex.Message;
            }
        }
		private async Task SetNameField(Boolean login)
		{
			// If login == false, just update the name field. 
			await App.updateUserName(this.UserNameTextBlock, login);

			// Test to see if the user can sign out.
			Boolean userCanSignOut = true;

			var LCAuth = new LiveAuthClient();
			LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();

			if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)
			{
				userCanSignOut = LCAuth.CanLogout;
			}

			var loader = new Windows.ApplicationModel.Resources.ResourceLoader();

			if (String.IsNullOrEmpty(UserNameTextBlock.Text) 
				|| UserNameTextBlock.Text.Equals(loader.GetString("MicrosoftAccount/Text")))
			{
				// Show sign-in button.
				SignInButton.Visibility = Visibility.Visible;
				SignOutButton.Visibility = Visibility.Collapsed;
			}
			else
			{
				// Show sign-out button if they can sign out.
				SignOutButton.Visibility = userCanSignOut ? Visibility.Visible : Visibility.Collapsed;
				SignInButton.Visibility = Visibility.Collapsed;
			}
		}
		private async void SignOutButton_OnClick(object sender, RoutedEventArgs e)
		{
			try
			{
				// Initialize access to the Live Connect SDK.
				LiveAuthClient LCAuth = new LiveAuthClient();
				LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
				// Sign the user out, if he or she is connected;
				//  if not connected, skip this and just update the UI
				if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)
				{
					LCAuth.Logout();
				}

				// At this point, the user should be disconnected and signed out, so
				//  update the UI.
				var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
				this.UserNameTextBlock.Text = loader.GetString("MicrosoftAccount/Text");

				// Show sign-in button.
				SignInButton.Visibility = Visibility.Visible;
				SignOutButton.Visibility = Visibility.Collapsed;
			}
			catch (LiveConnectException x)
			{
				// Handle exception.
			}
		}
예제 #5
0
파일: Auth.cs 프로젝트: NickHeiner/chivalry
 private async Task<LiveConnectClient> ensureConnection()
 {
     if (connection != null)
     {
         return connection;
     }
     // Initialize access to the Live Connect SDK.
     LiveAuthClient LCAuth = new LiveAuthClient("https://chivalry.azure-mobile.net/");
     LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
     // Sign in to the user's Microsoft account with the required scope.
     //    
     //  This call will display the Microsoft account sign-in screen if the user 
     //  is not already signed in to their Microsoft account through Windows 8.
     // 
     //  This call will also display the consent dialog, if the user has 
     //  has not already given consent to this app to access the data described 
     //  by the scope.
     // 
     LiveLoginResult loginResult = await LCAuth.LoginAsync(new string[] { "wl.basic", "wl.emails" });
     if (loginResult.Status == LiveConnectSessionStatus.Connected)
     {
         // Create a client session to get the profile data.
         connection = new LiveConnectClient(LCAuth.Session);
         mobileServiceUser = await App.MobileService.LoginAsync(loginResult.Session.AuthenticationToken);
         return connection;
     }
     if (LoginFailed != null)
     {
         LoginFailed(this, null);
     }
     return null;
 }
예제 #6
0
        private async void SignOutClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Initialize access to the Live Connect SDK.
                LiveAuthClient LCAuth = new LiveAuthClient();
                LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
                // Sign the user out, if he or she is connected;
                //  if not connected, skip this and just update the UI
                if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    
                    LCAuth.Logout();
                }

                // At this point, the user should be disconnected and signed out, so
                //  update the UI.
                this.userName.Text = "You're not signed in.";
                Connection.User = null;
                // Show sign-in button.
                signInBtn.Visibility = Windows.UI.Xaml.Visibility.Visible;
                signOutBtn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                new MessageDialog("The app is exiting since you are no longer logged in.").ShowAsync();
                App.Current.Exit();
            }
            catch (LiveConnectException x)
            {
                // Handle exception.
            }
        }
예제 #7
0
        /// <summary>
        /// Versucht Login, ohne einen entsprechenden Dialog zu zu zeigen.
        /// </summary>
        /// <returns>Ein MobileServiceUser, der awaited werden kann oder null bei Misserfolg.</returns>
        internal static async Task<MobileServiceUser> AuthenticateSilent(MobileServiceClient mobileService)
        {
            LiveAuthClient liveAuthClient = new LiveAuthClient(APIKeys.LiveClientId);
            session = (await liveAuthClient.InitializeAsync()).Session;
            return await mobileService.LoginWithMicrosoftAccountAsync(session.AuthenticationToken);

        }
예제 #8
0
        private async void SignOutClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Initialize access to the Live Connect SDK.
                LiveAuthClient LCAuth = new LiveAuthClient();
                LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
                // Sign the user out, if he or she is connected;
                //  if not connected, skip this and just update the UI
                if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    LCAuth.Logout();
                }

                // At this point, the user should be disconnected and signed out, so
                //  update the UI.
                this.userName.Text = "You're not signed in.";

                // Show sign-in button.
                signInBtn.Visibility = Windows.UI.Xaml.Visibility.Visible;
                signOutBtn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            catch (LiveConnectException x)
            {
                // Handle exception.
                this.userName.Text = x.Message.ToString();
                throw new NotImplementedException();
            }
        }
예제 #9
0
 //인스턴스 생성용 method
 private async void login_Client()
 {
     try
     {
         //Client 생성
         authClient = new LiveAuthClient();
         //초기화
         result = await authClient.InitializeAsync();
         //로그인
         loginResult = await authClient.LoginAsync(scope);
         //로그인 할 떄 cancel을 누르면 뒤로 돌아가기
     }
     catch (NullReferenceException ex)
     {
         //로그인 할 때 cancel을 누르면 nullreferenceException 발생
         //뒤로가기
         ex.Message.ToString();
         messagePrint(false);
         if (Frame.CanGoBack)
         {
             Frame.GoBack();
         }
     }
     catch (Exception ex)
     {
         //기타 Exception을 위한 catch
         ex.Message.ToString();
         messagePrint(false);
         if(Frame.CanGoBack)
         {
             Frame.GoBack();
         }
     }
 }
        /// <summary>
        /// Creates a new TailoredAuthClient class.
        /// </summary>
        /// <param name="authClient">The LiveAuthClient instance.</param>
        public TailoredAuthClient(LiveAuthClient authClient)
        {
            Debug.Assert(authClient != null, "authClient cannot be null.");

            this.authClient = authClient;
            this.authenticator = new OnlineIdAuthenticator();
        }
        private async Task<dynamic> GetUserLogged() 
        {
            var liveIdClient = new LiveAuthClient();
            Task<LiveLoginResult> tskLoginResult = liveIdClient.LoginAsync(new string[] { "wl.signin" });
            tskLoginResult.Wait();

            switch (tskLoginResult.Result.Status)
            {
                case LiveConnectSessionStatus.Connected:
                    try
                    {
                        LiveConnectClient client = new LiveConnectClient(tskLoginResult.Result.Session);
                        LiveOperationResult liveOperationResult = await client.GetAsync("me");

                        dynamic operationResult = liveOperationResult.Result;
                        return operationResult;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("ERRO, {0}", ex.Message), ex);
                    }
                case LiveConnectSessionStatus.NotConnected:
                    break;
            }

            return null;
        }
        /// <summary>
        /// Tests logging into MobileService with Live SDK token. App needs to be assosciated with a WindowsStoreApp
        /// </summary>
        private async Task TestLiveSDKLogin()
        {
            try
            {
                LiveAuthClient liveAuthClient = new LiveAuthClient(GetClient().MobileAppUri.ToString());
                LiveLoginResult result = await liveAuthClient.InitializeAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });
                if (result.Status != LiveConnectSessionStatus.Connected)
                {
                    result = await liveAuthClient.LoginAsync(new string[] { "wl.basic", "wl.offline_access", "wl.signin" });
                }
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    LiveConnectSession session = result.Session;
                    LiveConnectClient client = new LiveConnectClient(result.Session);
                    LiveOperationResult meResult = await client.GetAsync("me");
                    MobileServiceUser loginResult = await GetClient().LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);

                    Log(string.Format("{0} is now logged into MobileService with userId - {1}", meResult.Result["first_name"], loginResult.UserId));
                }
            }
            catch (Exception exception)
            {
                Log(string.Format("ExceptionType: {0} Message: {1} StackTrace: {2}",
                                                exception.GetType().ToString(),
                                                exception.Message,
                                                exception.StackTrace));
                Assert.Fail("Log in with Live SDK failed");
            }
        }
        private async void InitializePage()
        {
            try
            {
                this.authClient = new LiveAuthClient();
                LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);
                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    if (this.authClient.CanLogout)
                    {
                        this.btnLogin.Content = "Sign Out";
                    }
                    else
                    {
                        this.btnLogin.Visibility = Visibility.Collapsed;
                    }

                    this.liveClient = new LiveConnectClient(loginResult.Session);
                    this.GetMe();
                }
            }
            catch (LiveAuthException authExp)
            {
                this.tbResponse.Text = authExp.ToString();
            }
        }
        private async void InitializePage()
        {
            try
            {
                this.authClient = new LiveAuthClient();
                LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes);
                if (loginResult.Status == LiveConnectSessionStatus.Connected)
                {
                    if (this.authClient.CanLogout)
                    {
                        this.btnLogin.Content = "Sign Out";
                    }
                    else
                    {
                        this.btnLogin.Visibility = Visibility.Collapsed;
                    }

                    this.liveClient = new LiveConnectClient(loginResult.Session);
                }
            }
            catch (LiveAuthException)
            {
                // TODO: Display the exception
            }
        }
        public MainViewModel(IPopupService popupService, SynchronizationContext synchonizationContext)
        {
            var client = new MobileServiceClient(
                _mobileServiceUrl,
                _mobileServiceKey);

            _liveAuthClient = new LiveAuthClient(_mobileServiceUrl);
            
            // Apply a ServiceFilter to the mobile client to help with our busy indication
            _mobileServiceClient = client.WithFilter(new DotoServiceFilter(
                busy =>
                {
                    IsBusy = busy;
                }));
            _popupService = popupService;
            _synchronizationContext = synchonizationContext;
            _invitesTable = _mobileServiceClient.GetTable<Invite>();
            _itemsTable = _mobileServiceClient.GetTable<Item>();
            _profilesTable = _mobileServiceClient.GetTable<Profile>();
            _listMembersTable = _mobileServiceClient.GetTable<ListMembership>();
            _devicesTable = _mobileServiceClient.GetTable<Device>();
            _settingsTable = _mobileServiceClient.GetTable<Setting>();

            SetupCommands();

            LoadSettings();
        }
예제 #16
0
 public void MyTestInitialize() 
 {
     this.authClient = new LiveAuthClient(TestAuthClient.ClientId);
     this.authClient.AuthClient = new TestAuthClient(this.authClient);
     this.authClient.AuthClient.CloseSession();
     WebRequestFactory.Current = new TestWebRequestFactory();
 }
예제 #17
0
        private async Task SetNameField(Boolean login)
        {
          // await App.updateUserName(this.userName, login);
            this.userName.Text = Connection.UserName;
            Boolean userCanSignOut = true;

            LiveAuthClient LCAuth = new LiveAuthClient();
            LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();

            if (LCLoginResult.Status == LiveConnectSessionStatus.Connected)
            {
                userCanSignOut = LCAuth.CanLogout;
            }

            if (this.userName.Text.Equals("You're not signed in."))
            {
                // Show sign-in button.
                signInBtn.Visibility = Windows.UI.Xaml.Visibility.Visible;
                signOutBtn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else
            {
                // Show sign-out button if they can sign out.
                signOutBtn.Visibility = (userCanSignOut ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed);
                signInBtn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
        }
예제 #18
0
        public async Task<bool> LoginAsync(bool isSilent = true)
        {
            bool result = false;
            LastError = null;
            RestoreData = null;

            IsInProgress = true;

            try
            {
                var authClient = new LiveAuthClient();
                LiveLoginResult res = isSilent ? await authClient.InitializeAsync(scopes) : await authClient.LoginAsync(scopes);
                Session = res.Status == LiveConnectSessionStatus.Connected ? res.Session : null;

                result = true;
            }
            catch (LiveAuthException ex)
            {
                LastError = ex.Message;
            }

            IsInProgress = false;

            return result;
            //CheckPendingBackgroundOperations();
        }
예제 #19
0
        private  async void uploadButton_Click(object sender, RoutedEventArgs e)//上传
        {
            try
            {
                msgText.Text = "亲:正在上传";
                var authClient = new LiveAuthClient();
                var authResult = await authClient.LoginAsync(new string[] { "wl.skydrive", "wl.skydrive_update" });
                if (authResult.Session != null)
                {
                    var liveConnectClient = new LiveConnectClient(authResult.Session);
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    StorageFile file = await localFolder.GetFileAsync(App.WordBookFileName);
                    String fileText = await FileIO.ReadTextAsync(file);

                    LiveUploadOperation uploadOperation = await liveConnectClient.CreateBackgroundUploadAsync(
                        "me/skydrive", file.Name, file, OverwriteOption.Overwrite);
                    LiveOperationResult uploadResult = await uploadOperation.StartAsync();

                    if (uploadResult.Result != null)
                    {
                        msgText.Text = "恭喜:您已成功同步生词至OneDrive!";
                    }

                }
            }
            catch (LiveAuthException ex)
            {
                msgText.Text = ex.Message;
            }
            catch (LiveConnectException ex)
            {
                msgText.Text = ex.Message;
            }

        }
예제 #20
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var liveIdClient = new LiveAuthClient();
            Task<LiveLoginResult> tskLoginResult = liveIdClient.LoginAsync(new string[] { "wl.signin" });
            tskLoginResult.Wait();

            switch (tskLoginResult.Result.Status)
            {
                case LiveConnectSessionStatus.Connected:

                    try
                    {
                        LiveConnectClient client = new LiveConnectClient(tskLoginResult.Result.Session);
                        LiveOperationResult liveOperationResult = await client.GetAsync("me");

                        dynamic operationResult = liveOperationResult.Result;
                        string name = string.Format("Hello {0} ", operationResult.first_name);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("ERRO, {0}", ex.Message), ex);
                    }

                    break;
                case LiveConnectSessionStatus.NotConnected:
                    int j = 10;
                    break;
                default:
                    int z = 10;
                    break;
            }
        }
예제 #21
0
        public string AskForRegistrationUrl(UserProfileInfo user, string redirectUrl, out int tempCredentialId)
        {
            LiveAuthClient auth = new LiveAuthClient(clientId, clientSecret, redirectUrl);
            string url = auth.GetLoginUrl(scopes);
            tempCredentialId = -1;

            return url;
        }
예제 #22
0
 public async void DoLogin(string clientId)
 {
     var scopes = new List<string>();
     scopes.Add("wl.calendars");
     scopes.Add("http://outlook.office.com/Calendars.ReadWrite");
     var sdk = new LiveAuthClient(clientId);
     var result = await sdk.InitializeAsync(scopes);
     var url = sdk.GetLoginUrl(scopes);
     var token = sdk.Session.AuthenticationToken;
 }
예제 #23
0
        public async Task<LiveConnectSession> LogonAsync()
        {
            var scopes = new ArrayList();
            scopes.AddAll(requestedScopes);

            var client = new LiveAuthClient(activity, CLIENTID);
            var loginAuthListener = new OneDriveAuthListener();
            client.Login(activity, scopes, loginAuthListener);
            return await loginAuthListener.Task;
        }
예제 #24
0
 public async Task Activate()
 {
     var session = _cache.SkydriveSession;
     if (session == null)
     {
         var authClient = new LiveAuthClient(ApiKeys.SkyDriveClientId);
         var x = await authClient.InitializeAsync();
         session = x.Session;
     }
     _liveClient = new LiveConnectClient(session);
 }
예제 #25
0
        public async Task DisconnectAsync()
        {
            var cl = new LiveAuthClient(CLIENT_ID);

            await cl.Initialize();

            if (cl.Session != null)
            {
                cl.Logout();
            }
        }
예제 #26
0
        public async Task<LiveConnectSession> GetSession()
        {
            _client = new LiveAuthClient(_clientId, _tokenHandler);

            var existingToken = await _tokenHandler.RetrieveRefreshTokenAsync();
            if (existingToken != null)
            {
                var loginResult = await _client.InitializeAsync();
                return loginResult.Session;
            }
            return await LoginAsync();
        }
        /// <summary>
        /// Initializes a new instance of the LiveAuthClientCore class.
        /// </summary>
        public LiveAuthClientCore(
            string clientId,
            IRefreshTokenHandler refreshTokenHandler,
            LiveAuthClient authClient)
        {
            Debug.Assert(!string.IsNullOrEmpty(clientId));
            Debug.Assert(authClient != null);

            this.clientId = clientId;
            this.refreshTokenHandler = refreshTokenHandler;
            this.publicAuthClient = authClient;
        }
예제 #28
0
		private async void InitAuth()
		{
			if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
			{
				var authClient = new LiveAuthClient();
				LiveLoginResult authResult =
					await authClient.LoginAsync(new List<string>() { "wl.signin", "wl.basic", "wl.skydrive" });
				if (authResult.Status == LiveConnectSessionStatus.Connected)
				{
					// An app-level property for the session.
					App.Session = authResult.Session;
				}
			}
		}
        /// <summary>
        /// The login async.
        /// </summary>
        /// <returns>
        /// The <see cref="Task"/> object.
        /// </returns>
        /// 
        public async Task<AuthenticationSession> LoginAsync()
        {
            Exception rException = null;
            try
            {
                _authClient = new LiveAuthClient();
                // Rui: https://msdn.microsoft.com/en-us/library/hh694244.aspx
                //var loginResult = await _authClient.InitializeAsync(_scopes);
                
                // Rui: https://msdn.microsoft.com/en-us/library/hh533677.aspx
                var result = await _authClient.LoginAsync(_scopes);

                //if (loginResult.Status == LiveConnectSessionStatus.Connected)
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    
                    //_liveSession = loginResult.Session;
                    _liveSession = result.Session;
                    var meResult = await GetUserInfo();
                    var session = new AuthenticationSession
                    {
                        AccessToken = result.Session.AccessToken,
                        //AccessToken = loginResult.Session.AccessToken,
                        Provider = Constants.MicrosoftProvider,
                        UserInfo = meResult["name"].ToString()
                    };
                    return session;
                }

            }

            catch (LiveAuthException authExp)
            {
                System.Diagnostics.Debug.WriteLine("LiveAuthException = " + authExp.ToString());
            }

            catch (LiveConnectException connExp)
            {
                System.Diagnostics.Debug.WriteLine("LiveConnectException = " + connExp.ToString());
            }

            catch (Exception ex)
            {
                rException = ex;
                System.Diagnostics.Debug.WriteLine("rException = " + rException.ToString());
            }
            await _logManager.LogAsync(rException);

            return null;
        }
예제 #30
0
        public override bool Logout()
        {
            LiveAuthClient authClient;
            if (AuthClient == null)
                AuthClient = authClient = new LiveAuthClient();
            else
                authClient = (LiveAuthClient)AuthClient;

            authClient.Logout();
            IsSignIn = false;
            User = null;

            return true;
        }
예제 #31
0
        /// <summary>
        /// Initializes an new instance of the LiveAuthClientCore class.
        /// </summary>
        public LiveAuthClientCore(
            string clientId,
            string clientSecret,
            IRefreshTokenHandler refreshTokenHandler,
            LiveAuthClient authClient)
        {
            Debug.Assert(!string.IsNullOrEmpty(clientId));
            Debug.Assert(!string.IsNullOrEmpty(clientSecret));
            Debug.Assert(authClient != null);

            this.clientId            = clientId;
            this.clientSecret        = clientSecret;
            this.refreshTokenHandler = refreshTokenHandler;
            this.publicAuthClient    = authClient;
        }
예제 #32
0
        /// <summary>
        /// Load cached refresh token if there is one.
        /// </summary>
        public LiveConnectSession LoadSession(LiveAuthClient authClient)
        {
            LiveConnectSession session = null;
            var appData = IsolatedStorageSettings.ApplicationSettings;

            if (appData.Values.Count > 0)
            {
                session = new LiveConnectSession(authClient);

                if (appData.Contains(LiveAuthClient.StorageConstants.RefreshToken))
                {
                    session.RefreshToken = appData[LiveAuthClient.StorageConstants.RefreshToken] as string;
                }
            }

            return(session);
        }
예제 #33
0
        /// <summary>
        /// Creates a LiveConnectSession object based on the parsed response.
        /// </summary>
        internal static LiveConnectSession CreateSession(LiveAuthClient client, IDictionary <string, object> result)
        {
            var session = new LiveConnectSession(client);

            Debug.Assert(result.ContainsKey(AuthConstants.AccessToken));
            if (result.ContainsKey(AuthConstants.AccessToken))
            {
                session.AccessToken = result[AuthConstants.AccessToken] as string;

                if (result.ContainsKey(AuthConstants.AuthenticationToken))
                {
                    session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string;
                }
            }

            return(session);
        }
예제 #34
0
        /// <summary>
        /// Parse the response data.
        /// </summary>
        private LiveLoginResult ParseResponseFragment(string fragment)
        {
            Debug.Assert(!string.IsNullOrEmpty(fragment));

            LiveLoginResult loginResult         = null;
            IDictionary <string, object> result = LiveAuthClient.ParseQueryString(fragment);

            if (result.ContainsKey(AuthConstants.AccessToken))
            {
                LiveConnectSession sessionData = CreateSession(this, result);

                loginResult = new LiveLoginResult(LiveConnectSessionStatus.Connected, sessionData);
            }
            else if (result.ContainsKey(AuthConstants.Error))
            {
                loginResult = GetErrorResult(result);
            }

            return(loginResult);
        }
예제 #35
0
        /// <summary>
        /// Creates a LiveConnectSession object based on the parsed response.
        /// </summary>
        internal static LiveConnectSession CreateSession(LiveAuthClient client, IDictionary <string, object> result)
        {
            var session = new LiveConnectSession(client);

            Debug.Assert(result.ContainsKey(AuthConstants.AccessToken));
            if (result.ContainsKey(AuthConstants.AccessToken))
            {
                session.AccessToken = result[AuthConstants.AccessToken] as string;

                if (result.ContainsKey(AuthConstants.AuthenticationToken))
                {
                    session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string;
                }

                if (result.ContainsKey(AuthConstants.ExpiresIn))
                {
                    if (result[AuthConstants.ExpiresIn] is string)
                    {
                        session.Expires = LiveAuthClient.CalculateExpiration(result[AuthConstants.ExpiresIn] as string);
                    }
                    else
                    {
                        session.Expires = DateTimeOffset.UtcNow.AddSeconds((int)result[AuthConstants.ExpiresIn]);
                    }
                }

                if (result.ContainsKey(AuthConstants.Scope))
                {
                    session.Scopes =
                        LiveAuthClient.ParseScopeString(HttpUtility.UrlDecode(result[AuthConstants.Scope] as string));
                }

                if (result.ContainsKey(AuthConstants.RefreshToken))
                {
                    session.RefreshToken = result[AuthConstants.RefreshToken] as string;
                }
            }

            return(session);
        }
예제 #36
0
        private Task <LiveLoginResult> AuthenticateAsync(bool useSilentFlow)
        {
            var tcs = new TaskCompletionSource <LiveLoginResult>();

            this.AuthClient.AuthenticateAsync(
                this.clientId,
                LiveAuthClient.BuildScopeString(this.scopes),
                useSilentFlow,
                (string responseData, Exception exception) =>
            {
                if (exception != null)
                {
                    tcs.TrySetException(exception);
                    Interlocked.Decrement(ref this.asyncInProgress);
                }
                else
                {
                    this.ProcessAuthResponse(responseData, (LiveLoginResult result) =>
                    {
                        if (result.Error != null)
                        {
                            this.Session = null;
                            tcs.TrySetException(result.Error);
                        }
                        else
                        {
                            this.Session = result.Session;
                            this.AuthClient.SaveSession(this.Session);
                            tcs.TrySetResult(result);
                        }

                        Interlocked.Decrement(ref this.asyncInProgress);
                    });
                }
            });

            return(tcs.Task);
        }
예제 #37
0
        private async void TryRefreshToken(Action <LiveLoginResult> completionCallback)
        {
            LiveLoginResult result = await this.AuthClient.AuthenticateAsync(
                LiveAuthClient.BuildScopeString(this.currentScopes),
                true);

            if (result.Status == LiveConnectSessionStatus.NotConnected &&
                this.currentScopes.Count > 1)
            {
                // The user might have revoked one of the scopes while the app is running. Try getting a token for the remaining scopes
                // by passing in only the "wl.signin" scope. The server should return a token that contains all remaining scopes.
                this.currentScopes = new List <string>(new string[] { LiveAuthClient.SignInOfferName });
                result             = await this.AuthClient.AuthenticateAsync(
                    LiveAuthClient.BuildScopeString(this.currentScopes),
                    true);
            }

            if (result.Session != null && !AreSessionsSame(this.Session, result.Session))
            {
                this.Session = result.Session;
            }

            completionCallback(result);
        }
 /// <summary>
 /// Load session from persistence store. N/A on Windows 8.
 /// </summary>
 public LiveConnectSession LoadSession(LiveAuthClient authClient)
 {
     // We don't store any session data on Win8.
     return(null);
 }
예제 #39
0
 internal LiveConnectSession(LiveAuthClient authClient)
 {
     this.AuthClient = authClient;
 }
 /// <summary>
 ///     Constructor for creating a new OperationState object.
 /// </summary>
 public OperationState(TaskCompletionSource <LiveLoginResult> tcs, LiveAuthClient client)
 {
     this.Tcs        = tcs;
     this.AuthClient = client;
 }
 /// <summary>
 ///     Initializes the auth client and detects if a user is already signed in.
 ///     If a user is already signed in, this method creates a valid Session.
 ///     This call is UI-less.
 /// </summary>
 /// <param name="client">the LiveAuthClient object this method is attached to.</param>
 public static Task <LiveLoginResult> Initialize(this LiveAuthClient client)
 {
     return(client.Initialize(null));
 }
예제 #42
0
 /// <summary>
 /// Initialize the PhoneAuthClient object.
 /// </summary>
 public PhoneAuthClient(LiveAuthClient liveAuthClient)
 {
     Debug.Assert(liveAuthClient != null);
     this.liveAuthClient = liveAuthClient;
 }