public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
        {
            try
            {
                var callbackUrl = string.IsNullOrEmpty(_callbackUrl) ? options.EndUrl : _callbackUrl;
                WebAuthenticatorResult authResult =
                    // await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri(callbackUrl));
                    await WebAuthenticator.AuthenticateAsync(new WebAuthenticatorOptions
                {
                    Url         = new Uri(options.StartUrl),
                    CallbackUrl = new Uri(callbackUrl),
                    PrefersEphemeralWebBrowserSession = true
                });

                var authorizeResponse = ToRawIdentityUrl(options.EndUrl, authResult);

                return(new BrowserResult
                {
                    Response = authorizeResponse
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(new BrowserResult()
                {
                    ResultType = BrowserResultType.UnknownError,
                    Error = ex.ToString()
                });
            }
        }
Example #2
0
        public async Task Authenticate(string scheme)
        {
            // Check if the user is already authenticated
            if (IsAuthenticated())
            {
                throw new AuthenticationException();
            }

            Uri authUrl     = new Uri(string.Format(_authenticationUrl, scheme));
            Uri callbackUrl = new Uri(_callback);

            // Initiate browser based flow and wait until the callback is received
            WebAuthenticatorResult result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);

            // Check if the user cancels the flow at any point
            if (result == null)
            {
                throw new AuthenticationException();
            }

            // Store token informations in a key/value store
            Preferences.Set("access_token", result.Properties["access_token"]);
            Preferences.Set("refresh_token", result.Properties["refresh_token"]);
            Preferences.Set("provider", result.Properties["provider"]);
            Preferences.Set("expiration", DateTime.Parse(result.Properties["expiration"]));
        }
        public string ToRawIdentityUrl(string redirectUrl, WebAuthenticatorResult result)
        {
            IEnumerable <string> parameters = result.Properties.Select(pair => $"{pair.Key}={pair.Value}");
            var values = string.Join("&", parameters);

            return($"{redirectUrl}#{values}");
        }
Example #4
0
        public JwtSecurityToken ParseAuthenticationResult(WebAuthenticatorResult authenticationResult)
        {
            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(authenticationResult.IdToken);

            return(token);
        }
Example #5
0
        public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
        {
            WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri(Constants.RedirectUri));

            return(new BrowserResult()
            {
                Response = ParseAuthenticatorResult(authResult)
            });
        }
Example #6
0
        public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
        {
            WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri("com.companyname.mycalendar://login"));

            return(new BrowserResult()
            {
                Response = ParseAuthenticatorResult(authResult)
            });
        }
        private string ParseAuthenticatorResult(WebAuthenticatorResult result)
        {
            string code         = result?.Properties["code"];
            string scope        = result?.Properties["scope"];
            string state        = result?.Properties["state"];
            string sessionState = result?.Properties["session_state"];

            return($"{ApiConstants.RedirectUri}#code={code}&scope={scope}&state={state}&session_state={sessionState}");
        }
Example #8
0
        private string Parse(WebAuthenticatorResult result)
        {
            string code         = result?.Properties["code"];
            string scope        = result?.Properties["scope"];
            string state        = result?.Properties["state"];
            string sessionState = result?.Properties["session_state"];

            return($"myapp://auth_callback#code={code}&scope={scope}&state={state}&session_state={sessionState}");
        }
Example #9
0
        public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default)
        {
            WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri("myapp://auth_callback"));

            return(new BrowserResult()
            {
                Response = Parse(authResult)
            });
        }
Example #10
0
        string ParseAuthenticatorResult(WebAuthenticatorResult result)
        {
            string code         = result?.Properties["code"];
            string idToken      = result?.IdToken;
            string scope        = result?.Properties["scope"];
            string state        = result?.Properties["state"];
            string sessionState = result?.Properties["session_state"];

            return($"{Constants.RedirectUri}#code={code}&id_token={idToken}&scope={scope}&state={state}&session_state={sessionState}");
        }
Example #11
0
        public JwtSecurityToken ParseAuthenticationResult(WebAuthenticatorResult authenticationResult)
        {
            if (authenticationResult == null)
            {
                throw new ArgumentNullException(nameof(authenticationResult));
            }

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadJwtToken(authenticationResult.IdToken);

            return(token);
        }
Example #12
0
        protected async Task <bool> HandleCaptchaAsync(string CaptchaSiteKey)
        {
            var callbackUri = "bitwarden://captcha-callback";
            var data        = AppHelpers.EncodeDataParameter(new
            {
                siteKey             = CaptchaSiteKey,
                locale              = i18nService.Culture.TwoLetterISOLanguageName,
                callbackUri         = callbackUri,
                captchaRequiredText = AppResources.CaptchaRequired,
            });

            var url = environmentService.GetWebVaultUrl() +
                      "/captcha-mobile-connector.html?" +
                      "data=" + data +
                      "&parent=" + Uri.EscapeDataString(callbackUri) +
                      "&v=1";

            WebAuthenticatorResult authResult = null;
            bool cancelled = false;

            try
            {
                // PrefersEphemeralWebBrowserSession should be false to allow access to the hCaptcha accessibility
                // cookie set in the default browser
                // https://www.hcaptcha.com/accessibility
                var options = new WebAuthenticatorOptions
                {
                    Url         = new Uri(url),
                    CallbackUrl = new Uri(callbackUri),
                    PrefersEphemeralWebBrowserSession = false,
                };
                authResult = await WebAuthenticator.AuthenticateAsync(options);
            }
            catch (TaskCanceledException)
            {
                await deviceActionService.HideLoadingAsync();

                cancelled = true;
            }

            if (cancelled == false && authResult != null &&
                authResult.Properties.TryGetValue("token", out _captchaToken))
            {
                return(true);
            }
            else
            {
                await platformUtilsService.ShowDialogAsync(AppResources.CaptchaFailed,
                                                           AppResources.CaptchaRequired);

                return(false);
            }
        }
Example #13
0
        async void OnLoginButtonClicked(object sender, EventArgs e)
        {
            string url = identityService.CreateAuthorizationRequest();
            WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(url), new Uri(Constants.RedirectUri));

            string raw = ParseAuthenticatorResult(authResult);

            authorizeResponse = new AuthorizeResponse(raw);
            if (authorizeResponse.IsError)
            {
                Console.WriteLine("ERROR: {0}", authorizeResponse.Error);
            }
        }
        /// <summary>
        /// Authenticate the user through Google
        /// </summary>
        /// <returns></returns>
        public async Task <IdToken> AuthenticateUser()
        {
            string requestUri = "https://accounts.google.com/o/oauth2/v2/auth?";

            requestUri += $"scope=openid%20email%20profile";
            requestUri += $"&response_type=code";
            requestUri += $"&redirect_uri={redirect_uri}";
            requestUri += $"&client_id={client_id}";
            requestUri += "&hd=miamioh.edu";
            requestUri += "&prompt=select_account";
            WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(
                new Uri(requestUri),
                new Uri(redirect_uri));

            // while token is fetched to gather user info, disable page and show loading symbol
            activityIndicator.IsRunning = true;
            LoggingIn.IsVisible         = true;
            this.Content.IsEnabled      = false;

            string code     = authResult.Properties["code"];
            string content  = $"code={code}&client_id={client_id}&redirect_uri={redirect_uri}&grant_type=authorization_code";
            string tokenUrl = "https://oauth2.googleapis.com/token";

            IdToken       idToken = null;
            TokenResponse result  = await _restService.ObtainAccessToken(tokenUrl, content);

            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                var               provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                string j = decoder.Decode(result.IdToken);
                idToken = JsonConvert.DeserializeObject <IdToken>(j);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }

            //activityIndicator.IsRunning = false;
            //LoggingIn.IsVisible = false;
            return(idToken);
        }
Example #15
0
        /// <summary>
        /// Abre a tela da web para efetuar o login ou registrar o usuário
        /// </summary>
        /// <param name="tipoLogin">Tipo do login</param>
        /// <returns>Token do usuário</returns>
        private static async Task <string> LoginRegistrarUsuarioWeb(TipoLogin tipoLogin)
        {
            try
            {
                WebAuthenticatorResult result = await WebAuthenticator.AuthenticateAsync(
                    new Uri($"{AwsHelper.COGNITO_DOMAIN}/{Enumeradores.Enumerador.ObterDescricao(tipoLogin)}?client_id={AwsHelper.COGNITO_APP_CLIENT_ID}&response_type=token&scope=email+openid+profile&redirect_uri={AwsHelper.COGNITO_REDIRECT_URI}"),
                    new Uri(AwsHelper.COGNITO_REDIRECT_URI));

                return(result?.AccessToken);
            }
            catch (TaskCanceledException)
            {
                throw new MobileErrorException("Processo de autenticação cancelado!");
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #16
0
        string ParseAuthenticatorResult(WebAuthenticatorResult result)
        {
            bool first        = true;
            var  resultString = "com.companyname.mycalendar://login";

            foreach (var property in result.Properties)
            {
                if (first)
                {
                    resultString += $"#{property.Key}={property.Value}";
                    first         = false;
                }
                else
                {
                    resultString += $"&{property.Key}={property.Value}";
                }
            }

            return(resultString);
        }
Example #17
0
        public async Task <UserToken> ExchangeCodeForIdToken(WebAuthenticatorResult authenticatorResult)
        {
            using (var httpClient = new HttpClient {
                BaseAddress = new Uri($"{OktaConfiguration.OrganizationUrl}/oauth2/default/v1/")
            })
            {
                var data = new Dictionary <string, string>
                {
                    { "grant_type", "authorization_code" },
                    { "client_id", OktaConfiguration.ClientId },
                    { "redirect_uri", OktaConfiguration.Callback },
                    { "code_verifier", codeVerifier },
                    { "code", authenticatorResult.Properties["code"] }
                };

                var responseMessage = await httpClient.PostAsync("token", new FormUrlEncodedContent(data));

                var response = await responseMessage.Content.ReadAsStringAsync();

                return(JsonSerializer.Deserialize <UserToken>(response));
            }
        }
Example #18
0
        public override async Task <IAuthenticatonResult> Authenticate(AuthParameters authParameters)
        {
            try
            {
                WebAuthenticatorResult authApiResultData = null;

                var authUrl     = new Uri(config.AuthApiSettings.socialAuthEndPoint + authParameters.AuthType.ToString());
                var callbackUrl = new Uri("xamarinessentials://");

                authApiResultData = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);

                var user = new Models.User.User_Model();
                user.Name = authApiResultData.Properties["name"] ?? "Unknown";

                return(new AuthResult(AuthStatus.Success, "", authApiResultData.AccessToken, authApiResultData.RefreshToken, authApiResultData.ExpiresIn, user));
            }
            catch (Exception ex)
            {
                await logger.LogToDebugger(ex.Message);

                return(new AuthResult(AuthStatus.Error, ex.Message));
            }
        }