Пример #1
0
        public static async void Login(string[] permissions, Action<WebAuthenticationResult, Exception> onComplete)
        {
            try
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    var scope = string.Join(",", permissions);

                    var facebookRedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;

                    var requestUri = new Uri(string.Format(FaceBookAuth, AppId, facebookRedirectUri, scope));
                    var callbackUri = new Uri(facebookRedirectUri);

                    var asyncOperation = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, callbackUri);
                    if (onComplete != null)
                    {
                        var authResult = new WebAuthenticationResult();
                        if (asyncOperation != null)
                        {
                            authResult.ResponseData = asyncOperation.ResponseData;
                            authResult.ResponseErrorDetail = asyncOperation.ResponseErrorDetail;
                            authResult.ResponseStatus = (WebAuthenticationStatus) asyncOperation.ResponseStatus;
                        }
                        onComplete(authResult, null);
                    }
                });
            }
            catch (Exception ex)
            {
                if (onComplete != null)
                {
                    onComplete(null, ex);
                }
            }
        }
Пример #2
0
        private static void InvokeCallbackCommand( WebAuthenticateInteraction webAuthenticate, WebAuthenticationResult authenticationResult )
        {
            Contract.Requires( webAuthenticate != null );
            Contract.Requires( authenticationResult != null );

            IWebAuthenticationResult result = null;

            if ( authenticationResult.ResponseStatus == WebAuthenticationStatus.Success )
            {
                result = new WebAuthenticationResultAdapter( authenticationResult );
                webAuthenticate.ResponseStatus = 200U;
                webAuthenticate.ResponseData = authenticationResult.ResponseData;
                webAuthenticate.DefaultCommand?.Execute( result );
            }
            else
            {
                webAuthenticate.ResponseStatus = authenticationResult.ResponseErrorDetail;
                webAuthenticate.CancelCommand?.Execute( result );
            }
        }
Пример #3
0
        private async Task <BrowserResult> InvokeAsyncCore(BrowserOptions options, bool silentMode)
        {
            bool isLogout   = false;
            var  wabOptions = WebAuthenticationOptions.None;

            if (options.ResponseMode == OidcClientOptions.AuthorizeResponseMode.FormPost)
            {
                wabOptions |= WebAuthenticationOptions.UseHttpPost;
            }
            if (_enableWindowsAuthentication)
            {
                wabOptions |= WebAuthenticationOptions.UseCorporateNetwork;
            }
            if (silentMode)
            {
                wabOptions |= WebAuthenticationOptions.SilentMode;
            }

            WebAuthenticationResult wabResult = null;

            try
            {
                // Check for logout
                Uri startUri = new Uri(options.StartUrl);
                if (startUri.AbsolutePath.StartsWith("/v2/logout", StringComparison.OrdinalIgnoreCase))
                {
                    isLogout = true;

                    // See http://www.cloudidentity.com/blog/2014/11/21/getting-rid-of-residual-cookies-in-windows-store-apps/
                    try
                    {
                        await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.SilentMode, new Uri(options.StartUrl));
                    }
                    catch (Exception)
                    {
                        // timeout. That's expected
                    }
                }
                else
                {
                    if (string.Equals(options.EndUrl, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri, StringComparison.Ordinal))
                    {
                        wabResult = await WebAuthenticationBroker.AuthenticateAsync(
                            wabOptions, new Uri(options.StartUrl));
                    }
                    else
                    {
                        wabResult = await WebAuthenticationBroker.AuthenticateAsync(
                            wabOptions, new Uri(options.StartUrl), new Uri(options.EndUrl));
                    }
                }
            }
            catch (Exception ex)
            {
                return(new BrowserResult
                {
                    ResultType = BrowserResultType.UnknownError,
                    Error = ex.ToString()
                });
            }

            if (wabResult == null)
            {
                if (isLogout)
                {
                    return(new BrowserResult
                    {
                        ResultType = BrowserResultType.Success,
                        Response = String.Empty
                    });
                }

                return(new BrowserResult
                {
                    ResultType = BrowserResultType.UnknownError,
                    Error = "Invalid response from WebAuthenticationBroker"
                });
            }

            if (wabResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                return(new BrowserResult
                {
                    ResultType = BrowserResultType.Success,
                    Response = wabResult.ResponseData
                });
            }

            if (wabResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                return(new BrowserResult
                {
                    ResultType = BrowserResultType.HttpError,
                    Error = wabResult.ResponseErrorDetail.ToString()
                });
            }

            if (wabResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                return(new BrowserResult
                {
                    ResultType = BrowserResultType.UserCancel
                });
            }

            return(new BrowserResult
            {
                ResultType = BrowserResultType.UnknownError,
                Error = "Invalid response from WebAuthenticationBroker"
            });
        }
Пример #4
0
 internal UserCancelAuthorizeException(WebAuthenticationResult result) : base(result)
 {
 }
Пример #5
0
        public async Task MashapeFacebookLogin()
        {
            //NOTE: Check App.xaml.cs for the variables that you need to fill in

            var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url";

            var client = new System.Net.Http.HttpClient();

            HttpContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("consumerKey", App.ConsumerKey),
                new KeyValuePair <string, string>("consumerSecret", App.ConsumerSecret),
                new KeyValuePair <string, string>("callbackUrl", App.CallbackUrl)
            });

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader);

            progressRing.IsActive = true;
            btnLogin.IsEnabled    = false;
            var response = await client.PostAsync(targeturi, content);

            progressRing.IsActive = false;
            btnLogin.IsEnabled    = true;

            if (response.IsSuccessStatusCode)
            {
                string respContent = await response.Content.ReadAsStringAsync();

                string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url"));

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    new Uri(loginUrl),
                    new Uri(App.CallbackUrl));


                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                    var callBackUrl = WebAuthenticationResult.ResponseData.ToString();
                    //Where's ParseQueryString when you need it...
                    App.AccessToken = GetParameter(callBackUrl, "accessToken");
                    //App.AccessSecret = GetParameter(callBackUrl, "accessSecret");
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    // The user canceled the authentication
                }
            }
            else
            {
                //The POST failed, so update the UI accordingly
                //txtBlockResult.Text = "Error";
            }
        }
Пример #6
0
        /// <summary>
        /// Gets a requests token from reddit
        /// </summary>
        /// <returns></returns>
        private async Task <UserManager.SignInResult> GetRedditRequestToken()
        {
            // Create a random number
            string nonce = GetNonce();

            // Create the nav string
            string tokenRequestString = "https://reddit.com/api/v1/authorize.compact?"
                                        + "client_id=" + BACONIT_APP_ID
                                        + "&response_type=code"
                                        + "&state=" + nonce
                                        + "&redirect_uri=" + BACONIT_REDIRECT_URL
                                        + "&duration=permanent"
                                        + "&scope=modcontributors,modconfig,subscribe,wikiread,wikiedit,vote,mysubreddits,submit,"
                                        + "modlog,modposts,modflair,save,modothers,read,privatemessages,report,identity,livemanage,"
                                        + "account,modtraffic,edit,modwiki,modself,history,flair";

            try
            {
                Uri start = new Uri(tokenRequestString, UriKind.Absolute);
                Uri end   = new Uri(BACONIT_REDIRECT_URL, UriKind.Absolute);
                WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, start, end);

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    // Woot we got it! Parse out the token
                    int startOfState = result.ResponseData.IndexOf("state=") + 6;
                    int endOfState   = result.ResponseData.IndexOf("&", startOfState);
                    int startOfCode  = result.ResponseData.IndexOf("code=") + 5;
                    int endOfCode    = result.ResponseData.IndexOf("&", startOfCode);

                    // Make sure we found a code (result is -1 + 5 = 4)
                    if (startOfCode == 4)
                    {
                        return(new UserManager.SignInResult()
                        {
                            Message = "Reddit returned an error!"
                        });
                    }

                    // Check for the ends
                    endOfCode  = endOfCode == -1 ? result.ResponseData.Length : endOfCode;
                    endOfState = endOfState == -1 ? result.ResponseData.Length : endOfState;

                    string state = result.ResponseData.Substring(startOfState, endOfState - startOfState);
                    string code  = result.ResponseData.Substring(startOfCode, endOfCode - startOfCode);

                    // Check the state
                    if (nonce != state)
                    {
                        return(new UserManager.SignInResult()
                        {
                            Message = "The state is not the same!"
                        });
                    }

                    // Check the code
                    if (String.IsNullOrWhiteSpace(code))
                    {
                        return(new UserManager.SignInResult()
                        {
                            Message = "The code is empty!"
                        });
                    }

                    // Return the code!
                    return(new UserManager.SignInResult()
                    {
                        WasSuccess = true,
                        Message = code
                    });
                }
                else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    return(new UserManager.SignInResult()
                    {
                        WasErrorNetwork = true
                    });
                }
                else
                {
                    return(new UserManager.SignInResult()
                    {
                        WasUserCanceled = true
                    });
                }
            }
            catch (Exception e)
            {
                m_baconMan.MessageMan.DebugDia("Failed to get request token", e);
                return(new UserManager.SignInResult()
                {
                    WasErrorNetwork = true
                });
            }
        }
        private async void DoAuthFlow(LoginOptions loginOptions)
        {
            loginOptions.DisplayType = LoginOptions.DefaultStoreDisplayType;
            var loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
            var callbackUri = new Uri(loginOptions.CallbackUrl);
            await SDKServiceLocator.Get <IAuthHelper>().ClearCookiesAsync(loginOptions);

            WebAuthenticationResult webAuthenticationResult = null;
            var hasWebAuthErrors = false;

            try
            {
                LoggingService.Log("Launching web authentication broker", LoggingLevel.Verbose);

                webAuthenticationResult =
                    await
                    WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUri, callbackUri);
            }
            // If a bad URI was passed in the user is shown an error message by the WebAuthenticationBroken, when user
            // taps back arrow we are then thrown a FileNotFoundException, but since user already saw error message we
            // should just swallow that exception
            catch (FileNotFoundException)
            {
                SetupAccountPage();
                return;
            }
            catch (Exception ex)
            {
                LoggingService.Log(ex, LoggingLevel.Critical, "Exception occurred during login flow");

                hasWebAuthErrors = true;
            }

            if (hasWebAuthErrors)
            {
                await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error"));

                SetupAccountPage();
                return;
            }

            if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(webAuthenticationResult.ResponseData);
                if (!String.IsNullOrWhiteSpace(responseUri.Query) &&
                    responseUri.Query.IndexOf("error", StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_authentication_error"));

                    SetupAccountPage();
                }
                else
                {
                    AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1));

                    await SDKServiceLocator.Get <IAuthHelper>().OnLoginCompleteAsync(loginOptions, authResponse);
                }
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                SetupAccountPage();
            }
            else
            {
                await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error"));

                SetupAccountPage();
            }
        }
Пример #8
0
        private async void buttonWeibo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var appKey      = "39261162";
                var appSecret   = "652ec0b02f814d514fc288f3eab2efda";
                var callbackUrl = "http://webabcd.cnblogs.com"; // 在新浪微博开放平台设置的回调页

                var requestAuthorizationCode_url =
                    string.Format("https://api.weibo.com/oauth2/authorize?client_id={0}&response_type=code&redirect_uri={1}",
                                  appKey,
                                  callbackUrl);

                // 第一步:request authorization code
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    new Uri(requestAuthorizationCode_url),
                    new Uri(callbackUrl));

                // 第一步的结果
                lblMsg.Text = WebAuthenticationResult.ResponseStatus.ToString() + Environment.NewLine;

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    // 从第一步返回的数据中获取 authorization code
                    var authorizationCode = QueryString(WebAuthenticationResult.ResponseData, "code");
                    lblMsg.Text += "authorizationCode: " + authorizationCode + Environment.NewLine;

                    var requestAccessToken_url =
                        string.Format("https://api.weibo.com/oauth2/access_token?client_id={0}&client_secret={1}&grant_type=authorization_code&redirect_uri={2}&code={3}",
                                      appKey,
                                      appSecret,
                                      callbackUrl,
                                      authorizationCode);

                    // 第二步:request access token
                    HttpClient client   = new HttpClient();
                    var        response = await client.PostAsync(new Uri(requestAccessToken_url), null);

                    // 第二步的结果:获取其中的 access token
                    var jsonString = await response.Content.ReadAsStringAsync();

                    JsonObject jsonObject  = JsonObject.Parse(jsonString);
                    var        accessToken = jsonObject["access_token"].GetString();
                    lblMsg.Text += "accessToken: " + accessToken + Environment.NewLine;

                    var requestProtectedResource_url =
                        string.Format("https://api.weibo.com/2/statuses/friends_timeline.json?access_token={0}",
                                      accessToken);

                    // 第三步:request protected resource,获取需要的数据(本例为获取登录用户好友最新发布的微博)
                    var result = await client.GetStringAsync(new Uri(requestProtectedResource_url)); // 由于本 app 没有提交微博开放平台审核,所以如果使用的账号没有添加到微博开放平台的测试账号中的话,是会出现异常的

                    lblMsg.Text += "result: " + result;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += ex.ToString();
            }
        }
Пример #9
0
        private async void ctlApiEditor_SaveComplete(object sender, EventArgs e)
        {
            apiKey = ctlApiEditor.APIKey;

            try
            {
                _flickr.ApiKey    = apiKey.APIKey;
                _flickr.ApiSecret = apiKey.APISecret;


                // Acquiring a request token
                TimeSpan SinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
                Random   Rand       = new Random();
                String   FlickrUrl  = "https://secure.flickr.com/services/oauth/request_token";
                Int32    Nonce      = Rand.Next(1000000000);

                // Compute base signature string and sign it.
                // This is a common operation that is required for all requests even after the token is obtained.
                // Parameters need to be sorted in alphabetical order
                // Keys and values should be URL Encoded.
                String SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(apiKey.APICallbackUrl);
                SigBaseStringParams += "&" + "oauth_consumer_key=" + apiKey.APIKey;
                SigBaseStringParams += "&" + "oauth_nonce=" + Nonce.ToString();
                SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
                SigBaseStringParams += "&" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds);
                SigBaseStringParams += "&" + "oauth_version=1.0";
                String SigBaseString = "GET&";
                SigBaseString += Uri.EscapeDataString(FlickrUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

                IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(apiKey.APISecret + "&", BinaryStringEncoding.Utf8);
                MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
                CryptographicKey     MacKey           = HmacSha1Provider.CreateKey(KeyMaterial);
                IBuffer DataToBeSigned  = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8);
                IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
                String  Signature       = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

                FlickrUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature);
                string GetResponse = await SendDataAsync(FlickrUrl);

                //rootPage.NotifyUser("Received Data: " + GetResponse, NotifyType.StatusMessage);


                if (GetResponse != null)
                {
                    String   oauth_token        = null;
                    String   oauth_token_secret = null;
                    String[] keyValPairs        = GetResponse.Split('&');

                    for (int i = 0; i < keyValPairs.Length; i++)
                    {
                        String[] splits = keyValPairs[i].Split('=');
                        switch (splits[0])
                        {
                        case "oauth_token":
                            oauth_token = splits[1];
                            break;

                        case "oauth_token_secret":
                            oauth_token_secret = splits[1];
                            break;
                        }
                    }

                    RequestToken = new OAuthRequestToken()
                    {
                        Token = oauth_token, TokenSecret = oauth_token_secret
                    };

                    if (oauth_token != null)
                    {
                        FlickrUrl = "https://secure.flickr.com/services/oauth/authorize?oauth_token=" + oauth_token + "&perms=read";
                        System.Uri StartUri = new Uri(FlickrUrl);
                        System.Uri EndUri   = new Uri(apiKey.APICallbackUrl.Contains("http") ? apiKey.APICallbackUrl : $"http://{apiKey.APICallbackUrl}");

                        //rootPage.NotifyUser("Navigating to: " + FlickrUrl, NotifyType.StatusMessage);
                        WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                            WebAuthenticationOptions.None,
                            StartUri,
                            EndUri);

                        if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                        {
                            OutputToken(WebAuthenticationResult.ResponseData.ToString());
                            String[] partsa = WebAuthenticationResult.ResponseData.ToString().Split('?');
                            String[] partsb = partsa[1].Split('&');

                            var xoauth_token    = "";
                            var xoauth_verifier = "";

                            for (int i = 0; i < partsb.Length; i++)
                            {
                                String[] partsc = partsb[i].Split('=');
                                switch (partsc[0])
                                {
                                case "oauth_token":
                                    xoauth_token = partsc[1];
                                    break;

                                case "oauth_verifier":
                                    xoauth_verifier = partsc[1];
                                    break;
                                }
                            }


                            var rat = await _flickr.OAuthGetAccessTokenAsync(RequestToken, xoauth_verifier);

                            if (!rat.HasError)
                            {
                                AccessToken = rat.Result;

                                var dm = new PassportDataModel();
                                dm.Token       = AccessToken.Token;
                                dm.TokenSecret = AccessToken.TokenSecret;
                                dm.Verifier    = xoauth_verifier;
                                dm.PassType    = "Flickr";

                                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);
                            }
                        }
                        else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                        {
                            OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                        }
                        else
                        {
                            OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                        }
                    }
                }
            }
            catch //(Exception Error)
            {
                //rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
            }
        }
 public AuthorizeErrorHttpException(WebAuthenticationResult result) : base(result)
 {
 }
Пример #11
0
        public async override Task Login()
        {
            try
            {
                // try refresh token first
                RefreshToken = LocalSettings.LoadStorageValue <String>(LOCAL_OAUTH_TOKEN_REFRESH);
                if ((RefreshToken != null) && (RefreshToken != ""))
                {
                    await UpdateToken();
                }

                // refresh succeedeed, stop and return
                if (LoggedIn == WebAccountState.Connected)
                {
                    return;
                }

                String GooglePlusURL = "https://accounts.google.com/o/oauth2/auth?" +
                                       "client_id=" + Uri.EscapeDataString(ClientId) +
                                       "&redirect_uri=" + Uri.EscapeDataString(CallbackUrl) +
                                       "&response_type=code" +
                                       "&scope=" + Uri.EscapeDataString("http://picasaweb.google.com/data");

                Uri StartUri = new Uri(GooglePlusURL);
                // When using the desktop flow, the success code is displayed in the html title of this end uri
                Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.UseTitle,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    String webAuthResultResponseData = WebAuthenticationResult.ResponseData.ToString();

                    // Get auth code
                    string   responseData       = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("code"));
                    String[] keyValPairs        = responseData.Split('&');
                    string   authorization_code = null;
                    for (int i = 0; i < keyValPairs.Length; i++)
                    {
                        String[] splits = keyValPairs[i].Split('=');
                        switch (splits[0])
                        {
                        case "code":
                            authorization_code = splits[1];
                            break;
                        }
                    }

                    // test if first step failed for some reason
                    if (authorization_code == null)
                    {
                        return;
                    }

                    // request token from auth code
                    GooglePlusURL = "https://accounts.google.com/o/oauth2/token";

                    HttpContent content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("code", authorization_code),
                        new KeyValuePair <string, string>("client_id", ClientId),
                        new KeyValuePair <string, string>("client_secret", Secret),
                        new KeyValuePair <string, string>("redirect_uri", CallbackUrl),
                        new KeyValuePair <string, string>("grant_type", "authorization_code")
                    });

                    HttpResponseMessage _response = null;
                    try
                    {
                        _response = await(new HttpClient()).PostAsync(new Uri(GooglePlusURL), content);
                    }
                    catch (HttpRequestException e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                    if ((_response != null) && (_response.StatusCode == HttpStatusCode.OK))
                    {
                        LoggedIn = WebAccountState.Connected;
                        ResponseToken _responseToken = await Serialization.DeserializeHttpToJson <ResponseToken>(_response.Content) as ResponseToken;

                        Token        = _responseToken.access_token;
                        RefreshToken = _responseToken.refresh_token;
                        ExpiryDate   = DateTime.Now + new TimeSpan(0, 0, _responseToken.expires_in);

                        LocalSettings.SaveStorageValue <String>(LOCAL_OAUTH_TOKEN, Token);
                        LocalSettings.SaveStorageValue <String>(LOCAL_OAUTH_TOKEN_REFRESH, RefreshToken);
                        LocalSettings.SaveStorageValue <long>(LOCAL_OAUTH_EXPIRY_DATE, ExpiryDate.Ticks);

                        GetGooglePlusUserNameAsync(Token);
                    }
                }
            }
            catch (Exception Error)
            {
                Debug.WriteLine(Error.ToString());
            }
            return;
        }
Пример #12
0
 public AuthenticationEventArgs(WebAuthenticationResult result)
 {
     Result = result;
 }
Пример #13
0
        /// <summary>
        /// Authenticate against OAuth2 using WebAuthenticationBroker for a valid access token
        /// </summary>
        /// <param name="_baseUrl">Base Twitch API Url</param>
        /// <param name="_clientId">Client Id</param>
        /// <param name="_redirectUri">Authentication Redirect Uri</param>
        /// <param name="_scopes">Authentication Scopes</param>
        /// <returns>An access token to use with API requests</returns>
        public static async Task <string> Authenticate(string _baseUrl, string _clientId, string _redirectUri, string _scopes)
        {
            // Create request (use httpHelper to build query string)
            var httpHelper = new HttpHelper(_baseUrl, _clientId);
            var request    = httpHelper.CreateHttpRequest("kraken/oauth2/authenticate", HttpMethod.Get);

            httpHelper.AddQueryString(request, "client_id", _clientId); // Add client_id manually so it is part of the query string (required for WAB startUri below)
            httpHelper.AddQueryString(request, "action", "authorize");
            httpHelper.AddQueryString(request, "response_type", "token");
            httpHelper.AddQueryString(request, "redirect_uri", _redirectUri);
            httpHelper.AddQueryString(request, "scope", _scopes);
            //httpHelper.AddQueryString(request, "state", ""); // TODO?

            // Now use request.Uri to authenticate with WebAuthenticationBroker (OAuth2 for UWP applications)
            try {
                // Define where the WebAuthenticationBroker should start and end
                var startUri = request.RequestUri;
                var endUri   = new Uri(_redirectUri);

                // Begin authorization process
                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    // Success, so extract access token from result
                    string fragment = WebAuthenticationResult.ResponseData;

                    // Exit if user denies access (response was a twitch-cancel button (i.e. html user cancel))
                    // ?error=<error>&error_description=<description>
                    Match  match       = Regex.Match(fragment, "error=(?<reason>.*)&error_description");
                    string errorString = match.Groups["reason"].Value;
                    if (errorString.Equals("access_denied"))
                    {
                        throw new Exception("Access denied");
                    }

                    // Attempt to retrieve access token (successfully logged in)
                    // #access_token=<token>
                    match = Regex.Match(fragment, "#access_token=(?<token>.*)&scope=");
                    string oauth_token = match.Groups["token"].Value;

                    // Return oauth_token
                    if (!string.IsNullOrEmpty(oauth_token))
                    {
                        return(oauth_token);
                    }
                    else
                    {
                        throw new Exception("Returned OAuth Token was empty. Are you passing in the correct Client_Id?");
                    }
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new Exception(WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else if (WebAuthenticationResult.ResponseStatus != WebAuthenticationStatus.UserCancel)
                {
                    // Show error if not user cancel
                    throw new Exception(WebAuthenticationResult.ResponseStatus.ToString());
                }
            } catch (Exception ex) {
                Debug.WriteLine($"An error occurred while authenticating.\n\n{ex.ToString()}");
            }
            return(string.Empty);
        }
        public async void StartAuthentication(string clientId, string scope, string appSecret, Uri authorizeUrl, Uri redirectUrl, Uri tokenUrl, bool codeChallengeMethod)
        {
            string     codeVerifier = "";
            UriBuilder uriBuilder   = new UriBuilder(authorizeUrl);

            uriBuilder.Query += "?client_id=" + clientId + "&scope=" + Uri.EscapeUriString(scope) + "&response_type=code&redirect_uri=" + Uri.EscapeUriString(redirectUrl.AbsoluteUri);

            // Codice opzionale di sicurezza
            if (codeChallengeMethod)
            {
                codeVerifier = GetCodeVerifier();
                string codeChallenge = Base64URLEncode(EncDecHelper.SHA256Bytes(codeVerifier));
                uriBuilder.Query += "&code_challenge_method=S256&code_challenge=" + codeChallenge;
            }

            try
            {
                // Step 1: richiede il codice di autorizzazione
                WebAuthenticationResult Result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None,
                                                                                                 uriBuilder.Uri,
                                                                                                 redirectUrl);

                if (Result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    Account account = new Account();

                    // Estraggo il codice
                    string Code        = "";
                    string QueryString = new Uri(Result.ResponseData).Query;
                    QueryString = QueryString.Substring(1); // Salta "?"
                    string[] QueryParams = QueryString.Split('&');
                    for (short i = 0; i < QueryParams.Length; i++)
                    {
                        if (QueryParams[i].Contains("code="))
                        {
                            Code = QueryParams[i].Substring(5);
                            break;
                        }
                    }

                    // Step 2: scambio il codice con un access token
                    HttpClient appClient = new HttpClient();
                    try
                    {
                        List <KeyValuePair <string, string> > Param = new List <KeyValuePair <string, string> >
                        {
                            new KeyValuePair <string, string>("client_id", clientId),
                            new KeyValuePair <string, string>("redirect_uri", Uri.EscapeUriString(redirectUrl.AbsoluteUri)),
                            new KeyValuePair <string, string>("code", Uri.EscapeUriString(Code)),
                            new KeyValuePair <string, string>("scope", scope),
                            new KeyValuePair <string, string>("grant_type", "authorization_code")
                        };

                        // Non è obbligatorio in certi casi (es: Google Drive API per iOS, Android e UWP)
                        if (appSecret != "")
                        {
                            Param.Add(new KeyValuePair <string, string>("client_secret", appSecret));
                        }

                        // Codice opzionale di verifica
                        if (codeChallengeMethod && codeVerifier != "")
                        {
                            Param.Add(new KeyValuePair <string, string>("code_verifier", codeVerifier));
                        }

                        FormUrlEncodedContent Content  = new FormUrlEncodedContent(Param);
                        HttpResponseMessage   Response = await appClient.PostAsync(tokenUrl, Content);

                        if (Response.IsSuccessStatusCode)
                        {
                            // Ottengo un JSON con l'access token, il refesh token e la scadenza.
                            string content = await Response.Content.ReadAsStringAsync();

                            JObject JsonObj = JObject.Parse(content);
                            if (JsonObj != null && JsonObj.ContainsKey("access_token"))
                            {
                                foreach (KeyValuePair <string, JToken> token in JsonObj)
                                {
                                    account.Properties.Add(token.Key, token.Value.ToString());
                                }
                                account.Properties.Add("date_token", DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"));

                                // Step 3: richiedo un nuovo access token e un refresh token per aggiornare il
                                // token (in quando voglio accedere offline alla cartella di OneDrive)
                                OAuthAccountWrapper oAuthAccount = new OAuthAccountWrapper(account);
                                await RefreshToken(oAuthAccount, clientId, redirectUrl, appSecret, tokenUrl);

                                if (oAuthAccount.AccessToken.Length <= 0)
                                {
                                    appClient.Dispose();

                                    Debug.WriteLine("Authetication failed: access token not found in response");
                                    throw new Exception("Access token not found in response");
                                }

                                appClient.Dispose();
                                Debug.WriteLine("Authetication succeeded!");
                            }
                            else
                            {
                                appClient.Dispose();

                                Debug.WriteLine("Authetication failed: malformed response");
                                throw new Exception("Malformed response");
                            }
                        }
                        else
                        {
                            appClient.Dispose();

                            Debug.WriteLine("Authetication failed: " + Response.StatusCode.ToString());
                            throw new Exception("HTTP Error: " + Response.StatusCode + "\nUnable to redeem a token");
                        }

                        AuthenticatorCompletedEventArgs AuthCompletedEventArgs = new AuthenticatorCompletedEventArgs(account);
                        Completed?.Invoke(this, AuthCompletedEventArgs);
                    }
                    catch (Exception Ex)
                    {
                        appClient.Dispose();

                        Debug.WriteLine("Authetication failed: " + Ex.Message);
                        throw;
                    }
                }
                else if (Result.ResponseStatus != WebAuthenticationStatus.UserCancel)
                {
                    Debug.WriteLine("Authetication failed: " + Result.ResponseStatus.ToString());
                    throw new Exception("HTTP Error code: " + Result.ResponseErrorDetail + "\nError: " + Result.ResponseData);
                }
                else
                {
                    Debug.WriteLine("Authetication cancelled by user");

                    // Passando null si avrà IsAuthenticated a false.
                    // Vedi https://github.com/xamarin/Xamarin.Auth/blob/master/source/Core/Xamarin.Auth.Common.LinkSource/AuthenticatorCompletedEventArgs.cs
                    AuthenticatorCompletedEventArgs AuthCompletedEventArgs = new AuthenticatorCompletedEventArgs(null);
                    Completed?.Invoke(this, AuthCompletedEventArgs);
                }
            }
            catch (Exception Ex)
            {
                Debug.WriteLine("Authetication failed: " + Ex.Message);

                AuthenticatorErrorEventArgs AuthCompletedEventArgs = new AuthenticatorErrorEventArgs(Ex);
                Error?.Invoke(this, AuthCompletedEventArgs);
            }
        }
        /// <summary>
        /// Log a user into a Mobile Services application given a provider name and optional token object.
        /// </summary>
        /// <param name="provider" type="MobileServiceAuthenticationProvider">
        /// Authentication provider to use.
        /// </param>
        /// <param name="token" type="JsonObject">
        /// Optional, provider specific object with existing OAuth token to log in with.
        /// </param>
        /// <returns>
        /// Task that will complete when the user has finished authentication.
        /// </returns>
        internal async Task <MobileServiceUser> SendLoginAsync(MobileServiceAuthenticationProvider provider, JsonObject token = null)
        {
            if (this.LoginInProgress)
            {
                throw new InvalidOperationException(Resources.MobileServiceClient_Login_In_Progress);
            }

            if (!Enum.IsDefined(typeof(MobileServiceAuthenticationProvider), provider))
            {
                throw new ArgumentOutOfRangeException("provider");
            }

            string providerName = provider.ToString().ToLower();

            this.LoginInProgress = true;
            try
            {
                IJsonValue response = null;
                if (token != null)
                {
                    // Invoke the POST endpoint to exchange provider-specific token for a Windows Azure Mobile Services token

                    response = await this.RequestAsync("POST", LoginAsyncUriFragment + "/" + providerName, token);
                }
                else
                {
                    // Use WebAuthenicationBroker to launch server side OAuth flow using the GET endpoint

                    Uri startUri = new Uri(this.ApplicationUri, LoginAsyncUriFragment + "/" + providerName);
                    Uri endUri   = new Uri(this.ApplicationUri, LoginAsyncDoneUriFragment);

                    WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
                        WebAuthenticationOptions.None, startUri, endUri);

                    if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                    {
                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.Authentication_Failed, result.ResponseErrorDetail));
                    }
                    else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                    {
                        throw new InvalidOperationException(Resources.Authentication_Canceled);
                    }

                    int i = result.ResponseData.IndexOf("#token=");
                    if (i > 0)
                    {
                        response = JsonValue.Parse(Uri.UnescapeDataString(result.ResponseData.Substring(i + 7)));
                    }
                    else
                    {
                        i = result.ResponseData.IndexOf("#error=");
                        if (i > 0)
                        {
                            throw new InvalidOperationException(string.Format(
                                                                    CultureInfo.InvariantCulture,
                                                                    Resources.MobileServiceClient_Login_Error_Response,
                                                                    Uri.UnescapeDataString(result.ResponseData.Substring(i + 7))));
                        }
                        else
                        {
                            throw new InvalidOperationException(Resources.MobileServiceClient_Login_Invalid_Response_Format);
                        }
                    }
                }

                // Get the Mobile Services auth token and user data
                this.currentUserAuthenticationToken = response.Get(LoginAsyncAuthenticationTokenKey).AsString();
                this.CurrentUser = new MobileServiceUser(response.Get("user").Get("userId").AsString());
            }
            finally
            {
                this.LoginInProgress = false;
            }

            return(this.CurrentUser);
        }
Пример #16
0
        public async Task <GoogleUser> AuthenticateAsync()
        {
            //https://developers.google.com/api-client-library/dotnet/get_started

            //Get authorize token
            string googleUrl = AuthorizeUrl + "?client_id=" + Uri.EscapeDataString(ClientId);

            googleUrl += "&redirect_uri=" + Uri.EscapeDataString(CallbackUri);
            googleUrl += "&response_type=code";
            googleUrl += "&scope=" + Uri.EscapeDataString(Scope);

            Uri startUri = new Uri(googleUrl);
            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, new Uri(CallbackUri));

            string code = result.ResponseStatus != WebAuthenticationStatus.Success ? null : result.ResponseData.Substring(result.ResponseData.IndexOf('=') + 1);

            if (code != null)
            {
                code = Uri.UnescapeDataString(code);
            }
            if (code == null)
            {
                return(null);
            }

            //Fetch the oAuth2 token
            var httpClient = new HttpClient();
            var content    = new HttpFormUrlEncodedContent(new Dictionary <string, string>
            {
                { "code", code },
                { "client_id", ClientId },
                { "client_secret", ClientSecret },
                { "redirect_uri", CallbackUri },
                { "grant_type", "authorization_code" },
            });

            HttpResponseMessage accessTokenResponse = await httpClient.PostAsync(new Uri(AccessTokenUrl), content);

            Dictionary <string, string> responseDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(accessTokenResponse.Content.ToString());
            Account account = new Account(null, responseDict);

            //Get user info
            try
            {
                var request  = new OAuth2Request("GET", new Uri(ProfileUrl), null, account);
                var response = await request.GetResponseAsync();

                if (response == null)
                {
                    return(null);
                }

                var userJson = response.GetResponseText();
                var user     = JsonConvert.DeserializeObject <GoogleUser>(userJson);
                return(user);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
 /// <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;
 }
Пример #18
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Uri StartUri = new Uri(String.Format(
                                       "https://login.live.com/oauth20_authorize.srf?client_id={0}&scope={1}&response_type=token&redirect_uri={2}",
                                       "000000004812E450",
                                       "wl.signin onedrive.readwrite",
                                       WebUtility.UrlEncode("http://kiewic.com/")));

            Uri EndUri = new Uri("http://kiewic.com/");

            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                StartUri,
                EndUri);

            string testData = "http://kiewic.com/#access_token=EwCQAq1DBAAUGCCXc8wU/zFu9QnLdZXy%2bYnElFkAASu2H0Plv73qlsNgaAsNtK931pWT/wMdIa4zJzNKDNz9Er%2b97p7qo0XGR4%2bkfr%2bTCh4EV5wQ5NTYHufWeIdlvlm9lkdt3S6SotwygCJtUJqoVBI4fGJxXdTz6tCiqsC2NbZNxGR9od4osWN33ZuNIHp2f3%2b0KiX0fs%2bLJK8wIHW22LtUsj%2bCZY/K9qA%2bEbxAfgIpZDsAzV2U1NdjUobSKkvA3SEaARx/exIm0jZTRvM0XRoNHn/ZhlcMrd1nehEpOM3SFp3%2bkIfKiFiHXVm0P/vRS/VJFHXyNyCDFqGuw63vOklnqT4w2LhQyGu3G/%2bUIJBpBfuSHNwikthHPm3xjYoDZgAACO1iT9UawnDVYAFVZk/mv7wwb58vrJc1l0v7UClfth7j5bm/%2b7yYB0Rr9WHdquSqrotvovjR//V2Kmtgn3rzLQYg8ma5/2t6VgtyPIwbQm6kRP382CYpS3n5ZdvyX7nNWHwM9RlsKkZdS9zT7kkwxVsbW7MJaqSlcnbnkWaad84KzfrjSyxr9ceUb/eajRu3ltRy9Tbtkt2A8QjXtKw2Th82WjIrZjDg10JoeRqvFtfu1IeEBlofUgAPUK7VkbDdKVbgDIl97TZD5qW9m8JTQkhlbq6%2btZhiqFN/JZLOPum6a4sEOAf46v1sw70UDv0raxewMA6y2j6gGMGFojFse6vWHXTLQRpqnBwpc3iOnaaqcMGGCRimdMhtCmKITW9%2bJ/NbKo8DbTk65ancQYmBgNpNHNVStZTGex3MwcxEY9mQ1p69aXN0fXhWY7GL%2bB0wEuwJn50H04s4WtlepIv2Ww0QhfZ1vxkd1HIRdwE%3d&authentication_token=eyJhbGciOiJIUzI1NiIsImtpZCI6IjEiLCJ0eXAiOiJKV1QifQ.eyJ2ZXIiOjEsImlzcyI6InVybjp3aW5kb3dzOmxpdmVpZCIsImV4cCI6MTQyNTYxMjU0NCwidWlkIjoiNmM0NzY5YjcxMmZlNDBjYTY0MDAyYTg4MDI1NjBkMjgiLCJhdWQiOiJraWV3aWMuY29tIiwidXJuOm1pY3Jvc29mdDphcHB1cmkiOiJhcHBpZDovLzAwMDAwMDAwNDgxMkU0NTAiLCJ1cm46bWljcm9zb2Z0OmFwcGlkIjoiMDAwMDAwMDA0ODEyRTQ1MCJ9.Xzw94LXFH3wIwwSWpQmxPH9HAB9H-qyLLW4WZfcSY9o&token_type=bearer&expires_in=3600&scope=wl.signin%20onedrive.readwrite%20wl.basic%20wl.contacts_skydrive%20wl.skydrive%20wl.skydrive_update&user_id=6c4769b712fe40ca64002a8802560d28";

            testData = result.ResponseData;

            var urlDecoder = new WwwFormUrlDecoder(testData);

            foreach (var decoderEntry in urlDecoder)
            {
                Debug.WriteLine(decoderEntry.Name + " " + decoderEntry.Value);
            }

            string token = urlDecoder.GetFirstValueByName("http://kiewic.com/#access_token");

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", String.Format("bearer {0}", token));

            HttpStringContent createSessionContent = new HttpStringContent(
                "{ \"@name.conflictBehavior\": \"rename\" }",
                UnicodeEncoding.Utf8,
                "application/json");

            Uri createSessionUri = new Uri("https://api.onedrive.com/v1.0/drive/root:/Foo/bar2.txt:/upload.createSession");
            var response         = await client.PostAsync(createSessionUri, createSessionContent);

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

            Debug.WriteLine(responseString);

            JsonObject jsonObject = JsonObject.Parse(responseString);
            Uri        uploadUrl  = new Uri(jsonObject.GetNamedString("uploadUrl"));

            HttpStringContent putContent1 = new HttpStringContent(
                "hello ",
                UnicodeEncoding.Utf8,
                "text/plain");

            putContent1.Headers.Add("Content-Range", "bytes 0-5/11");

            HttpStringContent putContent2 = new HttpStringContent(
                "world",
                UnicodeEncoding.Utf8,
                "text/plain");

            putContent2.Headers.Add("Content-Range", "bytes 6-10/11");

            response = await client.PutAsync(uploadUrl, putContent2);

            responseString = await response.Content.ReadAsStringAsync();

            Debug.WriteLine(responseString);

            response = await client.PutAsync(uploadUrl, putContent1);

            responseString = await response.Content.ReadAsStringAsync();

            Debug.WriteLine(responseString);
        }
        private async void Launch_Click(object sender, RoutedEventArgs e)
        {
            if (FlickrClientID.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client ID.", NotifyType.StatusMessage);
            }
            else if (FlickrCallbackUrl.Text == "")
            {
                rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
            }
            else if (FlickrClientSecret.Text == "")
            {
                rootPage.NotifyUser("Please enter an Client Secret.", NotifyType.StatusMessage);
            }

            try
            {
                // Acquiring a request token
                TimeSpan SinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
                Random   Rand       = new Random();
                String   FlickrUrl  = "https://secure.flickr.com/services/oauth/request_token";
                Int32    Nonce      = Rand.Next(1000000000);

                // Compute base signature string and sign it.
                // This is a common operation that is required for all requests even after the token is obtained.
                // Parameters need to be sorted in alphabetical order
                // Keys and values should be URL Encoded.
                String SigBaseStringParams = "oauth_callback=" + Uri.EscapeDataString(FlickrCallbackUrl.Text);
                SigBaseStringParams += "&" + "oauth_consumer_key=" + FlickrClientID.Text;
                SigBaseStringParams += "&" + "oauth_nonce=" + Nonce.ToString();
                SigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
                SigBaseStringParams += "&" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds);
                SigBaseStringParams += "&" + "oauth_version=1.0";
                String SigBaseString = "GET&";
                SigBaseString += Uri.EscapeDataString(FlickrUrl) + "&" + Uri.EscapeDataString(SigBaseStringParams);

                IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(FlickrClientSecret.Text + "&", BinaryStringEncoding.Utf8);
                MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
                CryptographicKey     MacKey           = HmacSha1Provider.CreateKey(KeyMaterial);
                IBuffer DataToBeSigned  = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8);
                IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
                String  Signature       = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

                FlickrUrl += "?" + SigBaseStringParams + "&oauth_signature=" + Uri.EscapeDataString(Signature);
                string GetResponse = await SendDataAsync(FlickrUrl);

                rootPage.NotifyUser("Received Data: " + GetResponse, NotifyType.StatusMessage);


                if (GetResponse != null)
                {
                    String   oauth_token        = null;
                    String   oauth_token_secret = null;
                    String[] keyValPairs        = GetResponse.Split('&');

                    for (int i = 0; i < keyValPairs.Length; i++)
                    {
                        String[] splits = keyValPairs[i].Split('=');
                        switch (splits[0])
                        {
                        case "oauth_token":
                            oauth_token = splits[1];
                            break;

                        case "oauth_token_secret":
                            oauth_token_secret = splits[1];
                            break;
                        }
                    }

                    if (oauth_token != null)
                    {
                        FlickrUrl = "https://secure.flickr.com/services/oauth/authorize?oauth_token=" + oauth_token + "&perms=read";
                        System.Uri StartUri = new Uri(FlickrUrl);
                        System.Uri EndUri   = new Uri(FlickrCallbackUrl.Text);

                        rootPage.NotifyUser("Navigating to: " + FlickrUrl, NotifyType.StatusMessage);
                        WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                            WebAuthenticationOptions.None,
                            StartUri,
                            EndUri);

                        if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                        {
                            OutputToken(WebAuthenticationResult.ResponseData.ToString());
                        }
                        else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                        {
                            OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                        }
                        else
                        {
                            OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                        }
                    }
                }
            }
            catch (Exception Error)
            {
                rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
            }
        }
Пример #20
0
        //private async void button1_Click(object sender, RoutedEventArgs e)

        public async void GetGoogleAuth()

        {
            //using Windows.Security.Authentication.Web;

            var googleUrl = new System.Text.StringBuilder();

            googleUrl.Append("https://accounts.google.com/o/oauth2/auth?client_id=");

            googleUrl.Append(Uri.EscapeDataString("960919841378-usr76hbavemtf6ired4c6j40nre7ag3d.apps.googleusercontent.com"));

            googleUrl.Append("&scope=openid%20email%20profile");

            googleUrl.Append("&redirect_uri=");

            googleUrl.Append(Uri.EscapeDataString("urn:ietf:wg:oauth:2.0:oob:auto"));

            googleUrl.Append("&response_type=code");

            googleUrl.Append("&include_granted_scopes=true");



            string endURL = "https://accounts.google.com/o/oauth2/approval";



            Uri startURI = new Uri(googleUrl.ToString());

            Uri endURI = new Uri(endURL);

            string result = string.Empty;

            try

            {
                WebAuthenticationResult webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startURI, endURI);

                switch (webAuthenticationResult.ResponseStatus)

                {
                // Successful authentication.

                case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success:

                    wbVewPostAuthentication.Navigate(new Uri("https://msdn.microsoft.com/en-us/dn308572"));

                    break;

                // HTTP error.

                case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp:

                    result = webAuthenticationResult.ResponseErrorDetail.ToString();

                    break;

                default:

                    result = webAuthenticationResult.ResponseData.ToString();

                    break;
                }

                if (!string.IsNullOrWhiteSpace(result))
                {
                    wbVewPostAuthentication.NavigateToString(result);
                }
            }

            catch (Exception ex)

            {
                result = ex.Message;
            }
        }
Пример #21
0
        public static async Task <AuthResponse> AuthenticateAsync(ContentDialog userCancelDialog = null, ContentDialog errorHttpDialog = null)
        {
            WebAuthenticationResult authenticationResult = null;

            try
            {
                authenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.UseTitle,
                    new Uri(
                        $"{Client.AuthUri}?client_id={Client.ClientId}" +
                        $"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&scope=https://www.googleapis.com/auth/youtube"),
                    new Uri("https://accounts.google.com/o/oauth2/approval"));
            }
            catch (FileNotFoundException)
            {
                await errorHttpDialog?.ShowAsync();

                return(null);
            }

            string authorizationCode = string.Empty;

            switch (authenticationResult.ResponseStatus)
            {
            case WebAuthenticationStatus.Success:
                authorizationCode = authenticationResult.ResponseData;
                authorizationCode = authorizationCode.Substring(13);
                break;

            case WebAuthenticationStatus.UserCancel:
                await userCancelDialog?.ShowAsync();

                return(null);

            case WebAuthenticationStatus.ErrorHttp:
                await errorHttpDialog?.ShowAsync();

                return(null);

            default:
                throw new ArgumentOutOfRangeException();
            }

            var pairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("code", authorizationCode),
                new KeyValuePair <string, string>("client_id", Client.ClientId),
                new KeyValuePair <string, string>("client_secret", Client.ClientSecret),
                new KeyValuePair <string, string>("redirect_uri", Client.RedirectUris[0]),
                new KeyValuePair <string, string>("grant_type", "authorization_code")
            };

            var httpClient  = new HttpClient();
            var httpContent = new HttpFormUrlEncodedContent(pairs);

            try
            {
                var httpResponse = await httpClient.PostAsync(Client.TokenUri, httpContent);

                if (httpResponse.IsSuccessStatusCode)
                {
                    string contentResponse = await httpResponse.Content.ReadAsStringAsync();

                    var authResponse = JsonConvert.DeserializeObject <AuthResponse>(contentResponse);
                    return(authResponse);
                }
                else
                {
                    await errorHttpDialog?.ShowAsync();
                }
            }
            catch
            {
                await errorHttpDialog?.ShowAsync();
            }

            return(null);
        }
Пример #22
0
        void LoginPage_BackKeyPress(object sender, global::System.ComponentModel.CancelEventArgs e)
        {
            WebAuthenticationResult result = new WebAuthenticationResult("", WebAuthenticationStatus.UserCancel, 0u);

            WebAuthenticationResultSource.TrySetResult(result);
        }
Пример #23
0
        /// <summary>
        /// The authenticate async.
        /// </summary>
        /// <param name="claims">
        /// The claims.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="SecurityException">Thrown when authentication fails
        /// </exception>
        public async Task <string> AuthenticateAsync(string[] claims)
        {
            string savedToken;

            if (this.dataStorage.TryRestore(this.Name, out savedToken))
            {
                this.LogToConsole(string.Format("Using saved token: {0}", savedToken));
                return(savedToken);
            }

            var claimsExpanded = claims.Select(claim => string.Format(IdentityClaim, claim)).ToArray();

            var startUri = new Uri(
                string.Format(GoogleUrl, ClientId, RedirectUrl, string.Join(",", claimsExpanded)), UriKind.Absolute);

            this.LogToConsole(string.Format("Attemping to authenticate to URL {0}", startUri));

            WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
                WebAuthenticationOptions.None,
                startUri,
                new Uri(RedirectUrl, UriKind.Absolute));

            if (result.ResponseStatus == WebAuthenticationStatus.Success)
            {
                this.LogToConsole("Successfully authenticated.");
                var results = result.ResponseData.Split('=');
                var code    = results[1];

                this.LogToConsole(string.Format("Received Google code {0}", code));

                var client  = new HttpClient();
                var request = new HttpRequestMessage(HttpMethod.Post, OAuthUrl);

                this.LogToConsole(string.Format("Attempting to retreive token from {0}", OAuthUrl));

                var content = string.Format(OAuthPost, code, ClientId, ClientSecret, RedirectUrl);

                this.LogToConsole(string.Format("Request content: \n{0}", content));

                request.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)));
                request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                HttpResponseMessage response = await client.SendAsync(request);

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

                if (!string.IsNullOrWhiteSpace(responseContent))
                {
                    this.LogToConsole(
                        string.Format("Received content from authentication post: \n{0}", responseContent));

                    var jsonObject  = JsonObject.Parse(responseContent);
                    var accessToken = jsonObject["access_token"].GetString();
                    var expires     = jsonObject["expires_in"].GetNumber();
                    var expiration  = DateTime.UtcNow.AddSeconds(expires);

                    if (!string.IsNullOrWhiteSpace(accessToken))
                    {
                        this.LogToConsole(string.Format("Saved access token {0} with expiration UTC {1}.", accessToken, expiration));
                        this.dataStorage.Save(this.Name, expiration, accessToken);
                        return(accessToken);
                    }

                    this.LogToConsole("No access token found.");
                    throw new SecurityException("Authentication failed: unable to extract the access token.");
                }

                this.LogToConsole("No response received");
                throw new SecurityException("Authentication failed: no response from the server.");
            }

            this.LogToConsole("Authentication attempt was not successful.");
            throw new SecurityException(string.Format("Authentication failed: {0}", result.ResponseErrorDetail));
        }
Пример #24
0
        public async Task <WSAFacebookLoginResult> Login(List <string> permissions)
        {
            WSAFacebookLoginResult loginResult = new WSAFacebookLoginResult();

            try
            {
                Logout(false);

                string requestPermissions = "public_profile";

                if (permissions != null && permissions.Count > 0)
                {
                    requestPermissions = string.Join(",", permissions);
                }

                string accessToken = string.Empty;

#if UNITY_WSA_10_0
                Uri appCallbackUri = new Uri("ms-app://" + _packageSID);

                Uri requestUri = new Uri(
                    string.Format("https://www.facebook.com/dialog/oauth?client_id={0}&response_type=token&redirect_uri={1}&scope={2}",
                                  _facebookAppId, appCallbackUri, requestPermissions));

                WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, appCallbackUri);

                if (result.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    Match match = Regex.Match(result.ResponseData, "access_token=(.+)&");

                    accessToken = match.Groups[1].Value;
                }
#else
                if (_dxSwapChainPanel != null)
                {
                    string requestUri = string.Format("https://www.facebook.com/dialog/oauth?client_id={0}&response_type=token&redirect_uri={1}&scope={2}",
                                                      _facebookAppId, WSAFacebookConstants.WebRedirectUri, requestPermissions);

                    FacebookLogin dialog = new FacebookLogin(Screen.width, Screen.height);

                    accessToken = await dialog.Show(requestUri, WSAFacebookConstants.LoginDialogResponseUri, _dxSwapChainPanel);
                }
#endif

                if (!string.IsNullOrEmpty(accessToken))
                {
                    _accessToken = accessToken;
                    IsLoggedIn   = true;

                    try
                    {
                        StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(_savedDataFilename, CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteTextAsync(file, _accessToken);
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception e)
            {
                IsLoggedIn = false;
                loginResult.ErrorMessage = e.Message;
            }

            loginResult.Success     = IsLoggedIn;
            loginResult.AccessToken = !string.IsNullOrWhiteSpace(_accessToken) ? _accessToken : null;

            return(loginResult);
        }
Пример #25
0
        private async void Scrobble_Click_1(object sender, RoutedEventArgs e)
        {
            if (Security._vault.RetrieveAll().Count == 0)
            {
                Globalv.session_key = null;
                Scrobble.SetValue(AutomationProperties.NameProperty, "Last.fm Connect");
                justLoggedOut = false;
            }
            else
            {
                PasswordCredential rt = Security._vault.Retrieve("Session Key", "user");
                rt.RetrievePassword();
                Globalv.session_key = rt.Password;
                //sign out

                Security._vault.Remove(rt);
                Globalv.session_key = null;
                Scrobble.SetValue(AutomationProperties.NameProperty, "Last.fm Connect");
                justLoggedOut = true;
            }
            if (Globalv.session_key == null && justLoggedOut == false)
            {
                String lfmURL = "https://www.last.fm/api/auth/?api_key=" + Globalv.lfm_api_key + "&cb=" + EndUri;

                System.Uri StartUri = new Uri(lfmURL);

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                    WebAuthenticationOptions.None,
                    StartUri,
                    EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    //get and save lfm session key
                    string[] responseData = WebAuthenticationResult.ResponseData.ToString().Split('?');
                    string   token        = responseData[1].Substring(6);

                    HttpClient            cli        = new HttpClient();
                    string                getsk_sig  = "api_key" + Globalv.lfm_api_key + "methodauth.getSessiontoken" + token + "0e6e780c3cfa3faedf0c58d5aa6de92f";
                    HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm("MD5");
                    CryptographicHash     objHash    = objAlgProv.CreateHash();
                    IBuffer               buffSig    = CryptographicBuffer.ConvertStringToBinary(getsk_sig, BinaryStringEncoding.Utf8);
                    objHash.Append(buffSig);
                    IBuffer buffSighash = objHash.GetValueAndReset();

                    string api_sig = CryptographicBuffer.EncodeToHexString(buffSighash);

                    string get_sk         = @"http://ws.audioscrobbler.com/2.0/?method=auth.getSession&api_key=" + Globalv.lfm_api_key + "&api_sig=" + api_sig + "&token=" + token;
                    HttpResponseMessage r = await cli.GetAsync(get_sk);

                    string xml_resp = await r.Content.ReadAsStringAsync();

                    using (XmlReader rd = XmlReader.Create(new StringReader(xml_resp)))
                    {
                        rd.ReadToFollowing("key");

                        Globalv.session_key = rd.ReadElementContentAsString();
                        var c = new PasswordCredential("Session Key", "user", Globalv.session_key);
                        Mu3.Security._vault.Add(c);

                        justLoggedOut = false;
                        Scrobble.SetValue(AutomationProperties.NameProperty, "Last.fm Signout");

                        /*
                         * PasswordCredential rt = Security._vault.Retrieve("Session Key", "user");
                         * rt.RetrievePassword();
                         * MessageDialog m = new MessageDialog(rt.Password);
                         * await m.ShowAsync();
                         */
                    }
                    //MessageDialog m1 = new MessageDialog(Globalv.session_key);
                    //await m1.ShowAsync();
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    MessageDialog m = new MessageDialog("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                    await m.ShowAsync();
                }
                else
                {
                    MessageDialog m = new MessageDialog("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                    await m.ShowAsync();
                }
            }
        }
Пример #26
0
        public async System.Threading.Tasks.Task<bool> LoginToGoogle(String gaJSON)
        {
            if (gaJSON.Length == 0)
            {
                try
                {
                    // Generates state and PKCE values.
                    string state = randomDataBase64url(32);
                    string code_verifier = randomDataBase64url(32);
                    string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
                    const string code_challenge_method = "S256";

                    // Stores the state and code_verifier values into local settings.
                    // Member variables of this class may not be present when the app is resumed with the
                    // authorization response, so LocalSettings can be used to persist any needed values.
                    ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                    localSettings.Values["state"] = state;
                    localSettings.Values["code_verifier"] = code_verifier;

                    // Creates the OAuth 2.0 authorization request.
                    string authorizationRequest = string.Format("{0}?access_type=offline&response_type=code&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
                        authorizationEndpoint,
                        System.Uri.EscapeDataString(redirectURI),
                        clientID,
                        state,
                        code_challenge,
                        code_challenge_method);

                    // Opens the Authorization URI in the browser


                    WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                            WebAuthenticationOptions.None,
                                            new Uri(authorizationRequest),
                                            new Uri(redirectURI));
                    if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                    {
                        Uri authorizationResponse = new Uri(WebAuthenticationResult.ResponseData.ToString());
                        string queryString = authorizationResponse.Query;
                        tokenString = queryString.Split('=')[1];
                        Debug.WriteLine("MainPage received authorizationResponse: " + authorizationResponse);

                        // Parses URI params into a dictionary
                        // ref: http://stackoverflow.com/a/11957114/72176

                        Dictionary<string, string> queryStringParams =
                                queryString.Substring(1).Split('&')
                                     .ToDictionary(c => c.Split('=')[0],
                                                   c => Uri.UnescapeDataString(c.Split('=')[1]));
                        if (queryStringParams.ContainsKey("error"))
                        {
                            Debug.WriteLine(String.Format("OAuth authorization error: {0}.", queryStringParams["error"]));
                            return false;
                        }

                        if (!queryStringParams.ContainsKey("code")
                            || !queryStringParams.ContainsKey("state"))
                        {
                            Debug.WriteLine("Malformed authorization response. " + queryString);
                            return false;
                        }

                        // Gets the Authorization code & state
                        string code = queryStringParams["code"];
                        string incoming_state = queryStringParams["state"];

                        // Retrieves the expected 'state' value from local settings (saved when the request was made).
                        string expected_state = (String)localSettings.Values["state"];

                        // Compares the receieved state to the expected value, to ensure that
                        // this app made the request which resulted in authorization
                        if (incoming_state != expected_state)
                        {
                            Debug.WriteLine(String.Format("Received request with invalid state ({0})", incoming_state));
                            return false;
                        }
                        // Resets expected state value to avoid a replay attack.
                        localSettings.Values["state"] = null;

                        // Authorization Code is now ready to use!
                        Debug.WriteLine(Environment.NewLine + "Authorization code: " + code);
                        code_verifier = (String)localSettings.Values["code_verifier"];
                        if (await performCodeExchangeAsync(code, code_verifier))
                        {
                            return createCredential();
                        }
                        else
                        {
                            return false;
                        };

                    }
                    else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                    {
                        return false;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception Error)
                {
                    Debug.WriteLine(Error.InnerException);
                    return false;
                }

            }
            else
            {
                if (await refreshToken(gaJSON))
                {
                    return createCredential();
                }
                else
                {
                    return false;
                }
            }

            
        }
 internal WebAuthenticationResultAdapter( WebAuthenticationResult result )
 {
     Contract.Requires( result != null );
     this.result = result;
 }
Пример #28
0
        private async void Launch_Click(object sender, RoutedEventArgs e)
        {
            if (GoogleCallbackUrl.Text == "")
            {
                rootPage.NotifyUser("Please enter an Callback URL.", NotifyType.StatusMessage);
            }

            try
            {
                String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=" + ClientID + "&redirect_uri=" + Uri.EscapeDataString(GoogleCallbackUrl.Text) + "&response_type=code&scope=" + Uri.EscapeDataString("https://www.googleapis.com/auth/youtube.upload") + "+" + Uri.EscapeDataString("https://www.googleapis.com/auth/youtube") + "+" + Uri.EscapeDataString("https://www.googleapis.com/auth/youtubepartner");

                Uri StartUri = new Uri(GoogleURL);
                // When using the desktop flow, the success code is displayed in the html title of this end uri
                Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval");

                rootPage.NotifyUser("Navigating to: " + GoogleURL, NotifyType.StatusMessage);

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, StartUri, EndUri);

                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    OutputToken(WebAuthenticationResult.ResponseData.ToString());
                    var autorizationCode = WebAuthenticationResult.ResponseData.Substring(13);
                    var pairs            = new Dictionary <string, string>();
                    pairs.Add("code", autorizationCode);
                    pairs.Add("client_id", ClientID);
                    pairs.Add("client_secret", ClientSecret);
                    pairs.Add("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
                    pairs.Add("grant_type", "authorization_code");

                    var formContent = new HttpFormUrlEncodedContent(pairs);

                    var client = new Windows.Web.Http.HttpClient();
                    var httpResponseMessage = await client.PostAsync(new Uri("https://accounts.google.com/o/oauth2/token"), formContent);

                    Response = await httpResponseMessage.Content.ReadAsStringAsync();
                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    OutputToken("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    OutputToken("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
                }
                int pFrom = Response.IndexOf("\"access_token\": ") + "\"access_token\": ".Length;
                int pTo   = Response.LastIndexOf("\"expires_in\":");

                this.Token_Access = Response.Substring(pFrom, pTo - pFrom).Replace("\"", "").Replace(",", "").Replace("\n", "").Trim();

                pFrom             = Response.IndexOf("\"refresh_token\": ") + "\"refresh_token\": ".Length;
                pTo               = Response.LastIndexOf("\"scope\"");
                this.Token_Reresh = Response.Substring(pFrom, pTo - pFrom).Replace("\"", "").Replace(",", "").Replace("\n", "").Trim();

                await Task.Run(ShowBasicUserInfo);
            }
            catch (Exception Error)
            {
                rootPage.NotifyUser(Error.Message, NotifyType.ErrorMessage);
            }

            if (this.ChannelTitle != "" || this.ChannelTitle != null)
            {
                LoginNameTextBlock.Text = ChannelTitle;
            }

            if (this.Thumbnail_uri != "" || this.Thumbnail_uri != null)
            {
                Image img = new Image();
                img.Source          = new BitmapImage(new Uri(this.Thumbnail_uri));
                ImgThumbnail.Source = img.Source;
            }
        }