Inheritance: IWebAuthenticationResult
        public async Task ParseAuthenticationResult(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
                //connection error
                case WebAuthenticationStatus.ErrorHttp:
                    Debug.WriteLine("Connection error");
                    break;
                //authentication successfull
                case WebAuthenticationStatus.Success:
                    var pattern = string.Format("{0}#access_token={1}&expires_in={2}",
                        WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)",
                        "(?<expires_in>.+)");
                    var match = Regex.Match(result.ResponseData, pattern);

                    var access_token = match.Groups["access_token"];
                    var expires_in = match.Groups["expires_in"];

                    AccessToken = access_token.Value;
                    TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));

                    await ShowUserInfo();

                    InviteFriends.Visibility = Visibility.Visible;

                    break;
                //operation aborted by the user
                case WebAuthenticationStatus.UserCancel:
                    Debug.WriteLine("Operation aborted");
                    break;
                default:
                    break;
            }

        }
Ejemplo n.º 2
0
		static WebAuthenticationResult()
		{
			UserCancel = new WebAuthenticationResult
			{
				ResponseStatus = WebAuthenticationStatus.UserCancel
			};
		}
        public void AuthenticationComplete(WebAuthenticationResult result)
        {
            if (pendingLoginTask == null)
            {
                throw new InvalidOperationException(Resources.IAuthenticationBroker_NoLoginInProgress);
            }

            if (result.ResponseStatus != WebAuthenticationStatus.Success)
            {
                string message;
                if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                {
                    message = Resources.IAuthenticationBroker_AuthenticationCanceled;
                }
                else
                {
                    message = string.Format(CultureInfo.InvariantCulture,
                                            Resources.IAuthenticationBroker_AuthenticationFailed,
                                            result.ResponseErrorDetail);
                }
                pendingLoginTask.SetException(new InvalidOperationException(message));                
            }
            else
            {
                string tokenString = GetTokenStringFromResult(result);
                pendingLoginTask.SetResult(tokenString);
            }

            pendingLoginTask = null;            
        }
        public void AuthenticationComplete(WebAuthenticationResult result)
        {
            if (pendingLoginTask == null)
            {
                throw new InvalidOperationException("Authentication has not been started.");
            }

            if (result.ResponseStatus != WebAuthenticationStatus.Success)
            {
                string message;
                if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                {
                    message = "Authentication was cancelled by the user.";
                }
                else
                {
                    message = string.Format(CultureInfo.InvariantCulture,
                                            "Authentication failed with HTTP response code {0}.",
                                            result.ResponseErrorDetail);
                }
                pendingLoginTask.SetException(new InvalidOperationException(message));                
            }
            else
            {
                string tokenString = GetTokenStringFromResult(result);
                pendingLoginTask.SetResult(tokenString);
            }

            pendingLoginTask = null;            
        }
 void browserControl_NavigationFailed(object sender, NavigationFailedEventArgs e)
 {
     WebBrowserNavigationException ex = e.Exception as WebBrowserNavigationException;
     uint error = ex != null ? (uint)ex.StatusCode : 0u;
     WebAuthenticationResult result = new WebAuthenticationResult("", WebAuthenticationStatus.ErrorHttp, error);
     WebAuthenticationResultSource.TrySetResult(result);
     e.Handled = true;
 }
Ejemplo n.º 6
0
 public static string GetVerificationToken(WebAuthenticationResult result)
 {
     var url = result.ResponseData;
     var uri = new Uri(url);
     var query = uri.QueryDictionary();
     var verification = query["oauth_verifier"];
     return verification;
 }
 void browserControl_Navigating(object sender, NavigatingEventArgs e)
 {
     if (IsEndUri(e.Uri))
     {
         WebAuthenticationResult result = new WebAuthenticationResult(e.Uri.AbsoluteUri, WebAuthenticationStatus.Success, 0u);
         WebAuthenticationResultSource.TrySetResult(result); 
     }
 }
		public void ContinueWebAuthentication(WebAuthenticationResult results)
		{
			try
			{
				WebAuthenticationResult result = results;
				var tcs = _tcs;
				_tcs = null;
				tcs.SetResult(DecodeParameters(new Uri(result.ResponseData)));
			}
			catch (Exception ex)
			{
				throw (ex);
			}
		}
    public string ParseAuthenticationResult(FacebookClient fb, WebAuthenticationResult result)
    {
      switch (result.ResponseStatus)
      {
        case WebAuthenticationStatus.ErrorHttp:
          return "Error";
        case WebAuthenticationStatus.Success:

          var oAuthResult = fb.ParseOAuthCallbackUrl(new Uri(result.ResponseData));
          return oAuthResult.AccessToken;
        case WebAuthenticationStatus.UserCancel:
          return "Operation aborted";
      }
      return null;
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Processes the result.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <exception cref="UniversalDemo.OAuthException">
        /// Raised if there was an HTTP error during the authentication process.
        /// </exception>
        /// <exception cref="UniversalDemo.OAuthUserCancelledException">
        /// Raised if the user cancelled authentication.
        /// </exception>
        private static void ProcessResult(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    var response = DropboxOAuth2Helper.ParseTokenFragment(
                        new Uri(result.ResponseData));
                    ((App)Application.Current).AccessToken = response.AccessToken;
                    break;

                case WebAuthenticationStatus.ErrorHttp:
                    throw new OAuthException(result.ResponseErrorDetail);

                case WebAuthenticationStatus.UserCancel:
                default:
                    throw new OAuthUserCancelledException();
            }
        }
Ejemplo n.º 11
0
        public static async Task<string> RetrieveToken(WebAuthenticationResult result, string oauthKey, string oauthSecret)
        {
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                string code = GetCode(result.ResponseData);
                return await GetToken(code, oauthKey, oauthSecret);
            }
            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new ApiAuthException(WebAuthenticationStatus.ErrorHttp);
            }
            if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new ApiAuthException(WebAuthenticationStatus.UserCancel);
            }

            return null;
        }
Ejemplo n.º 12
0
        private void ValidateAndProccessResult(WebAuthenticationResult result)
        {
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(result.ResponseData);
                var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(responseUri);

                if (string.IsNullOrWhiteSpace(facebookOAuthResult.Error))
                    _fb.AccessToken = facebookOAuthResult.AccessToken;
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
            // error de http
            }
            else
            {
                _fb.AccessToken = null; //Keep null when user signout from facebook
            }
        }
        private void ValidateAndProccessResult(WebAuthenticationResult result)
        {
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(result.ResponseData.ToString());
                var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(responseUri);

                if (string.IsNullOrWhiteSpace(facebookOAuthResult.Error))
                    _fb.AccessToken = facebookOAuthResult.AccessToken;
                else
                {//error de acceso denegado por cancelación en página
                }
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {// error de http
            }
            else
            {// otras condiciones de error
            }
        }
Ejemplo n.º 14
0
        public static void SetAuthorizationResultUri(WebAuthenticationResult webAuthenticationResult)
        {
            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.Success, webAuthenticationResult.ResponseData);
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.ErrorHttp, null);
                    break;
                case WebAuthenticationStatus.UserCancel:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.UserCancel, null);
                    break;
                default:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.UnknownError, null);
                    break;
            }

            returnedUriReady.Release();
        }
        private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult, CallState callState)
        {
            AuthorizationResult result;
            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = OAuth2Response.ParseAuthorizeResponse(webAuthenticationResult.ResponseData, callState);
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = new AuthorizationResult(AdalError.AuthenticationFailed, webAuthenticationResult.ResponseErrorDetail.ToString());
                    break;
                case WebAuthenticationStatus.UserCancel:
                    result = new AuthorizationResult(AdalError.AuthenticationCanceled, AdalErrorMessage.AuthenticationCanceled);
                    break;
                default:
                    result = new AuthorizationResult(AdalError.AuthenticationFailed, AdalErrorMessage.AuthorizationServerInvalidResponse);
                    break;
            }

            return result;
        }
        private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult, CallState callState)
        {
            AuthorizationResult result;
            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = new AuthorizationResult(AuthorizationStatus.Success, webAuthenticationResult.ResponseData);
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = new AuthorizationResult(AuthorizationStatus.ErrorHttp, webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture));
                    break;
                case WebAuthenticationStatus.UserCancel:
                    result = new AuthorizationResult(AuthorizationStatus.UserCancel, null);
                    break;
                default:
                    result = new AuthorizationResult(AuthorizationStatus.UnknownError, null);
                    break;
            }

            return result;
        }
Ejemplo n.º 17
0
        public async Task ContinueAuthorizationAsync(WebAuthenticationResult result)
        {
            if (null == result || result.ResponseStatus != WebAuthenticationStatus.Success)
            {
                InfoMessage = _loader.GetString("AuthZ_OAuthFailed");
                return;
            }

            try
            {
                ShowAuthorizeButton = false;
                Working = true;
                InfoMessage = _loader.GetString("AuthZ_CompletingOAuthFlow_AcquiringAccessToken");

                bool ok = await _githubService.CompleteOAuthFlowAsync(result.ResponseData);

                if (ok)
                {
                    _navigationService
                        .UriFor<MainViewModel>()
                        .Navigate();
                }
                else
                {
                    InfoMessage = _loader.GetString("AuthZ_ObtainingAccessTokenFailed");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                ShowAuthorizeButton = true;
                Working = false;
            }
        }
 /// <summary>Constructs a new instance of the class and set its properties by the specified result.</summary>
 public SerializableWebAuthResult(WebAuthenticationResult result)
 {
     this.ResponseData = result.ResponseData;
     this.ResponseErrorDetail = result.ResponseErrorDetail;
     this.ResponseStatus = result.ResponseStatus;
 }
Ejemplo n.º 19
0
 public void ParseAuthenticationResult(WebAuthenticationResult result)
 {
     switch (result.ResponseStatus)
     {
         //connection error
         case WebAuthenticationStatus.ErrorHttp:
             _fcallback.loginFailed(SilverlightImplementation.toJava("Failed to connect."));
             break;
         //authentication successfull
         case WebAuthenticationStatus.Success:
             var oAuthResult = fb.ParseOAuthCallbackUrl(new Uri(result.ResponseData));
             com.codename1.io.Preferences.set(PREF_TOKEN, SilverlightImplementation.toJava(oAuthResult.AccessToken));
             com.codename1.io.Preferences.set(PREF_EXPIRES, oAuthResult.Expires.Ticks);
             _fcallback.loginSuccessful();
             break;
         //operation aborted by the user
         case WebAuthenticationStatus.UserCancel:
             _fcallback.loginFailed(SilverlightImplementation.toJava("Operation aborted"));
             break;
         default:
             break;
     }
 }
        private async Task<Session> GetSession(WebAuthenticationResult result)
        {
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var code = GetCode(result.ResponseData);
                var serviceRequest = await GetToken(code);

                return new Session
                {
                    AccessToken = serviceRequest.access_token,
                    ExpireDate = new DateTime(long.Parse(serviceRequest.expires_in)),
                    Id = serviceRequest.id_token,
                    Provider = Constants.GoogleProvider
                };
            }
            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new Exception("Error http");
            }
            if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new Exception("User Canceled.");
            }
            return null;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Finishes the login process asynchronously.
        /// </summary>
        /// <param name="webAuthenticationResult">The web authentication result.</param>
        private async Task FinishLoginAsync(WebAuthenticationResult webAuthenticationResult)
        {
            if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                this._exceptionHandler.Handle(new Exception(webAuthenticationResult.ResponseData));
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                LogTo.Debug("User cancelled the login.");
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(webAuthenticationResult.ResponseData);
                var decoder = new WwwFormUrlDecoder(responseUri.Query);

                string accessToken = decoder.GetFirstValueByName("code");

                var client = this.GetClient();

                await client.Core.OAuth2.TokenAsync(accessToken);

                AccountInfo dropboxUserInfo = await client.Core.Accounts.AccountInfoAsync();
                this._sessionService.UserLoggedIn(client.UserAccessToken, dropboxUserInfo.uid);

                await this._eventAggregator.PublishOnUIThreadAsync(new UserLoggedInEvent());
            }
        }
Ejemplo n.º 22
0
        private Session GetSession(WebAuthenticationResult result)
        {
            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                string accessToken;
                string expiresIn;
                GetKeyValues(result.ResponseData, out accessToken, out expiresIn);

                return new Session
                {
                    AccessToken = accessToken,
                    ExpireDate = new DateTime(long.Parse(expiresIn)),
                    Provider = Constants.FacebookProvider
                };
            }
            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new Exception("Error http");
            }
            if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new Exception("User Canceled.");
            }
            return null;
        }
 void LoginPage_BackKeyPress(object sender, global::System.ComponentModel.CancelEventArgs e)
 {
     WebAuthenticationResult result = new WebAuthenticationResult("", WebAuthenticationStatus.UserCancel, 0u);
     WebAuthenticationResultSource.TrySetResult(result);
 }
Ejemplo n.º 24
0
 public AuthResult(WebAuthenticationResult result)
 {
     Status = result.ResponseStatus;
     ResponseUri = result.ResponseData;
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Manages the result of the authentication operation
        /// </summary>
        /// <param name="webAuthenticationResult">result of the authentication operation</param>
        public async Task ManageAuthenticateResult(WebAuthenticationResult webAuthenticationResult)
        {
            if (webAuthenticationResult.ResponseStatus != WebAuthenticationStatus.Success)
            {
                throw new UnauthorizedAccessException();
            }
            var responseData = webAuthenticationResult.ResponseData.Substring(GetCallbackUrl().Length + 1).Split('&');
            var keyValuePairs = new Dictionary<string, string>();
            foreach (var str in responseData)
            {
                var keyValue = str.Split('=');
                keyValuePairs.Add(keyValue[0], keyValue[1]);
            }
            if (keyValuePairs["action"] != "allow" || keyValuePairs["state"] != "iloverd")
            {
                throw new UnauthorizedAccessException();
            }

            await UpdateTokens(keyValuePairs["code"], "authorization_code");
        }
Ejemplo n.º 26
0
        public void ParseAuthenticationResult(WebAuthenticationResult result)
        {
            switch (result.ResponseStatus)
            {
                case WebAuthenticationStatus.ErrorHttp:
                    //Debug.WriteLine("Error");
                    break;
                case WebAuthenticationStatus.Success:
                    var pattern = string.Format("{0}#access_token={1}&expires_in={2}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)", "(?<expires_in>.+)");
                    var match = Regex.Match(result.ResponseData, pattern);

                    var access_token = match.Groups["access_token"];
                    var expires_in = match.Groups["expires_in"];

                    _accessToken = access_token.Value;
                    _tokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value));
                    
                    var dm = new PassportDataModel();
                    dm.Token = _accessToken;
                    dm.TokenExpiry = _tokenExpiry;
                    //dm.TokenSecret = AccessToken.TokenSecret;
                    //dm.Verifier = xoauth_verifier;
                    dm.PassType = GroupingType;
                    //dm.UserId = AccessToken.UserId;
                    //dm.UserName = AccessToken.Username;
                    //dm.FullName = AccessToken.FullName;
                    //dm.ScreenName = AccessToken.ScreenName;

                    dm.APIKeyFKID = apiKey.Id;
                    
                    StorageService.Instance.Storage.Insert(dm);
                    
                    IsLoggedInVisible = Visibility.Visible;
                    IsLoginVisible = Visibility.Collapsed;
                    IsAPIEditorVisible = Visibility.Collapsed;
                    
                    break;
                case WebAuthenticationStatus.UserCancel:
                    //Debug.WriteLine("Operation aborted");
                    break;
                default:
                    break;
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Continues the authenticate user flow by extracting results from the Windows-specific
        /// auth method and moving on to the final common step.
        /// </summary>
        /// <param name="authResult">The result from the WebAuthenticationBroker call.</param>
        /// <returns>
        /// Whether the token was retrieved
        /// </returns>
        internal async Task<Response<AuthResultCode>> ConvertAuthPermissionParams(WebAuthenticationResult authResult)
        {
            try
            {
                switch (authResult.ResponseStatus)
                {
                    case WebAuthenticationStatus.Success:

                        // ResponseData will give us the final URI with a Querystring containing an auth code or error details
                        // e.g. code=90e754fd-0a4a-4eb5-b5f6-25dad9face6a or error=access_denied
                        AuthResultCode resultCode = AuthResultCode.Unknown;
                        string authorizationCode = null;

                        if (OAuthResultParser.ParseQuerystringForCompletedFlags(authResult.ResponseData, out resultCode, out authorizationCode))
                        {
                            // Move on to obtain a token
                            return await this.ObtainToken(authorizationCode, null, resultCode);
                        }
                        else
                        {
                            return new Response<AuthResultCode>(null, AuthResultCode.Unknown, Guid.Empty);
                        }

                    case WebAuthenticationStatus.ErrorHttp:
                        switch ((HttpStatusCode)authResult.ResponseErrorDetail)
                        {
                            case HttpStatusCode.BadRequest:
                                return new Response<AuthResultCode>(null, AuthResultCode.InvalidScope, Guid.Empty);

                            case HttpStatusCode.Unauthorized:
                                return new Response<AuthResultCode>(null, AuthResultCode.UnauthorizedClient, Guid.Empty);

                            case HttpStatusCode.InternalServerError:
                                return new Response<AuthResultCode>(null, AuthResultCode.ServerError, Guid.Empty);
                        }

                        // Any other items will return as cancelled below...
                        break;
                }
            }
            catch
            {
                // Usually means we got cancelled
            }

            return new Response<AuthResultCode>(null, AuthResultCode.Cancelled, Guid.Empty);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Completes the authenticate user call.
        /// </summary>
        /// <param name="client">The MixRadio client.</param>
        /// <param name="clientSecret">The client secret obtained during app registration</param>
        /// <param name="result">The result received through LaunchActivatedEventArgs.</param>
        /// <param name="cancellationToken">The cancellation token to cancel operation</param>
        /// <returns>
        /// An AuthResultCode indicating the result
        /// </returns>
        /// <remarks>This method is for Windows Phone 8.1 use</remarks>
        public static async Task<AuthResultCode> CompleteAuthenticateUserAsync(this MusicClient client, string clientSecret, WebAuthenticationResult result, CancellationToken? cancellationToken = null)
        {
            if (result != null)
            {
                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    var authResult = AuthResultCode.Unknown;
                    string code = null;

                    OAuthResultParser.ParseQuerystringForCompletedFlags(result.ResponseData, out authResult, out code);
                    if (authResult == AuthResultCode.Success)
                    {
                        var authToken = await client.GetAuthenticationTokenAsync(clientSecret, code, cancellationToken);
                        if (authToken != null)
                        {
                            await StoreOAuthToken(authToken, client.ClientId, clientSecret, cancellationToken).ConfigureAwait(false);
                        }
                    }

                    return authResult;
                }
            }

            return AuthResultCode.Unknown;
        }
        /// <summary>
        /// Gets the JSON string that represents the Mobile Service authentication token
        /// from the <see cref="WebAuthenticationResult"/>.
        /// </summary>
        /// <param name="result">The <see cref="WebAuthenticationResult"/> returned
        /// from the <see cref="WebAuthenticationBroker"/>.</param>
        /// <returns>
        /// A JSON string that represents a Mobile Service authentication token.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Thrown if the authentication flow resulted in an error message or an invalid response.
        /// </exception>
        private string GetTokenStringFromResult(WebAuthenticationResult result)
        {
            Debug.Assert(result != null);
            Debug.Assert(result.ResponseStatus == WebAuthenticationStatus.Success);

            string tokenString = null;

            string responseData = result.ResponseData;
            if (!string.IsNullOrEmpty(responseData))
            {
                tokenString = GetSubStringAfterMatch(responseData, "#token=");
            }

            if (string.IsNullOrEmpty(tokenString))
            {
                string message = null;
                string errorString = GetSubStringAfterMatch(responseData, "#error=");
                if (string.IsNullOrEmpty(errorString))
                {
                    message = "Invalid format of the authentication response.";
                }
                else
                {
                    message = string.Format(CultureInfo.InvariantCulture,
                                            "Login failed: {0}",
                                            errorString);
                }

                throw new InvalidOperationException(message);
            }

            return tokenString;
        }
Ejemplo n.º 30
0
 public AuthenticationEventArgs(WebAuthenticationResult result)
 {
     Result = result;
 }