public SkyDriveImportPage()
        {
            InitializeComponent();
            this.labelHeight = this.statusLabel.Height;
            this.session = PhoneApplicationService.Current.State["parameter"] as LiveConnectSession;
            PhoneApplicationService.Current.State.Remove("parameter");
            if (this.session == null)
            {
                throw new ArgumentException("Parameter passed to SkyDriveImportPage must be a LiveConnectSession.");
            }

            this.skydriveStack = new List<List<SkyDriveListItem>>();
            this.skydriveStack.Add(new List<SkyDriveListItem>());
            this.skydriveStack[0].Add(new SkyDriveListItem()
            {
                Name = "SkyDrive",
                SkyDriveID = "me/skydrive",
                Type = SkyDriveItemType.Folder,
                ParentID = ""
            });
            this.currentFolderBox.Text = this.skydriveStack[0][0].Name;

            this.BackKeyPress += SkyDriveImportPage_BackKeyPress;

#if GBC
            this.fileFormatLabel.Text = AppResources.SkyDriveFileFormatHint2;
            this.titleLabel.Text = AppResources.ApplicationTitle2;
#endif
        }
        public async void LoginWithSession()
        {
            try
            {
                LiveConnectSession savedSession = new LiveConnectSession(this.authClient);
                savedSession.RefreshToken = TestAuthClient.FakeOldRefreshToken;

                this.authClient.AuthClient.SaveSession(savedSession);

                await this.InitializeAuthClient(TestAuthClient.Scopes);

                LiveConnectSession session = this.authClient.Session;
                Assert.IsNotNull(session, "Session is null.");
                Assert.IsTrue(session.IsValid, "Session is not valid.");

                Assert.IsTrue(session.AccessToken == TestAuthClient.FakeAccessToken, "AccessToken is incorrect.");
                Assert.IsTrue(session.RefreshToken == TestAuthClient.FakeRefreshToken, "RefreshToken is incorrect.");
                Assert.IsTrue(new List<string>(session.Scopes).Count == TestAuthClient.Scopes.Length, "Scope count is incorrect.");
            }
            catch (Exception e)
            {
                Assert.Fail(e.ToString());
            }
            finally
            {
                EnqueueTestComplete();
            }
        }
        public async static Task<List<SkyDriveEntity>> GetFolderContents(LiveConnectSession session, string folderId)
        {
            try
            {
                LiveConnectClient client = new LiveConnectClient(session);
                LiveOperationResult result = await client.GetAsync(folderId + "/files");

                //clear entries in data
                data.Clear();

                List<object> container = (List<object>)result.Result["data"];
                foreach (var item in container)
                {
                    SkyDriveEntity entity = new SkyDriveEntity();

                    IDictionary<string, object> dictItem = (IDictionary<string, object>)item;
                    string type = dictItem["type"].ToString();
                    entity.IsFolder = type == "folder" || type == "album" ? true : false;
                    entity.ID = dictItem["id"].ToString();
                    entity.Name = dictItem["name"].ToString();
                    data.Add(entity);
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        private void SignInButtonSessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
        {
            if (e.Session != null)
            {
                _session = e.Session;
                var client = new LiveConnectClient(_session);
                EventHandler<LiveOperationCompletedEventArgs> handler = null;
                handler = (s, even) =>
                              {
                                  client.GetCompleted -= handler;
                                  var resultDict = (Dictionary<string, object>)even.Result;

                                  var items = (List<object>)resultDict["data"];
                                  // Перебираем все объекты в папке, отбиаем только тип folder
                                  foreach (var item in
                                      items.Cast<Dictionary<string, object>>().Where(item => item["type"].ToString() == "folder"))
                                  {
                                      _files.Add(new FileModel() { Name = item["name"].ToString() });
                                  }
                                  lbFileList.ItemsSource = _files;
                              };
                client.GetCompleted += handler;
                //Путь к корню вашего skydrive
                client.GetAsync("me/skydrive/files");

            }
        }
        /// <summary>
        ///  Provider class to access SkyDrive contents.
        /// </summary>
        /// <param name="session">A live connect session which will be used to retrieve cloud content.</param>
        public SkyDriveProvider(LiveConnectSession session)
            : base("SkyDrive", SupportedDrive.SkyDrive, RootDirectory)
        {

            Init(session);

        }
Exemple #6
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);

        }
 public async void SetSession(LiveConnectSession session)
 {
     _syncContext.Send(delegate
     {
         SkyDriveHelper.SetSession(session);
     }, null);
 }
        /// <summary>
        /// Authenticate the user.  Ask user for consent if neccessary.
        /// </summary>
        public async Task<LiveLoginResult> AuthenticateAsync(string scopes, bool silent)
        {
            Exception error = null;
            string accessToken = null;
            string authenticationToken = null;

            LiveLoginResult result = null;

            try
            {
                accessToken = await this.GetAccessToken(scopes, silent);
                LiveConnectSession session = new LiveConnectSession(this.authClient);
                session.AccessToken = accessToken;

                if (!string.IsNullOrEmpty(this.authClient.RedirectUrl) &&
                    !this.authClient.RedirectUrl.Equals(Win8ReturnUriScheme, StringComparison.OrdinalIgnoreCase))
                {
                    authenticationToken = await this.GetAuthenticationToken(this.authClient.RedirectUrl, silent);
                    session.AuthenticationToken = authenticationToken;
                }

                result = new LiveLoginResult(LiveConnectSessionStatus.Connected, session);
            }
            catch (TaskCanceledException)
            {
                result = new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null);
            }
            catch (Exception comExp)
            {
                switch (comExp.HResult)
                {
                    case TailoredAuthClient.UserNotFoundLoginExceptionHResult:
                        result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null);
                        break;
                    case TailoredAuthClient.ConsentNotGrantedExceptionHResult:
                        result = new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null);
                        break;
                    case TailoredAuthClient.InvalidClientExceptionHResult:
                    case TailoredAuthClient.InvalidAuthTargetExceptionHResult:
                        error = new LiveAuthException(AuthErrorCodes.InvalidRequest, ResourceHelper.GetString("InvalidAuthClient"), comExp);
                        break;
                    default:
                        error = new LiveAuthException(AuthErrorCodes.ServerError, ResourceHelper.GetString("ServerError"), comExp);
                        break;
                }
            }

            if (result == null)
            {
                Debug.Assert(error != null);

                result = new LiveLoginResult(error);
            }

            return result;
        }
 public SkyDriveBackup(MyLiveConnectClient liveConnectClient, string appFolderName, LiveConnectSession session, List<string> fileNames, BackupViewModel model)
 {
     SkyDriveFolderId = string.Empty;
     Files = new Dictionary<string, string>();
     FileNames = fileNames;
     _session = session;
     _appFolderName = appFolderName;
     LiveClient = liveConnectClient;
     _model = model;
     GetFolders();
 }
 public void OnAuthComplete(LiveStatus status, LiveConnectSession session, Object userState)
 {
     try
     {
         source.SetResult(session);
     }
     catch (Exception ex)
     {
         source.TrySetException(ex);
     }
 }
 private void signInButton_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
 {
     if (e.Status == LiveConnectSessionStatus.Connected)
     {
         MainPage.session = e.Session;
         this.NavigationService.Navigate(new Uri("/Index.xaml", UriKind.Relative));
     }
     else
     {
         MainPage.session = null;
     }
 }
        /// <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;
        }
Exemple #13
0
        public BackupPage()
        {
            InitializeComponent();

            this.session = PhoneApplicationService.Current.State["parameter"] as LiveConnectSession;
            PhoneApplicationService.Current.State.Remove("parameter");
            if (this.session == null)
            {
                throw new ArgumentException("Parameter passed to SkyDriveImportPage must be a LiveConnectSession.");
            }
            this.db = ROMDatabase.Current;

            this.romList.ItemsSource = db.GetROMList();
        }
        private async void Init(LiveConnectSession session)
        {
            if (session == null)
                throw new NullReferenceException("The 'session' parameter cannot be null");
            _liveClient = new LiveConnectClient(session);
            _absoluteRootDirectory = RootDirectory;

            LiveOperationResult operationResult = await _liveClient.GetAsync("me"); //me, or user id will be taken cared of by the session object which will specifically connect to a particular user. so no need to worry about supporting multiple user accounts here.
            dynamic result = operationResult.Result;
            this.UserName = result.name;

            _rootCloudObject = await GetRootDirectoryAsync();


            //_rootCloudObject = new SkyDriveObject(operationResult.Result.Result);
        }
Exemple #15
0
 public async Task<LiveLoginResult> Authenticate()
 {
     LiveLoginResult result = null;
     try
     {
         //string url = _liveAuthClient.GetLoginUrl(new string[] { "wl.signin", "wl.basic", "wl.emails"});
         result = await _liveAuthClient.InitializeWebSessionAsync(new HttpContextWrapper(HttpContext.Current));
         if (false)
         {
             result = await _liveAuthClient.ExchangeAuthCodeAsync(new HttpContextWrapper(HttpContext.Current));
         }
         _session = result.Session;
     }
     catch (LiveAuthException){}
     return result;
 }
Exemple #16
0
 public static void MicrosoftAccount_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
 {
     if (e.Status == Microsoft.Live.LiveConnectSessionStatus.Connected)
     {
         MicrosoftAccountClient = new LiveConnectClient(e.Session);
         MicrosoftAccountSession = e.Session;
         MicrosoftAccountClient.GetCompleted += client_GetCompleted;
         MicrosoftAccountClient.GetAsync("me", null);
     }
     else
     {
         CoreViewModel.Instance.MicrosoftAccountImage = "/Images/stock_user.png";
         CoreViewModel.Instance.MicrosoftAccountName = "no Microsoft Account connected";
         MicrosoftAccountClient = null;
     }
 }
Exemple #17
0
 private async void SignInButton_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
 {
     if (e.Status == Microsoft.Live.LiveConnectSessionStatus.Connected)
     {
         _currentSession = e.Session;
         this.liveClient = new LiveConnectClient(e.Session);
         await this.GetMe();
         this.Proceed.Visibility = System.Windows.Visibility.Visible;
     }
     else
     {
         this.Proceed.Visibility = System.Windows.Visibility.Collapsed;
         this.liveClient = null;
         this.tbGreeting.Text = e.Error != null ? e.Error.ToString() : string.Empty;
     }
 }
        /// <summary>
        /// Creates a new LiveConnectClient instance.
        /// </summary>
        /// <param name="session">the session object that contains the authentication information.</param>
        public LiveConnectClient(LiveConnectSession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            this.Session = session;
            this.syncContext = SynchronizationContextWrapper.Current;

#if DEBUG
            this.ApiEndpoint =
                string.IsNullOrEmpty(LiveConnectClient.ApiEndpointOverride)
                ? LiveConnectClient.DefaultApiEndpoint
                : LiveConnectClient.ApiEndpointOverride;
#else
            this.ApiEndpoint = LiveConnectClient.DefaultApiEndpoint;
#endif
        }
        private async void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            // 認証用インスタンスを生成
            var authClient = new LiveAuthClient();

            // スコープを設定
            var scopes = new List<string>() { "wl.signin", "wl.skydrive_update" };

            // ログイン用ダイアログを表示する
            var authResult = await authClient.LoginAsync(scopes);
            if (authResult.Status == LiveConnectSessionStatus.Connected)
            {
                Session = authResult.Session;
            }
            else
            {
                // サインインに失敗
                return;
            }
        }
		//event triggered when Skydrive sign in status is changed
		private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
		{
			//if the user is signed in
			if (e.Status == LiveConnectSessionStatus.Connected)
			{
				_session = e.Session;
				_client = new LiveConnectClient(e.Session);
				_model.Message = "Accessing SkyDrive...";


				_myClient = new MyLiveConnectClient(e.Session);

				_backup = new SkyDriveBackup(_myClient, SkyDriveFolderName, e.Session, new List<string> { "ReminderBackup.txt", "HistoryBackup.txt", "HarvestBackup.txt" }, _model);
			}
			else
			{
				_model.Message = "Not signed in.";
				_client = null;
			}
		}
Exemple #21
0
        /// <summary>
        /// Login mit einem entsprechenden Dialog.
        /// </summary>
        /// <returns>Ein MobileServiceUser, der awaited werden kann oder null bei Misserfolg.</returns>
        internal async static Task<MobileServiceUser> Authenticate(MobileServiceClient mobileService)
        {
            LiveAuthClient liveAuthClient = new LiveAuthClient(APIKeys.LiveClientId);
            var source = new TaskCompletionSource<MobileServiceUser>();

            liveAuthClient.Logout();

            var scopes = new string[] { "wl.basic", "wl.offline_access", "wl.signin" };
            App.Current.RootVisual.Visibility = System.Windows.Visibility.Collapsed;

            try
            {
                session = (await liveAuthClient.LoginAsync(scopes)).Session;
            }
            finally
            {
                App.Current.RootVisual.Visibility = System.Windows.Visibility.Visible;
            }
            return await mobileService.LoginWithMicrosoftAccountAsync(session.AuthenticationToken);

        }
Exemple #22
0
        void btnSignin_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
        {
            if (e.Status == LiveConnectSessionStatus.Connected)
            {
                PhoneApplicationService.Current.State["parameter"] = this.session = e.Session;
                this.NavigationService.Navigate(new Uri("/SkyDriveImportPage.xaml", UriKind.Relative));

                //LiveConnectClient client = new LiveConnectClient(e.Session);
                //this.session = e.Session;
                //testLabel.Text = "Signed in.";
                //client.GetCompleted += client_GetCompleted;
                //client.GetAsync("me", null);
            }
            else
            {
                session = null;
                if (e.Error != null)
                {
                    statusLabel.Text = "Error calling API: " + e.Error.ToString();
                }
            }
        }
        private async System.Threading.Tasks.Task Authenticate()
        {
            LiveAuthClient liveIdClient = new LiveAuthClient("https://sendit.azure-mobile.net/");


            while (session == null)
            {
                // Force a logout to make it easier to test with multiple Microsoft Accounts
                if (liveIdClient.CanLogout)
                    liveIdClient.Logout();


                LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });
                if (result.Status == LiveConnectSessionStatus.Connected)
                {
                    session = result.Session;
                    LiveConnectClient client = new LiveConnectClient(result.Session);
                    LiveOperationResult meResult = await client.GetAsync("me");
                    MobileServiceUser loginResult = await App.MobileService.LoginAsync(result.Session.AuthenticationToken);


                    string title = string.Format("Welcome {0}!", meResult.Result["first_name"]);
                    var message = string.Format("You are now logged in - {0}", loginResult.UserId);
                    var dialog = new MessageDialog(message, title);
                    dialog.Commands.Add(new UICommand("OK"));
                    await dialog.ShowAsync();
                }
                else
                {
                    session = null;
                    var dialog = new MessageDialog("You must log in.", "Login Required");
                    dialog.Commands.Add(new UICommand("OK"));
                    await dialog.ShowAsync();
                }
            }


        }
        /// <summary>
        /// Creates a LiveConnectSession object based on the parsed response.
        /// </summary>
        private static LiveConnectSession CreateSession(IDictionary<string, object> result)
        {
            var session = new LiveConnectSession();

            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 = CalculateExpiration(result[AuthConstants.ExpiresIn] as string);
                    }
                    else
                    {
                        session.Expires = DateTimeOffset.UtcNow.AddSeconds((int)result[AuthConstants.ExpiresIn]);
                    }
                }

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

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

            return session;
        }
        private async Task<Boolean> LogInToSkydrive()
        {
            var hasErrors = false;

            do
            {
                try
                {
                    hasErrors = false;
                    this.retrySelected = false;

                    LiveAuthClient auth = new LiveAuthClient();
                    LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.signin", "wl.skydrive", "wl.skydrive_update" });

                    if (loginResult.Status == LiveConnectSessionStatus.Connected)
                    {
                        LiveSession = loginResult.Session;
                        return true;
                    }
                }
                catch (LiveAuthException)
                {
                    hasErrors = true;
                }

                if (hasErrors)
                {
                    var errorTitle = "Live Connect error";
                    await ShowMessage(errorTitle, "Exception occured while logging in to Skydrive.");
                }
            } while (this.retrySelected);

            return false;
        }
		public OneNoteRepository(LiveConnectSession liveConnectSession)
		{
			this.liveConnectSession = liveConnectSession;
		}
        private static bool AreSessionsSame(LiveConnectSession session1, LiveConnectSession session2)
        {
            if (session1 != null && session2 != null)
            {
                return
                    session1.AccessToken == session2.AccessToken &&
                    session1.AuthenticationToken == session2.AuthenticationToken;
            }

            return session1 == session2;
        }
        /// <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;
        }
Exemple #29
0
        /// <summary>
        /// Writes the user current session.
        /// </summary>
        public static void UpdateUserSession(HttpContextBase context, LiveLoginResult loginResult, string requestTs)
        {
            if (context == null)
            {
                return;
            }

            Debug.Assert(loginResult != null);

            Dictionary <string, string> cookieValues = new Dictionary <string, string>();
            HttpCookie cookie    = context.Request.Cookies[AuthCookie];
            HttpCookie newCookie = new HttpCookie(AuthCookie);

            newCookie.Path = "/";
            string host = context.Request.Headers["Host"];

            newCookie.Domain = host.Split(':')[0];

            if (cookie != null && cookie.Values != null)
            {
                foreach (string key in cookie.Values.AllKeys)
                {
                    newCookie.Values[key] = cookie[key];
                }
            }

            LiveConnectSession session = loginResult.Session;

            if (session != null)
            {
                newCookie.Values[AuthConstants.AccessToken]         = Uri.EscapeDataString(session.AccessToken);
                newCookie.Values[AuthConstants.AuthenticationToken] = Uri.EscapeDataString(session.AuthenticationToken);
                newCookie.Values[AuthConstants.Scope]     = Uri.EscapeDataString(LiveAuthUtility.BuildScopeString(session.Scopes));
                newCookie.Values[AuthConstants.ExpiresIn] = Uri.EscapeDataString(LiveAuthWebUtility.GetExpiresInString(session.Expires));
                newCookie.Values[AuthConstants.Expires]   = Uri.EscapeDataString(LiveAuthWebUtility.GetExpiresString(session.Expires));
            }

            LiveConnectSessionStatus status;

            if (!string.IsNullOrEmpty(newCookie[AuthConstants.AccessToken]))
            {
                // We have an access token, so it is connected, regardless expired or not
                // since it is handled after loading the session in both Asp.Net and JS library.
                status = LiveConnectSessionStatus.Connected;
            }
            else
            {
                status = loginResult.Status;
                if (loginResult.Status == LiveConnectSessionStatus.Unknown)
                {
                    // If we recorded NotConnected previously, keep it.
                    LiveConnectSessionStatus statusFromCookie;
                    if (Enum.TryParse <LiveConnectSessionStatus>(
                            newCookie[AuthConstants.Status],
                            true /*ignore case*/,
                            out statusFromCookie))
                    {
                        if (statusFromCookie == LiveConnectSessionStatus.NotConnected)
                        {
                            status = statusFromCookie;
                        }
                    }
                }
            }

            newCookie.Values[AuthConstants.Status] = GetStatusString(status);

            // Needs to write error to inform the JS library.
            LiveAuthException authError = loginResult.Error as LiveAuthException;

            if (authError != null)
            {
                newCookie.Values[AuthConstants.Error]            = Uri.EscapeDataString(authError.ErrorCode);
                newCookie.Values[AuthConstants.ErrorDescription] = HttpUtility.UrlPathEncode(authError.Message);
            }
            else if (status != LiveConnectSessionStatus.Connected)
            {
                newCookie.Values[AuthConstants.Error]            = Uri.EscapeDataString(AuthErrorCodes.AccessDenied);
                newCookie.Values[AuthConstants.ErrorDescription] = HttpUtility.UrlPathEncode("Cannot retrieve access token.");
            }

            if (!string.IsNullOrEmpty(requestTs))
            {
                newCookie.Values[AuthConstants.ClientRequestTs] = requestTs;
            }

            context.Response.Cookies.Add(newCookie);
        }
Exemple #30
0
 /// <summary>
 ///     Creates a new LiveLoginResult instance.
 /// </summary>
 public LiveLoginResult(LiveConnectSessionStatus status, LiveConnectSession session)
 {
     this.Status  = status;
     this.Session = session;
 }
 /// <summary>
 /// Save session to persistence store. N/A on Windows 8.
 /// </summary>
 public void SaveSession(LiveConnectSession session)
 {
     // No-op.
 }
 /// <summary>
 /// Save session to persistence store. N/A on Windows 8.
 /// </summary>
 public void SaveSession(LiveConnectSession session)
 {
     // No-op.
 }
Exemple #33
0
        private void TryRefreshToken(string redirectUrl)
        {
            Debug.Assert(this.loginStatus != null);

            IEnumerable <string> scopes;
            LiveAuthException    error;
            bool isTokenRequest = this.CheckRefreshTokenRequest(out scopes, out error);

            if (error != null)
            {
                this.OnAuthTaskCompleted(new LiveLoginResult(error));
                return;
            }

            // Try to refresh a token if
            // i) there is a token request or
            // ii) we don't have a token or
            // iii) the current token is expired.
            LiveLoginResult    result  = null;
            LiveConnectSession session = this.loginStatus.Session;
            bool hasValidToken         = session != null && session.IsValid;
            bool shouldRefresh         = (this.refreshTokenHandler != null) && (isTokenRequest || !hasValidToken);

            if (!shouldRefresh)
            {
                this.OnAuthTaskCompleted(null);
                return;
            }

            if (this.initScopes == null)
            {
                // We don't have initScopes, then use the scopes received from Url.
                this.initScopes = scopes;
            }

            this.refreshTokenHandler.RetrieveRefreshTokenAsync().ContinueWith(t =>
            {
                try
                {
                    this.refreshTokenInfo = t.Result;
                    if (this.refreshTokenInfo != null)
                    {
                        string currentUserId = this.publicAuthClient.CurrentUserId;
                        if (currentUserId != null && this.refreshTokenInfo.UserId != currentUserId)
                        {
                            // There is a user Id available in current session. We need to ensure the token provided matches it.
                            result = new LiveLoginResult(new LiveAuthException(
                                                             AuthErrorCodes.InvalidRequest, ErrorText.RefereshTokenNotMatchUserId));
                        }
                        else
                        {
                            LiveAuthRequestUtility.RefreshTokenAsync(
                                this.clientId,
                                this.clientSecret,
                                redirectUrl,
                                this.refreshTokenInfo.RefreshToken,
                                null/*scopes -  We intentially specify null scopes and validate the initScopes after we have the session
                                     * result. With this approach, we can return notConnected if initScopes is not satisfied, and surface
                                     * the error if there is one.
                                     */
                                ).ContinueWith((Task <LiveLoginResult> rt) =>
                            {
                                result = rt.Result;
                                this.OnAuthTaskCompleted(result);
                            });
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    error  = new LiveAuthException(AuthErrorCodes.ClientError, ErrorText.RetrieveRefreshTokenError, ex);
                    result = new LiveLoginResult(error);
                }

                this.OnAuthTaskCompleted(result);
            });
        }
        /// <summary>
        /// Authenticate the user.  Ask user for consent if neccessary.
        /// </summary>
        public async Task <LiveLoginResult> AuthenticateAsync(string scopes, bool silent)
        {
            Exception error               = null;
            string    accessToken         = null;
            string    authenticationToken = null;

            LiveLoginResult result = null;

            try
            {
                accessToken = await this.GetAccessToken(scopes, silent);

                LiveConnectSession session = new LiveConnectSession(this.authClient);
                session.AccessToken = accessToken;

                if (!string.IsNullOrEmpty(this.authClient.RedirectUrl) &&
                    !this.authClient.RedirectUrl.StartsWith(Win8AppIdPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    authenticationToken = await this.GetAuthenticationToken(this.authClient.RedirectUrl, silent);

                    session.AuthenticationToken = authenticationToken;
                }

                result = new LiveLoginResult(LiveConnectSessionStatus.Connected, session);
            }
            catch (TaskCanceledException)
            {
                result = new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null);
            }
            catch (Exception comExp)
            {
                switch (comExp.HResult)
                {
                case TailoredAuthClient.UserNotFoundLoginExceptionHResult:
                    result = new LiveLoginResult(LiveConnectSessionStatus.Unknown, null);
                    break;

                case TailoredAuthClient.ConsentNotGrantedExceptionHResult:
                    result = new LiveLoginResult(LiveConnectSessionStatus.NotConnected, null);
                    break;

                case TailoredAuthClient.InvalidClientExceptionHResult:
                case TailoredAuthClient.InvalidAuthTargetExceptionHResult:
                    error = new LiveAuthException(AuthErrorCodes.InvalidRequest, ResourceHelper.GetString("InvalidAuthClient"), comExp);
                    break;

                default:
                    error = new LiveAuthException(AuthErrorCodes.ServerError, ResourceHelper.GetString("ServerError"), comExp);
                    break;
                }
            }

            if (result == null)
            {
                Debug.Assert(error != null);

                result = new LiveLoginResult(error);
            }

            return(result);
        }
        // Authenticate the user via Microsoft Account (the default on Windows Phone)
        // Authentication via Facebook, Twitter or Google ID will be added in a future release.
        private async Task Authenticate()
        {
            prgBusy.IsActive = true;
            Exception exception = null;

            try
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    TextUserName.Text = "Please wait while we log you in...";
                });

                LiveAuthClient liveIdClient = new LiveAuthClient(ConfigSecrets.AzureMobileServicesURI);

                while (session == null)
                {
                    // Force a logout to make it easier to test with multiple Microsoft Accounts
                    // This code should be commented for the release build
                    //if (liveIdClient.CanLogout)
                    //    liveIdClient.Logout();

                    // Microsoft Account Login
                    LiveLoginResult result = await liveIdClient.LoginAsync(new[] { "wl.basic" });
                    if (result.Status == LiveConnectSessionStatus.Connected)
                    {
                        session = result.Session;
                        LiveConnectClient client = new LiveConnectClient(result.Session);
                        LiveOperationResult meResult = await client.GetAsync("me");
                        user = await App.MobileService
                            .LoginWithMicrosoftAccountAsync(result.Session.AuthenticationToken);

                        userfirstname = meResult.Result["first_name"].ToString();
                        userlastname = meResult.Result["last_name"].ToString();

                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            var message = string.Format("Logged in as {0} {1}", userfirstname, userlastname);
                            TextUserName.Text = message;
                        });

                        // Debugging dialog, make sure it's commented for publishing
                        //var dialog = new MessageDialog(message, "Welcome!");
                        //dialog.Commands.Add(new UICommand("OK"));
                        //await dialog.ShowAsync();
                        isLoggedin = true;
                        SetUIState(true);
                    }
                    else
                    {
                        session = null;
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            UpdateStatus("You must log in before you can chat in this app.", true);
                            var dialog = new MessageDialog("You must log in.", "Login Required");
                            dialog.Commands.Add(new UICommand("OK"));
                            dialog.ShowAsync();
                        });
                    }
                }

            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null)
            {
                UpdateStatus("Something went wrong when trying to log you in.", true);
                string msg1 = "An error has occurred while trying to sign you in." + Environment.NewLine + Environment.NewLine;

                // TO DO: Dissect the various potential errors and provide a more appropriate
                //        error message in msg2 for each of them.
                string msg2 = "Make sure that you have an active Internet connection and try again.";

                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    new MessageDialog(msg1 + msg2, "Authentication Error").ShowAsync();
                });
            }
            prgBusy.IsActive = false;
        }