//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; } }
/// <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("Exception occurred during login flow", LoggingLevel.Critical); LoggingService.Log(ex, LoggingLevel.Critical); 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(); } }
private async void LaunchServer() { ApplicationData.Current.LocalSettings.Values["PackageSid"] = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper(); Monitor.Text = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper(); await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); }
public async Task LoginOauth() { if (string.IsNullOrEmpty(Server)) { return; } IsLoading = true; try { var appRegistration = await GetAppRegistration(); var authClient = new AuthenticationClient(appRegistration); var oauthUrl = authClient.OAuthUrl((string.Format(_serverRedirect, Server))); var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(oauthUrl), new System.Uri(string.Format(_serverRedirect, Server))); string result; string code = ""; switch (webAuthenticationResult.ResponseStatus) { case Windows.Security.Authentication.Web.WebAuthenticationStatus.Success: // Successful authentication. result = webAuthenticationResult.ResponseData.ToString(); var query = QueryString.Parse(result); var testCode = query.FirstOrDefault(); code = testCode?.Value; break; case Windows.Security.Authentication.Web.WebAuthenticationStatus.ErrorHttp: // HTTP error. result = webAuthenticationResult.ResponseErrorDetail.ToString(); break; default: // Other error. result = webAuthenticationResult.ResponseData.ToString(); break; } if (string.IsNullOrEmpty(code)) { // TODO Add error screen } else { var auth = await authClient.ConnectWithCode(code, string.Format(_serverRedirect, Server)); SettingsService.UserAuth = auth; var client = new MastodonClient(appRegistration, auth); var account = await client.GetCurrentUser(); SettingsService.UserAccount = account; SettingsService.Instance.ServerInstance = Server; IsLoggedIn = true; if (App.IsTenFoot) { // NavigationService.Navigate(typeof(XboxViews.MainPage)); } else { Views.Shell.Instance.ViewModel.IsLoggedIn = true; NavigationService.Navigate(typeof(Views.MainPage)); } } } catch (Exception e) { await MessageDialogMaker.SendMessageDialogAsync(e.Message, false); } //var authUri = $"https://{Server}/oauth/authorize?response_type=code&client_id=" IsLoading = false; }
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" }); }
public override string GetRedirectUriAsString(Uri redirectUri, CallState callState) { return(ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri) ? WebAuthenticationBroker.GetCurrentApplicationCallbackUri().OriginalString : redirectUri.OriginalString); }
private async Task <OAuthRequestToken> GetRequestToken() { var f = new Flickr("dbc316af64fb77dae9140de64262da0a", "0781969a058a2745"); return(await f.OAuthRequestTokenAsync(WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString())); }
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); }
public async Task MashapeTwitterLogin() { //NOTE: Check App.xaml.cs for the variables that you need to fill in var targeturi = "https://twitter.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; searchBox.Visibility = Windows.UI.Xaml.Visibility.Visible; searchButton.Visibility = Windows.UI.Xaml.Visibility.Visible; 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"; } }
private async void MainPage_Loaded(object sender, RoutedEventArgs e) { var res = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri($"https://github.com/login/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={Uri.EscapeUriString(redirect.ToString())}&scope={SCOPE}"), redirect); }
private void SetRedirectUriRequestParameter() { this.redirectUriRequestParameter = ReferenceEquals(this.redirectUri, Constant.SsoPlaceHolderUri) ? WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri : this.redirectUri.AbsoluteUri; }
/// <summary> /// Creates a new instance of the Auth0 OIDC Client. /// </summary> /// <param name="options">The <see cref="Auth0ClientOptions"/> specifying the configuration for the Auth0 OIDC Client.</param> public Auth0Client(Auth0ClientOptions options) : base(options, "uwp") { options.Browser = options.Browser ?? new WebAuthenticationBrokerBrowser(); options.RedirectUri = options.RedirectUri ?? WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri; }
public async Task <bool> SignInWithGoogleAsync() { if (DateTimeOffset.UtcNow < TokenLastAccess.AddSeconds(3600)) { accessToken = GetTokenFromVault(TokenTypes.AccessToken); IsAuthorized = true; return(true); } else { string token = GetTokenFromVault(TokenTypes.RefreshToken); if (!string.IsNullOrWhiteSpace(token)) { StringContent content = new StringContent($"client_secret={ClientSecret}&refresh_token={token}&client_id={ClientID}&grant_type=refresh_token", Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage response = await httpClient.PostAsync(TokenEndpoint, content); string responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { JsonObject tokens = JsonObject.Parse(responseString); accessToken = tokens.GetNamedString("access_token"); foreach (var item in vault.RetrieveAll().Where((x) => x.Resource == TokenTypes.AccessToken.ToString())) { vault.Remove(item); } vault.Add(new PasswordCredential(TokenTypes.AccessToken.ToString(), "MyApp", accessToken)); TokenLastAccess = DateTimeOffset.UtcNow; IsAuthorized = true; return(true); } } } string state = RandomDataBase64(32); string code_verifier = RandomDataBase64(32); string code_challenge = Base64UrlEncodeNoPadding(Sha256(code_verifier)); const string code_challenge_method = "S256"; string authString = "https://accounts.google.com/o/oauth2/auth?client_id=" + ClientID; authString += "&scope=profile"; authString += $"&redirect_uri={RedirectURI}"; authString += $"&state={state}"; authString += $"&code_challenge={code_challenge}"; authString += $"&code_challenge_method={code_challenge_method}"; authString += "&response_type=code"; var receivedData = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.UseTitle, new Uri(authString), new Uri(ApprovalEndpoint)); switch (receivedData.ResponseStatus) { case WebAuthenticationStatus.Success: await GetAccessToken(receivedData.ResponseData.Substring(receivedData.ResponseData.IndexOf(' ') + 1), state, code_verifier); return(true); case WebAuthenticationStatus.ErrorHttp: Debug.WriteLine($"HTTP error: {receivedData.ResponseErrorDetail}"); return(false); case WebAuthenticationStatus.UserCancel: default: return(false); } }
private static Uri GetRedirectUri(Uri redirectUri) { return(redirectUri ?? WebAuthenticationBroker.GetCurrentApplicationCallbackUri()); }
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; } } }
public async Task <AuthenticationMessage> AuthenticateAsync() { var success = true; var errorMessage = string.Empty; if (!NetworkStatusManager.Current.IsConnected()) { return(new AuthenticationMessage(false, "There appears to be no network connection!")); } try { var scopes = new List <MSAScope> { MSAScope.Basic, MSAScope.Emails, MSAScope.OfflineAccess, MSAScope.SignIn }; var authUri = this.apiClient.RetrieveAuthenticationUri(scopes); var result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, new Uri(authUri), new Uri(ApiClient.RedirectUri)); if (result.ResponseStatus == WebAuthenticationStatus.Success) { if (!string.IsNullOrWhiteSpace(result.ResponseData)) { var responseUri = new Uri(result.ResponseData); if (responseUri.LocalPath.StartsWith("/oauth20_desktop.srf", StringComparison.OrdinalIgnoreCase)) { var error = responseUri.ExtractQueryValue("error"); if (string.IsNullOrWhiteSpace(error)) { var authCode = responseUri.ExtractQueryValue("code"); var msa = await this.apiClient.ExchangeAuthCodeAsync(authCode); if (msa != null) { await this.profileData.SetAccountAsync(msa); } } else { errorMessage = error; } } } } else { if (result.ResponseStatus != WebAuthenticationStatus.UserCancel) { errorMessage = "Sign in was not successful. Please try again."; } await this.profileData.ClearAsync(); success = false; } } catch (Exception ex) { EventLogger.Current.WriteWarning(ex.ToString()); success = false; } return(new AuthenticationMessage(success, errorMessage)); }
public async Task <WebAuthenticationResult> Authenticate(WebAuthenticationOptions webAuthenticationOptions, Uri url, Uri callback) { WebAuthenticationBroker.AuthenticateAndContinue(url, callback, null, webAuthenticationOptions); return(null); }
public Uri Get() { return(WebAuthenticationBroker.GetCurrentApplicationCallbackUri()); }
private async void SignOut_Clicked(object sender, RoutedEventArgs e) { var userResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, _logoutUrl); resultTxt.Text = $"{userResult.ResponseStatus}"; }
/// <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); }
/// <summary> /// Restituisce la Redirect Uri dell'applicazione da impostare sul portale di Azure /// </summary> public static string GetRedirectUri() { return(string.Format("ms-appx-web://microsoft.aad.brokerplugin/{0}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host).ToUpper()); }
public MainPageViewModel() { string URI = string.Format("ms-appx-web://Microsoft.AAD.BrokerPlugIn/{0}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); publicClientApp = PublicClientApplicationBuilder.Create("[Client ID]") .WithAuthority(AzureCloudInstance.AzurePublic, "common") .WithRedirectUri(URI) .Build(); }
private async void DoAuthFlow(LoginOptions loginOptions) { loginOptions.DisplayType = LoginOptions.DefaultStoreDisplayType; var loginUri = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions)); var callbackUri = new Uri(loginOptions.CallbackUrl); OAuth2.ClearCookies(loginOptions); WebAuthenticationResult webAuthenticationResult; try { PlatformAdapter.SendToCustomLogger( "AccountPage.DoAuthFlow - calling WebAuthenticationBroker.AuthenticateAsync()", 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) { PlatformAdapter.SendToCustomLogger("AccountPage.StartLoginFlow - Exception occured", LoggingLevel.Critical); PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical); DisplayErrorDialog(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) { DisplayErrorDialog(LocalizedStrings.GetString("generic_authentication_error")); SetupAccountPage(); } else { AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1)); PlatformAdapter.SendToCustomLogger("AccountPage.DoAuthFlow - calling EndLoginFlow()", LoggingLevel.Verbose); PlatformAdapter.Resolve <IAuthHelper>().EndLoginFlow(loginOptions, authResponse); } } else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel) { SetupAccountPage(); } else { DisplayErrorDialog(LocalizedStrings.GetString("generic_error")); SetupAccountPage(); } }
private async Task <BrowserResult> InvokeAsyncCore(BrowserOptions options, bool silentMode) { var wabOptions = WebAuthenticationOptions.None; if (enableWindowsAuthentication) { wabOptions |= WebAuthenticationOptions.UseCorporateNetwork; } if (silentMode) { wabOptions |= WebAuthenticationOptions.SilentMode; } WebAuthenticationResult wabResult; try { 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.ResponseStatus == WebAuthenticationStatus.Success) { return(new BrowserResult { ResultType = BrowserResultType.Success, Response = wabResult.ResponseData }); } else if (wabResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { return(new BrowserResult { ResultType = BrowserResultType.HttpError, Error = string.Concat(wabResult.ResponseErrorDetail.ToString()) }); } else if (wabResult.ResponseStatus == WebAuthenticationStatus.UserCancel) { return(new BrowserResult { ResultType = BrowserResultType.UserCancel }); } else { return(new BrowserResult { ResultType = BrowserResultType.UnknownError, Error = "Invalid response from WebAuthenticationBroker" }); } }
public async static Task <TokenResponse> DoImplicitFlowAsync(Uri endpoint, string clientId, string scope) { return(await DoImplicitFlowAsync(endpoint, clientId, scope, WebAuthenticationBroker.GetCurrentApplicationCallbackUri())); }
/// <summary> /// Launch the Web Authentication Broker and prompt user to login for access token and refresh token /// </summary> public static async void LoginSpotify() { var client = new RestClient() { BaseUrl = AccountUri, Timeout = 5000 }; var loginRequest = new RestRequest("authorize", Method.GET); loginRequest.AddParameter("client_id", ClientId); loginRequest.AddParameter("response_type", "code"); loginRequest.AddParameter("redirect_uri", RedirectUri.ToString()); var loginUri = client.Execute(loginRequest).ResponseUri; var result = ""; try { var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync( Windows.Security.Authentication.Web.WebAuthenticationOptions.None, loginUri, RedirectUri); switch (webAuthenticationResult.ResponseStatus) { case WebAuthenticationStatus.Success: result = webAuthenticationResult.ResponseData.ToString(); break; case WebAuthenticationStatus.ErrorHttp: result = webAuthenticationResult.ResponseErrorDetail.ToString(); break; case WebAuthenticationStatus.UserCancel: result = "Login Canceled"; break; default: result = webAuthenticationResult.ResponseData.ToString(); break; } } catch (Exception e) { result = e.Message; } Debug.WriteLine(result); var authenticationCode = ""; if (result.Contains("https://example.com/callback/")) { authenticationCode = result.Remove(0, RedirectUri.ToString().Length + 6); Debug.WriteLine(authenticationCode); } else { authenticationCode = string.Empty; //TODO: Handle the error where login is not successful. } if (string.IsNullOrEmpty(authenticationCode)) { return; } var accessTokenRequest = new RestRequest("api/token", Method.POST); var idSecretPair = $"{ClientId}:{ClientSecret}"; var requestHeader = $"Basic {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(idSecretPair))}"; accessTokenRequest.AddHeader("Authorization", requestHeader); accessTokenRequest.AddParameter("grant_type", "authorization_code"); accessTokenRequest.AddParameter("code", authenticationCode); accessTokenRequest.AddParameter("redirect_uri", RedirectUri.ToString()); var accessTokenResponse = client.Execute(accessTokenRequest); Debug.WriteLine(accessTokenResponse.StatusCode); Debug.WriteLine(accessTokenResponse.Content); var credentialDetials = JsonConvert.DeserializeObject <SpotifyCredential>(accessTokenResponse.Content); //TODO: Save the spotify credentials to device for further consumption }
/// <summary> /// Called when an element is changed. /// </summary> /// <param name="e">Event arguments.</param> protected override async void OnElementChanged( ElementChangedEventArgs <Page> e) { base.OnElementChanged(e); // Use a stored account if available, otherwise show the authentication UI // FIXME: for now, we ask for a token every time so as not to handle the case where the token is expired. // Consider implementing refresh tokens or RFC 7662 (token introspection) in the future /* Account appAccount = OAuthAccountStoreFactory.Create(this.Context) * .FindAccountsForService(App.AppName).FirstOrDefault(); * if (appAccount == null) * {*/ // Start the token request using the OAuth 2.0 implicit grant string state = CryptographicBuffer.EncodeToHexString( CryptographicBuffer.GenerateRandom(25)); Uri authorizationURI = new Uri(Config.TellOPConfiguration.OAuth2AuthorizeUrl.ToString() + "?response_type=token&client_id=" + Uri.EscapeDataString(Config.TellOPConfiguration.OAuth2ClientId) + "&redirect_uri=" + Uri.EscapeDataString(Config.TellOPConfiguration.OAuth2RedirectUrl.ToString()) + "&scope=" + Uri.EscapeDataString(Config.TellOPConfiguration.OAuth2Scopes) + "&state=" + state); WebAuthenticationResult authResult; try { authResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authorizationURI, Config.TellOPConfiguration.OAuth2RedirectUrl); switch (authResult.ResponseStatus) { case WebAuthenticationStatus.Success: break; case WebAuthenticationStatus.UserCancel: TellOP.App.LogOnAuthenticationCompletedButNotAuthenticatedAction.Invoke(); return; case WebAuthenticationStatus.ErrorHttp: default: TellOP.App.LogOnAuthenticationErrorAction.Invoke(); return; } } catch (Exception) { TellOP.App.LogOnAuthenticationErrorAction.Invoke(); return; } // Analyze the OAuth 2.0 response data bool stateMatches = false; string accessToken = null; Dictionary <string, string> oauthResponse = new Dictionary <string, string>(); string responseData = authResult.ResponseData; if (responseData.Contains("#")) { responseData = responseData.Split('#')[1]; } string[] oAuthResponseParams = responseData.Split('&'); foreach (string oAuthResponseParam in oAuthResponseParams) { string[] splitParam = oAuthResponseParam.Split('='); if (splitParam.Length != 2) { continue; } // Note: plus signs should be removed from the URI manually as UnescapeDataString does not do that (the // behavior is not standard across all URI schemes). // See <https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring(v=vs.110).aspx> string unescapedParam = Uri.UnescapeDataString(splitParam[1]).Replace('+', ' '); oauthResponse.Add(splitParam[0], unescapedParam); switch (splitParam[0]) { case "state": stateMatches = unescapedParam.Equals(state); break; case "access_token": accessToken = unescapedParam; break; case "token_type": if (!unescapedParam.Equals("Bearer")) { TellOP.App.LogOnAuthenticationErrorAction.Invoke(); return; } break; case "scope": if (!unescapedParam.Equals( Config.TellOPConfiguration.OAuth2Scopes)) { TellOP.App.LogOnAuthenticationErrorAction.Invoke(); return; } break; default: // Nothing to do break; } } if (!stateMatches || string.IsNullOrWhiteSpace(accessToken)) { TellOP.App.LogOnAuthenticationErrorAction.Invoke(); return; } // Create a Xamarin.Auth account and load user data Account authAccount = new Account(null, oauthResponse); await TellOP.App.LoadUserData(authAccount); /*} * else * { * App.LoadUserData(appAccount); * }*/ }
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); } }
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); }