Example #1
0
        /// <summary>
        /// Download a file into a stream.
        /// </summary>
        /// <param name="path">relative or absolute uri to the file to be downloaded.</param>
        /// <param name="ct">a cancellation token</param>
        /// <param name="progress">a progress event callback handler</param>
        public Task <LiveDownloadOperationResult> DownloadAsync(
            string path,
            CancellationToken ct,
            IProgress <LiveOperationProgress> progress)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path");

            var tcs = new TaskCompletionSource <LiveDownloadOperationResult>();
            var op  = new DownloadOperation(
                this,
                this.GetResourceUri(path, ApiMethod.Download),
                progress,
                null);

            op.OperationCompletedCallback = (LiveDownloadOperationResult result) =>
            {
                if (result.IsCancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (result.Error != null)
                {
                    tcs.TrySetException(result.Error);
                }
                else
                {
                    tcs.TrySetResult(result);
                }
            };

            ct.Register(op.Cancel);
            op.Execute();

            return(tcs.Task);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the RefreshTokenInfo class.
        /// </summary>
        /// <param name="refreshToken">The refresh token value.</param>
        /// <param name="userId">The user ID associated with the token.</param>
        public RefreshTokenInfo(string refreshToken, string userId)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(refreshToken, "refreshToken");
            LiveUtility.ValidateNotNullOrWhiteSpaceString(userId, "userId");

            this.RefreshToken = refreshToken;
            this.UserId       = userId;
        }
Example #3
0
        /// <summary>
        /// Upload a file to the server.
        /// </summary>
        /// <param name="path">relative or absolute uri to the location where the file should be uploaded to.</param>
        /// <param name="fileName">name for the uploaded file.</param>
        /// <param name="inputStream">Stream that contains the file content.</param>
        /// <param name="option">
        ///     a enum to specify the overwrite behavior if a file with the same name already exists.
        ///     Default is DoNotOverwrite.
        /// </param>
        /// <param name="ct">a cancellation token</param>
        /// <param name="progress">a progress event callback handler</param>
        public Task <LiveOperationResult> UploadAsync(
            string path,
            string fileName,
            Stream inputStream,
            OverwriteOption option,
            CancellationToken ct,
            IProgress <LiveOperationProgress> progress)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(path, "path");
            LiveUtility.ValidateNotNullParameter(inputStream, "inputStream");

            if (string.IsNullOrEmpty(fileName))
            {
                string message = String.Format(CultureInfo.CurrentUICulture,
                                               ResourceHelper.GetString("InvalidNullOrEmptyParameter"),
                                               "fileName");
                throw new ArgumentException(message, "fileName");
            }

            if (!inputStream.CanRead)
            {
                string message = String.Format(CultureInfo.CurrentUICulture,
                                               ResourceHelper.GetString("StreamNotReadable"),
                                               "inputStream");
                throw new ArgumentException(message, "inputStream");
            }

            var tcs = new TaskCompletionSource <LiveOperationResult>();
            var op  = new UploadOperation(
                this,
                this.GetResourceUri(path, ApiMethod.Upload),
                fileName,
                inputStream,
                option,
                progress,
                null);

            op.OperationCompletedCallback = (LiveOperationResult result) =>
            {
                if (result.IsCancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (result.Error != null)
                {
                    tcs.TrySetException(result.Error);
                }
                else
                {
                    tcs.TrySetResult(result);
                }
            };

            ct.Register(op.Cancel);
            op.Execute();

            return(tcs.Task);
        }
Example #4
0
        /// <summary>
        /// Initializes an instance of LiveAuthClient class.
        /// </summary>
        /// <param name="clientId">The client Id of the app.</param>
        /// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
        public LiveAuthClient(
            string clientId,
            IRefreshTokenHandler refreshTokenHandler)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");

            this.authClient  = new LiveAuthClientCore(clientId, refreshTokenHandler, this);
            this.syncContext = SynchronizationContextWrapper.Current;
        }
Example #5
0
        /// <summary>
        /// Clear the auth state in the current session
        /// </summary>
        public void ClearSession(HttpContextBase context)
        {
            LiveUtility.ValidateNotNullParameter(context, "context");

            HttpContextUtility.ClearUserSession(context);
            this.loginStatus = null;
            this.publicAuthClient.Session = null;
            this.publicAuthClient.FirePendingPropertyChangedEvents();
        }
Example #6
0
        /// <summary>
        /// Generates a consent URL that includes a set of provided  parameters.
        /// </summary>
        /// <param name="scopes">A list of scope values that the user will need to authorize.</param>
        /// <param name="options">A table of optional authorization parameters to be encoded into the URL.</param>
        /// <returns>The generated login URL value.</returns>
        public string GetLoginUrl(IEnumerable <string> scopes, IDictionary <string, string> options)
        {
            LiveUtility.ValidateNotEmptyStringEnumeratorArguement(scopes, "scopes");

            string      locale      = null;
            string      state       = null;
            DisplayType display     = DisplayType.WinDesktop;
            ThemeType   theme       = ThemeType.Win7;
            string      redirectUrl = LiveAuthUtility.BuildDesktopRedirectUrl();

            if (options != null)
            {
                if (options.ContainsKey(AuthConstants.Locale))
                {
                    locale = options[AuthConstants.Locale];
                }

                if (options.ContainsKey(AuthConstants.ClientState))
                {
                    state = options[AuthConstants.ClientState];
                }

                if (options.ContainsKey(AuthConstants.Display))
                {
                    string displayStr = options[AuthConstants.Display];
                    if (!Enum.TryParse <DisplayType>(displayStr, true, out display))
                    {
                        throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "display");
                    }
                }

                if (options.ContainsKey(AuthConstants.Theme))
                {
                    string themeStr = options[AuthConstants.Theme];
                    if (!Enum.TryParse <ThemeType>(themeStr, true, out theme))
                    {
                        throw new ArgumentException(ErrorText.ParameterInvalidDisplayValue, "theme");
                    }
                }
            }

            if (locale == null)
            {
                locale = CultureInfo.CurrentUICulture.ToString();
            }

            return(this.authClient.GetLoginUrl(scopes, redirectUrl, display, theme, locale, state));
        }
Example #7
0
        /// <summary>
        /// Initializes an instance of LiveAuthClient class.
        /// </summary>
        /// <param name="clientId">The client Id of the app.</param>
        /// <param name="clientSecret">The client secret of the app.</param>
        /// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
        /// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
        public LiveAuthClient(
            string clientId,
            string clientSecret,
            string defaultRedirectUrl,
            IRefreshTokenHandler refreshTokenHandler)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
            LiveUtility.ValidateNotNullOrWhiteSpaceString(clientSecret, "clientSecret");
            if (!string.IsNullOrWhiteSpace(defaultRedirectUrl))
            {
                LiveUtility.ValidateUrl(defaultRedirectUrl, "defaultRedirectUrl");
                this.defaultRedirectUrl = defaultRedirectUrl;
            }

            this.authClient = new LiveAuthClientCore(clientId, clientSecret, refreshTokenHandler, this);
        }
Example #8
0
        /// <summary>
        /// Decrypts the user ID from a given authentication token.
        /// </summary>
        /// <returns>The user ID string value</returns>
        public string GetUserId(string authenticationToken)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(authenticationToken, "authenticationToken");

            string            userId;
            LiveAuthException error;

            if (this.authClient.GetUserId(authenticationToken, out userId, out error))
            {
                return(userId);
            }
            else
            {
                throw error;
            }
        }
Example #9
0
        /// <summary>
        /// Initializes the LiveAuthClient instance for the current user.
        /// If an authorization code is present, it will send a request to the auth server to exchange the token.
        /// If there is an auth session in current context, it will retrieve the current auth session.
        /// If the current session is expired or the current request url indicates (refresh=1) to get a new token,
        /// it will try to request a new access token using refresh token that will need to be provided through
        /// IRefreshTokenHandler.RetrieveRefreshTokenAsync() method.
        /// Any updated session state will be saved in the auth session cookie.
        /// </summary>
        /// <param name="context">The HttpContextBase instance of current request.</param>
        /// <param name="redirectUrl">The redirect URL of the app. This must match exactly the Url that is used to
        /// generate the login Url via LiveAuthClient.GetLoginUrl</param>
        /// <param name="scopes">A list of scopes to validate whether the user has consented. If the available session
        /// does not satisfy the specified scopes, NotConnected status will be returned. However, the developer still
        /// can find the available session throw the Session property.</param>
        /// <returns>An async Task instance</returns>
        public Task <LiveLoginResult> InitializeWebSessionAsync(
            HttpContextBase context,
            string redirectUrl,
            IEnumerable <string> scopes)
        {
            LiveUtility.ValidateNotNullParameter(context, "context");
            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = LiveAuthUtility.GetCurrentRedirectUrl(context.Request.Url);
            }
            else
            {
                LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
            }

            return(this.authClient.InitializeWebSessionAsync(redirectUrl, context, scopes));
        }
Example #10
0
        /// <summary>
        /// Exchange authentication code for access token.
        /// </summary>
        /// <param name="context">The HttpContextBase instance</param>
        /// <param name="redirectUri">The redirect URL of the app.</param>
        /// <returns>An async Task instance.</returns>
        public Task <LiveLoginResult> ExchangeAuthCodeAsync(
            HttpContextBase context,
            string redirectUrl)
        {
            LiveUtility.ValidateNotNullParameter(context, "context");

            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = LiveAuthUtility.GetCurrentRedirectUrl(context.Request.Url);
            }
            else
            {
                LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");
            }

            return(this.authClient.ExchangeAuthCodeAsync(redirectUrl, context));
        }
Example #11
0
        /// <summary>
        /// Initializes an instance of LiveAuthClient class.
        /// To address security concerns, developers may wish to change their client secret. This constructor allows
        /// the developer to pass in a client secret map to handle the client secret change and ensure a graceful experience
        /// during the change rollover. You can create a new secret for your app on the developer portal (https://account.live.com/developers/applications)
        /// site. Once a new secret is created, the site will indicate the version of each secret, new and old.
        /// For example, the old secret and new secret may be shown as v0 and v1 on the developer portal site.
        /// Before the new secret is activated, both secrets are accepted by the Microsoft authentication server. You should update your
        /// code to provide the secret map when intializing a LiveAuthClient instance. This will ensure that the new secret
        /// will be used when communicating with the Microsoft authentication server, and the LiveAuthClient instance will use the correct version of
        /// the client secret to validate authentication tokens that may be signed by either old or new versions of client secret.
        /// Once you activate the new secret on the developer portal site, the old secret will no longer be accepted by the Microsoft
        /// authentication server, however, you may still want to keep the old secret in the map for one day, so that
        /// clients with authentication tokens signed with the old secret will continue to work.
        /// </summary>
        /// <param name="clientId">The client Id of the app.</param>
        /// <param name="clientSecretMap">The client secret map of the app.</param>
        /// <param name="defaultRedirectUrl">The default redirect URL for the site.</param>
        /// <param name="refreshTokenHandler">An IRefreshTokenHandler instance to handle refresh token persistency and retrieval.</param>
        public LiveAuthClient(
            string clientId,
            IDictionary <int, string> clientSecretMap,
            string defaultRedirectUrl,
            IRefreshTokenHandler refreshTokenHandler)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(clientId, "clientId");
            LiveUtility.ValidateNotNullParameter(clientSecretMap, "clientSecretMap");
            if (clientSecretMap.Count == 0)
            {
                throw new ArgumentException("Client secret must be provided.", "clientSecretMap");
            }

            if (!string.IsNullOrWhiteSpace(defaultRedirectUrl))
            {
                LiveUtility.ValidateUrl(defaultRedirectUrl, "defaultRedirectUrl");
                this.defaultRedirectUrl = defaultRedirectUrl;
            }

            this.authClient = new LiveAuthClientCore(clientId, clientSecretMap, refreshTokenHandler, this);
        }
Example #12
0
        /// <summary>
        /// Gets the logout URL.
        /// </summary>
        /// <param name="redirectUri">The URL that the page will be redirected to after logout is completed.</param>
        /// <returns>The logout URL.</returns>
        public string GetLogoutUrl(string redirectUrl)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(redirectUrl, "redirectUrl");

            return(this.authClient.GetLogoutUrl(redirectUrl));
        }
Example #13
0
        /// <summary>
        /// Clear the auth state in the current session
        /// </summary>
        /// <param name="context">Optional</param>
        public void ClearSession(HttpContextBase context)
        {
            LiveUtility.ValidateNotNullParameter(context, "context");

            this.authClient.ClearSession(context);
        }
Example #14
0
        /// <summary>
        /// Initializes the LiveAuthClient instance.
        /// This will trigger retrieving token with refresh token process.
        /// </summary>
        /// <param name="redirectUri">The redirect URL of the app.</param>
        /// <param name="scopes">A list of scopes to validate whether the user has consented.</param>
        /// <returns>An async Task instance.</returns>
        public Task <LiveLoginResult> InitializeSessionAsync(string redirectUrl, IEnumerable <string> scopes)
        {
            LiveUtility.ValidateUrl(redirectUrl, "redirectUrl");

            return(this.authClient.InitializeSessionAsync(redirectUrl, scopes));
        }
Example #15
0
//#if WEB
//        /// <summary>
//        /// Initializes a new instance of the RefreshTokenInfo class.
//        /// </summary>
//        /// <param name="refreshToken">The refresh token value.</param>
//        /// <param name="userId">The user ID associated with the token.</param>
//        public RefreshTokenInfo(string refreshToken, string userId)
//        {
//            LiveUtility.ValidateNotNullOrWhiteSpaceString(refreshToken, "refreshToken");
//            LiveUtility.ValidateNotNullOrWhiteSpaceString(userId, "userId");

//            this.RefreshToken = refreshToken;
//            this.UserId = userId;
//        }
//#elif DESKTOP
        /// <summary>
        /// Initializes a new instance of the RefreshTokenInfo class.
        /// </summary>
        /// <param name="refreshToken">The refresh token value.</param>
        public RefreshTokenInfo(string refreshToken)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(refreshToken, "refreshToken");

            this.RefreshToken = refreshToken;
        }
Example #16
0
 /// <summary>
 /// Initializes the LiveAuthClient instance.
 /// This will trigger retrieving token with refresh token process if the app provides the refresh token via
 /// IRefreshTokenHandler.RetrieveRefreshTokenAsync method.
 /// </summary>
 /// <param name="scopes">The list of offers that the application is requesting user to consent for.</param>
 /// <returns>An async Task instance.</returns>
 public Task <LiveLoginResult> InitializeAsync(IEnumerable <string> scopes)
 {
     LiveUtility.ValidateNotNullParameter(scopes, "scopes");
     return(this.authClient.InitializeAsync(scopes));
 }
Example #17
0
        /// <summary>
        /// Exchange authentication code for access token.
        /// </summary>
        /// <param name="AuthenticationCode">The authentication code the app received from Microsoft authorization
        /// server during the user authorization process.</param>
        /// <returns></returns>
        public Task <LiveConnectSession> ExchangeAuthCodeAsync(string authenticationCode)
        {
            LiveUtility.ValidateNotNullOrWhiteSpaceString(authenticationCode, "authenticationCode");

            return(this.authClient.ExchangeAuthCodeAsync(authenticationCode));
        }