示例#1
0
        private async void LoginButtonClicked(object sender, EventArgs e)
        {
            try
            {
                var callbackUrl = new Uri(OktaConfiguration.Callback);
                var loginUrl    = new Uri(loginService.BuildAuthenticationUrl());

                var authenticatorResult = await WebAuthenticator.AuthenticateAsync(loginUrl, callbackUrl);

                userToken = await loginService.ExchangeCodeForIdToken(authenticatorResult);

                var idToken = loginService.ParseAuthenticationResult(userToken.IdToken);

                var nameClaim = idToken.Claims.FirstOrDefault(claim => claim.Type == "name");

                if (nameClaim != null)
                {
                    WelcomeLabel.Text      = $"Welcome to Xamarin.Forms {nameClaim.Value}!";
                    LogoutButton.IsVisible = !(LoginButton.IsVisible = false);
                }
            }
            catch (TaskCanceledException)
            {
            }
        }
示例#2
0
        private async void ButtonLogin_Clicked(object sender, EventArgs e)
        {
            try
            {
                var service = new DropboxAuthService();
                var url     = service.CreateAuthorizationRequest(DropboxConfiguration.AuthorityUrl);
                authorizeUrl.Text = url;

                var authenticationResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri(url),
                    new Uri(DropboxConfiguration.RedirectUri));

                editorAuthResponse.Text = JsonSerializer.Serialize(authenticationResult);

                var code = authenticationResult.Properties["code"];

                var result = await service.GetTokenAsync(code);

                editorTokenResponse.Text = JsonSerializer.Serialize(result);

                var refresh = await service.GetRefreshTokenAsync(result.RefreshToken);

                editorRefreshTokenResponse.Text = JsonSerializer.Serialize(refresh);
            }
            catch (Exception ex)
            {
                lblInfo.Text = ex.ToString();
            }
        }
示例#3
0
        // autenticacion
        public async Task <WebAuthenticatorResult> Login()
        {
            // efectua el login de linkedin
            string LoginUrl = $"https://www.linkedin.com/oauth/v2/authorization?response_type={responseType}&client_id={clientId}&state={state}&scope={scope}&redirect_uri={redirectUrl}";

            return(await WebAuthenticator.AuthenticateAsync(new Uri(LoginUrl), new Uri(callbackUrl)));
        }
示例#4
0
        public async Task <(string response, Exception error)> Authenticate()
        {
            try
            {
                var storedToken = await this.GetAccessTokenFromSettings();

                if (storedToken)
                {
                    return(this.AccessToken, null);
                }
                else
                {
                    var state      = Guid.NewGuid().ToString("N");
                    var url        = $"https://www.dropbox.com/oauth2/authorize?client_id={ClientId}&state={state}&response_type=token&redirect_uri={RedirectUri}";
                    var authResult = await WebAuthenticator.AuthenticateAsync(
                        new Uri(url),
                        new Uri(RedirectUri));

                    this.AccessToken = authResult?.AccessToken;
                    await SaveDropboxToken(AccessToken);

                    return(this.AccessToken, null);
                }
            }
            catch (Exception ex)
            {
                return(null, ex);
            }
        }
示例#5
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 SomeViewModel()
        {
            SomeAction = new CoreCommand(async(obj) =>
            {
                LoadingMessageHUD = "Some action...";
                IsLoadingHUD      = true;
                await Task.Delay(new TimeSpan(0, 0, 4));
                IsLoadingHUD = false;
            });
            SeeFontAction = new Command(async() => {
                await Navigation.PushAsync(new FontDemo());
            });
            GoogleLoginAction = new CoreCommand(async(obj) =>
            {
                var authResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri("https://cloudmovieweb.azurewebsites.net/mobileauth/Google"),
                    new Uri("cloudmovie.mobile://"));

                AccountToken = authResult?.AccessToken;
            });
            MicrosoftLoginAction = new CoreCommand(async(obj) =>
            {
                var authResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri("https://cloudmovieweb.azurewebsites.net/mobileauth/Microsoft"),
                    new Uri("cloudmovie.mobile://"));

                AccountToken = authResult?.AccessToken;
            });
        }
示例#7
0
        async void Button_Clicked(System.Object sender, System.EventArgs e)
        {
            IRemoteAuthenticationClient authClient = new RemoteAuthenticationClient("", "", "");
            var authUri = authClient.BuildAuthorizeUri("sample", "myhue");

            var authResult = await WebAuthenticator.AuthenticateAsync(
                new Uri(authUri.AbsoluteUri),
                new Uri("mymeetings://"));

            var code = authResult?.Properties.FirstOrDefault(x => x.Key == "code").Value;

            if (String.IsNullOrEmpty(code))
            {
                return;
            }

            var accessToken = await authClient.GetToken(code);

            IRemoteHueClient client = new RemoteHueClient(authClient.GetValidToken);
            var bridges             = await client.GetBridgesAsync();

            var currentBridge = bridges.FirstOrDefault().Id;

            try
            {
                //var key = await client.RegisterAsync(bridges.First().Id, "Sample App");
                client.Initialize(bridges.First().Id, "");
                var lights = await client.GetLightsAsync();

                var lightResult = await client.SendCommandAsync(new LightCommand().TurnOff());
            }
            catch (Exception ex)
            {
            }
        }
示例#8
0
        private async void Login(string url, string clientId, string responseType, string callback, string scope)
        {
            try
            {
                var loginService = new LoginService();
                var fullUrl      = loginService.BuildAuthenticationUrl(url, clientId, responseType, callback, scope);

                var authenticationResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri(fullUrl),
                    new Uri(callback));

                var accessToken = authenticationResult?.AccessToken;

                if (accessToken == null && authenticationResult.Properties != null && authenticationResult.Properties.ContainsKey("code"))
                {
                    accessToken = authenticationResult.Properties["code"];
                }

                lblInfo.Text = accessToken;
            }
            catch (Exception ex)
            {
                lblInfo.Text = ex.ToString();
            }
        }
示例#9
0
        public async Task <Tuple <Tuple <string, string>, UserInfo> > GetEmailByLoggingIn()
        {
            WebAuthenticatorResult authResult;

            try
            {
                authResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri($"https://{domain}/login?client_id={clientId}&response_type={responseType}&scope={scope}&redirect_uri={callbackUri}"),
                    new Uri(callbackUri)
                    );
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                authResult = null;
            }

            if (authResult == null)
            {
                return(null);
            }
            var claims  = JWT.JsonWebToken.Base64UrlDecode(authResult.IdToken.Split('.')[1]);
            var cString = System.Text.Encoding.UTF8.GetString(claims);

            var c = JsonConvert.DeserializeObject <AuthClaims>(cString);
            var u = new UserInfo {
                Id = c.Email.ToLower(), Name = c.NickName
            };
            var tokens = new Tuple <string, string>(authResult.IdToken, authResult.RefreshToken);

            return(new Tuple <Tuple <string, string>, UserInfo>(tokens, u));
        }
        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()
                });
            }
        }
示例#11
0
        public async Task <WebAuthenticatorResult> LaunchUriAsync(string url)
        {
            var authResult = await WebAuthenticator.AuthenticateAsync(
                new Uri(url),
                new Uri(Constants.RedirectUri));

            return(authResult);
        }
        /// <summary>
        /// Runs the Google OAuth process in two steps :
        ///     - First step : retrieves the unique OAuth code from login UI web page
        ///     - Second step : send the unique OAuth code to Google's token server to get the OAuth token
        /// </summary>
        /// <returns>Returns a GoogleOAuthResponse containing the OAuth token</returns>
        public async Task <GoogleToken?> DoGoogleOAuthLoginAsync()
        {
            _loggingService.Trace("Executing LoginProvider.DoGoogleOAuthLoginAsync");

            WebAuthenticatorResult authenticatorResult;

            try
            {
                authenticatorResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri(_appSettings.GoogleAuthUrl),
                    new Uri(_appSettings.RedirectUrl));
            }
            catch (TaskCanceledException)
            {
                _loggingService.Trace("Task Canceled : DoGoogleOAuthLoginAsync");

                return(null);
            }

            var code = authenticatorResult.Properties.FirstOrDefault(x => x.Key.Equals("code")).Value;

            if (string.IsNullOrWhiteSpace(code))
            {
                _loggingService.Trace("No 'code' property found in authResult. Returning.");

                return(null);
            }

            using var client = new HttpClient();
            var parameters = new Dictionary <string, string> {
                { "code", code },
                { "client_id", _appSettings.ClientId },
                { "redirect_uri", _appSettings.RedirectUrl },
                { "grant_type", "authorization_code" }
            };

            HttpResponseMessage response;
            var encodedContent = new FormUrlEncodedContent(parameters);

            try
            {
                response = await client.PostAsync(_appSettings.GoogleTokenUrl, encodedContent).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();
            }
            catch (Exception e)
            {
                _loggingService.Error(e, "Error Executing LoginProvider.DoGoogleOAuthLoginAsync");

                return(null);
            }

            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var googleToken = JsonConvert.DeserializeObject <GoogleToken>(responseContent);

            return(googleToken);
        }
示例#13
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)
            });
        }
示例#14
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)
            });
        }
示例#15
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)
            });
        }
示例#16
0
        protected override async Task <string> StartSecureNavigation(Uri startUrl, Uri redirectUrl)
        {
            var authenticationResult = await WebAuthenticator.AuthenticateAsync(startUrl, redirectUrl);

            if (!authenticationResult.Properties.Any())
            {
                return(string.Empty);
            }

            return($"?{string.Join("&", authenticationResult.Properties.Select(x => $"{x.Key}={x.Value}"))}");
        }
示例#17
0
        public async Task Redirect(string urlBase, string callbackScheme, string accessToken, string refreshToken, int expires)
        {
            var r = await WebAuthenticator.AuthenticateAsync(
                new Uri($"{urlBase}?access_token={accessToken}&refresh_token={refreshToken}&expires={expires}"),
                new Uri($"{callbackScheme}://"));

            Assert.Equal(accessToken, r?.AccessToken);
            Assert.Equal(refreshToken, r?.RefreshToken);
            Assert.NotNull(r?.ExpiresIn);
            Assert.True(r?.ExpiresIn > DateTime.UtcNow);
        }
        public override async Task <AuthorizationResponse> Authorize(AuthorizationRequest request)
        {
            var authUrl     = request.BuildUrl();
            var callbackUrl = new Uri(request.RedirectUri);
            var result      = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);

            var serialized            = JsonSerializer.Serialize(result.Properties);
            var authorizationResponse = JsonSerializer.Deserialize <AuthorizationResponse>(serialized);

            return(authorizationResponse !);
        }
示例#19
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);
            }
        }
        public virtual async Task <Token> Login(object?state = null, string?client_id = null, IDictionary <string, string?>?acr_values = null, CancellationToken cancellationToken = default)
        {
            var authResult = await WebAuthenticator.AuthenticateAsync(GetLoginUrl(state, client_id, acr_values), ClientAppProfile.OAuthRedirectUri).ConfigureAwait(false);

            Token token = authResult.Properties;

            string jsonToken = JsonConvert.SerializeObject(token);

            await StoreToken(jsonToken, cancellationToken).ConfigureAwait(false);

            return(token);
        }
        public async Task <Result <bool> > StartSignInAsync()
        {
            try
            {
                var existingToken = await GetAccessTokenAsync();

                if (existingToken?.ResultType == ResultType.Ok && existingToken.Data != null)
                {
                    return(new SuccessResult <bool>(true));
                }

                var state      = Guid.NewGuid().ToString();
                var clientId   = _authSettings.ClientId;
                var authResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri($"{_baseUrl}/signin?client_id={clientId}&state={state}&redirect_uri=suavekeystwitch://"),
                    new Uri("suavekeystwitch://"));

                var code         = authResult.Properties["code"];
                var confirmState = authResult.Properties["state"];

                if (state != confirmState)
                {
                    return(new InvalidResult <bool>("Invalid state. This might be a sign of an interception attack."));
                }

                using (var client = new HttpClient())
                {
                    var response = await client.PostAsync($"{_baseUrl}/signin/token?client_id={clientId}&code={code}&grant_type=authorization_code&redirect_uri=suavekeystwitch://", null);

                    if (response?.IsSuccessStatusCode == true)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var tokenInfo = JsonConvert.DeserializeObject <TokenResponse>(json);

                        // we have our tokens. Gotta do something with it
                        _currentToken = tokenInfo?.AccessToken;
                        await StoreTokenInfo(tokenInfo);

                        return(new SuccessResult <bool>(true));
                    }
                }


                return(new InvalidResult <bool>("Unable to authenticate."));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new UnexpectedResult <bool>());
            }
        }
示例#22
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);
        }
示例#24
0
        public async Task <Result <bool> > StartSignInAsync()
        {
            try
            {
                var existingToken = await GetAccessTokenAsync();

                if (existingToken?.ResultType == ResultType.Ok && existingToken.Data != null)
                {
                    return(new SuccessResult <bool>(true));
                }

                var state      = Guid.NewGuid().ToString();
                var clientId   = _authSettings.ClientId;
                var url        = $"{_baseUrl}/oauth2/authorize?client_id={clientId}&response_type=code&scope=chat:read+chat:edit+channel:moderate+whispers:read+whispers:edit+channel_editor&redirect_uri=suavekeystwitch://";
                var authResult = await WebAuthenticator.AuthenticateAsync(
                    new Uri(url),
                    new Uri("suavekeystwitch://"));

                var code = authResult.Properties["code"];

                using (var client = new HttpClient())
                {
                    var response = await client.PostAsync($"{_baseUrl}/oauth2/token?client_id={clientId}&client_secret={_authSettings.ClientSecret}&code={code}&grant_type=authorization_code&redirect_uri=suavekeystwitch://", null);

                    if (response?.IsSuccessStatusCode == true)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var tokenInfo = JsonConvert.DeserializeObject <TokenResponse>(json);

                        // we have our tokens. Gotta do something with it
                        _currentToken = tokenInfo?.AccessToken;
                        await StoreTokenInfo(tokenInfo);

                        return(new SuccessResult <bool>(true));
                    }
                }


                return(new InvalidResult <bool>("Unable to authenticate."));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new UnexpectedResult <bool>());
            }
        }
示例#25
0
        public static async Task <bool> IDP4Login()
        {
            try
            {
                var authUrl     = new Uri($"https://pilotdeli-mvc.azurewebsites.net/mobileauth/login");
                var callbackUrl = new Uri(CALLBACK_URL);
                var result      = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);

                appToken.AccessToken.Token  = result?.AccessToken;
                appToken.RefreshToken.Token = result?.RefreshToken;

                appToken.AccessToken.ExpiredDate = getTokenExpiredDate(appToken.AccessToken.Token);

                var needLogout = await NeedLoginAgain();

                if (needLogout)
                {
                    await App.Current.MainPage.DisplayAlert("แจ้งเตือน", $"Session หมด อายุ", "ปิด");
                    await Logout();

                    return(false);
                }

                var RefId = result.Properties.ContainsKey("ref_id") ? result.Properties["ref_id"] : "";

                if (!string.IsNullOrWhiteSpace(RefId))
                {
                    await BikerService.SetBikerInfo(RefId);
                }
                else
                {
                    await App.Current.MainPage.DisplayAlert("แจ้งเตือน", $"คุณยังไม่ได้ยืนยัน Consent", "ปิด");
                    await Logout();

                    return(false);
                }

                //TODO: SetClientBearer when server use real IDP
                //HttpClientService.SetClientBearer(appToken.AccessToken.Token);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
示例#26
0
        private async void LogoutButtonClicked(object sender, EventArgs e)
        {
            try
            {
                var callbackUrl    = new Uri(OktaConfiguration.LogOutCallback);
                var buildLogOutUrl = loginService.BuildLogOutUrl(userToken.IdToken);
                var logoutResult   = await WebAuthenticator.AuthenticateAsync(new Uri(buildLogOutUrl), callbackUrl);

                userToken = null;

                WelcomeLabel.Text      = "Welcome to Xamarin.Forms!";
                LogoutButton.IsVisible = !(LoginButton.IsVisible = true);
            }
            catch (TaskCanceledException)
            {
            }
        }
        private async Task MiAuthAsync()
        {
            uuid = Guid.NewGuid().ToString();

            var url = $"https://{Url.Value}/miauth/{uuid}?"
                      + "name=Groundpolis+Mobile"
                      + $"&callback={HttpUtility.UrlEncode(Const.MIAUTH_CALLBACK)}"
                      + $"&permission={string.Join(",", Groundpolis.Permission)}";

            // MVVM の流儀に反するけど、しらねー
            try
            {
                await WebAuthenticator.AuthenticateAsync(new Uri(url), new Uri(Const.MIAUTH_CALLBACK));
            }
            catch (Exception)
            {
                Error.Value    = "は?エラーやぞ";
                IsLoaded.Value = true;
                IsBusy.Value   = false;
                return;
            }

            IsLoaded.Value = true;

            IsBusy.Value = true;
            var miauthUrl = $"https://{Url.Value}/api/miauth/{uuid}/check";
            var res       = await Http.PostAsync(miauthUrl, new StringContent(""));

            var json = await res.Content.ReadAsStringAsync();

            var status = JsonConvert.DeserializeObject <MiAuthStatus>(json);

            if (status.Ok)
            {
                await Groundpolis.SignInAsync(status.Token, Url.Value);

                while (Root.Navigation.ModalStack.Count > 0)
                {
                    await Root.Navigation.PopModalAsync();
                }
            }
            else
            {
                Error.Value = "認証に失敗しました";
            }
        }
        /// <summary>
        /// Obtain the authorization code from the App Service Authentication.
        /// </summary>
        /// <returns>The authorization code</returns>
        /// <exception cref="InvalidOperationException">
        ///     Thrown if the authentication fails.
        /// </exception>
        public override async Task <string> GetAuthorizationCodeAsync()
        {
            try
            {
                var result = await WebAuthenticator.AuthenticateAsync(LoginUri, CallbackUri).ConfigureAwait(false);

                if (!result.Properties.TryGetValue("authorization_code", out string authorization_code))
                {
                    throw new InvalidOperationException("Authentication failed: authorization_code not returned");
                }
                return(Uri.UnescapeDataString(authorization_code));
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Authorization failed: {ex.Message}", ex);
            }
        }
示例#29
0
        private async void LoginButtonClicked(object sender, EventArgs e)
        {
            try
            {
                var callbackUrl = new Uri(AuthConfiguration.Callback);
                var loginUrl    = new Uri(AuthConfiguration.AuthorizationEndpoint);

                var authenticationResult = await WebAuthenticator.AuthenticateAsync(loginUrl, callbackUrl);

                NameLabel.Text         = authenticationResult.Get("code");
                LogoutButton.IsVisible = !(LoginButton.IsVisible = false);
            }
            catch (TaskCanceledException)
            {
                //User closed browser
            }
        }
示例#30
0
        public async Task AuthenticateAsync()
        {
            APIAccessor accessor  = new APIAccessor();
            string      client_id = "35241";
            string      url       = $"https://www.bungie.net/en/OAuth/Authorize?client_id={client_id}&response_type=code";
            string      redirect  = "myapp://";

            var authResult = await WebAuthenticator.AuthenticateAsync(new Uri(url), new Uri(redirect));

            string code = authResult?.Properties["code"];

            string    raw = $"{redirect}#client_id={client_id}&grant_type=authorization_code&code={code}";
            var       authorizeResponse = new AuthorizeResponse(raw);
            UserToken userToken         = await GetTokenAsync(authorizeResponse.Code, accessor);

            APIAccessor.Authorized(userToken);
        }