private async void LogoutWabButton_Click(object sender, RoutedEventArgs e) { var options = new OidcClientOptions { Authority = "https://demo.identityserver.io", ClientId = "native.hybrid", Scope = "openid profile api offline_access", RedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri, PostLogoutRedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, Browser = new WabBrowser(enableWindowsAuthentication: false) }; var client = new OidcClient(options); try { await client.LogoutAsync(new LogoutRequest() { BrowserDisplayMode = DisplayMode.Hidden, IdTokenHint = _result.IdentityToken }); } catch (Exception ex) { // TODO: This is never called: See https://github.com/IdentityModel/IdentityModel.OidcClient2/issues/123 } }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); if (ApplicationData.Current.LocalSettings.Values.ContainsKey("RefreshToken")) { string refreshToken = ApplicationData.Current.LocalSettings.Values["RefreshToken"].ToString(); string returnUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); IOneDriveClient client = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(ClientId, returnUrl, Scopes, refreshToken); bool isFolderExisting = true; try { await client.Drive.Root.ItemWithPath("OneDrive Sample").Request().GetAsync(); } catch (OneDriveException exc) { isFolderExisting = false; } if (isFolderExisting) { StorageFile file = await Package.Current.InstalledLocation.GetFileAsync("BackgroundWallpaper.jpg"); using (Stream stream = await file.OpenStreamForReadAsync()) { await client.Drive.Root.ItemWithPath("OneDrive Sample/BackgroundWallpaper.png").Content.Request().PutAsync <Item>(stream); } } } deferral.Complete(); }
/// <summary> /// Performs the first step in the OAuth2 workflow and retreives the auth code /// </summary> /// <param name="authCodeUri">The box api uri to retrieve the auth code. BoxConfig.AuthCodeUri should be used for this field</param> /// <param name="redirectUri">The redirect uri that the page will navigate to after granting the auth code</param> /// <returns></returns> public static async Task <string> GetAuthCode(Uri authCodeUri, Uri redirectUri = null) { Uri callbackUri = redirectUri == null? WebAuthenticationBroker.GetCurrentApplicationCallbackUri() : redirectUri; WebAuthenticationResult war = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, authCodeUri, callbackUri); switch (war.ResponseStatus) { case WebAuthenticationStatus.Success: // grab auth code var response = war.ResponseData; WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(new Uri(response).Query); return(decoder.GetFirstValueByName("code")); case WebAuthenticationStatus.UserCancel: throw new Exception("User Canceled Login"); case WebAuthenticationStatus.ErrorHttp: default: throw new Exception("Error returned by GetAuthCode() : " + war.ResponseStatus.ToString()); } }
private async void PrepareClient() { var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().OriginalString; // Create options for endpoint discovery var options = new OidcClientOptions { Authority = "https://demo.identityserver.io", ClientId = "interactive.confidential", ClientSecret = "secret", Scope = "openid profile email api offline_access", RedirectUri = redirectUri, PostLogoutRedirectUri = redirectUri, ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect, Flow = OidcClientOptions.AuthenticationFlow.AuthorizationCode }; // Create the client. In production application, this is often created and stored // directly in the Application class. _oidcClient = new OidcClient(options); // Invoke Discovery and prepare a request state, containing the nonce. // This is done here to ensure the discovery mechanism is done before // the user clicks on the SignIn button. Since the opening of a web window // should be done during the handling of a user interaction (here it's the button click), // it will be too late to reach the discovery endpoint. // Not doing this could trigger popup blocker mechanisms in browsers. _loginState = await _oidcClient.PrepareLoginAsync(); btnSignin.IsEnabled = true; // Same for logout url. _logoutUrl = new Uri(await _oidcClient.PrepareLogoutAsync(new LogoutRequest())); btnSignout.IsEnabled = true; }
/// <summary> /// Logs in a <see cref="ParseUser" /> using Facebook for authentication. If a user for the /// given Facebook credentials does not already exist, a new user will be created. /// /// The user will be logged in through Facebook's OAuth web flow using the Windows /// WebAuthenticationBroker. /// </summary> /// <param name="permissions">A list of Facebook permissions to request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The user that was either logged in or created.</returns> public static async Task <ParseUser> LogInAsync(IEnumerable <string> permissions, CancellationToken cancellationToken) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); authProvider.Permissions = permissions; authProvider.ResponseUrlOverride = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); Action <Uri> navigate = async uri => { var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, uri); if (result.ResponseStatus != WebAuthenticationStatus.Success) { cts.Cancel(); } else { authProvider.HandleNavigation(new Uri(result.ResponseData)); } }; authProvider.Navigate += navigate; try { return(await ParseUser.LogInWithAsync("facebook", cts.Token)); } finally { authProvider.Navigate -= navigate; authProvider.ResponseUrlOverride = null; } }
private void SetRedirectUriRequestParameter() { if (ReferenceEquals(this.redirectUri, Constant.SsoPlaceHolderUri)) { try { this.redirectUriRequestParameter = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri; } catch (FormatException ex) { // This is the workaround for a bug in managed Uri class of WinPhone SDK which makes it throw UriFormatException when it gets called from unmanaged code. const string CurrentApplicationCallbackUriSetting = "CurrentApplicationCallbackUri"; if (ApplicationData.Current.LocalSettings.Values.ContainsKey(CurrentApplicationCallbackUriSetting)) { this.redirectUriRequestParameter = (string)ApplicationData.Current.LocalSettings.Values[CurrentApplicationCallbackUriSetting]; } else { throw new AdalException(AdalError.NeedToSetCallbackUriAsLocalSetting, AdalErrorMessage.NeedToSetCallbackUriAsLocalSetting, ex); } } } else { this.redirectUriRequestParameter = redirectUri.AbsoluteUri; } }
public async Task <string> LoginAsync() { var clientId = "{0oa1b3kqofpeKGOUb357}"; var url = "https://dev-986035.okta.com/oauth2/default"; var state = GetBase64UrlData(32); var nonce = GetBase64UrlData(12); var codeVerifier = GetBase64UrlData(32); var tmp = CryptographicBuffer.ConvertStringToBinary(codeVerifier, BinaryStringEncoding.Utf8); var codeVerifierBuffer = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256).HashData(tmp); var codeChallenge = GetBase64UrlData(null, codeVerifierBuffer); var absoluteUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri; var callback = Uri.EscapeDataString(absoluteUri); var authorizationRequest = string.Format( "{0}?response_type=id_token&scope=openid profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method=S256&nonce={5}", url, callback, clientId, state, codeChallenge, nonce); var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(authorizationRequest), new Uri(absoluteUri)); if (result.ResponseStatus != WebAuthenticationStatus.Success) { return(null); } var queryParams = result.ResponseData.Split("#?&".ToCharArray()); var idToken = queryParams.FirstOrDefault(p => p.StartsWith("id_token")); return(idToken?.Substring(9)); }
private void OnAuthoirzeDialogClick(object sender, RoutedEventArgs e) { AccessTokenTextBlock.Text = string.Empty; string scope = "public_profile,email"; string fbAppId = "{facebook app id}"; string appId = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().OriginalString; string request = $"https://www.facebook.com/v2.6/dialog/oauth?client_id={fbAppId}&redirect_uri={appId}&response_type=token&scope={scope}&display=popup"; OAuthDialog oauthdialog = new OAuthDialog(); oauthdialog.AuthorizeRedirectChanged += (o, a) => { int idx = a.IndexOf("access_token"); if (idx > 0) { string[] data = a.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries); Dictionary <string, string> returnData = data[1].Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(part => part.Split('=')) .ToDictionary(split => split[0], split => split[1]); AccessTokenTextBlock.Text = returnData["access_token"]; } else { AccessTokenTextBlock.Text = a; } }; oauthdialog.AuthorizeUrl = request; oauthdialog.Show(); }
public MainPage() { this.InitializeComponent(); string SID = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); Debug.WriteLine(SID); }
public async override Task <ServiceInfo> GetServiceInfo( AppConfig appConfig, CredentialCache credentialCache, IHttpProvider httpProvider, ClientType clientType = ClientType.Business) { if (clientType == ClientType.Consumer) { throw new OneDriveException( new Error { Code = OneDriveErrorCode.AuthenticationFailure.ToString(), Message = "AdalServiceInfoProvider only supports Active Directory authentication." }); } var serviceInfo = await base.GetServiceInfo(appConfig, null, httpProvider, clientType); serviceInfo.BaseUrl = appConfig.ActiveDirectoryServiceEndpointUrl; serviceInfo.ServiceResource = appConfig.ActiveDirectoryServiceResource; if (string.IsNullOrEmpty(serviceInfo.ReturnUrl)) { serviceInfo.ReturnUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); } if (serviceInfo.AuthenticationProvider == null) { serviceInfo.AuthenticationProvider = new AdalAuthenticationProvider(serviceInfo); } return(serviceInfo); }
private async Task Login() { //Client ID of the Facebook App (retrieved from the Facebook Developers portal) //Required permissions var scope = "public_profile, email"; var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); var fb = new FacebookClient(); var loginUrl = fb.GetLoginUrl(new { client_id = ClientId, redirect_uri = redirectUri, response_type = "token", scope = scope }); Uri startUri = loginUrl; Uri endUri = new Uri(redirectUri, UriKind.Absolute); #if WINDOWS_PHONE_APP WebAuthenticationBroker.AuthenticateAndContinue(startUri, endUri, null, WebAuthenticationOptions.None); #endif #if WINDOWS_APP WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri); await ParseAuthenticationResult(result); #endif }
/// <summary> /// Obtains the access token necessary to call Office 365 APIs. The access token might be obtained anew, /// or it might be returned from the Windows Azure Active Directory library cache. /// On failure, the method will display a message dialog to the user, and then return null. /// </summary> internal static async Task <string> GetAccessToken(string resourceId) { string authority = string.Format(CultureInfo.InvariantCulture, OAuthUrl, TenantId ?? "common"); AuthenticationContext authContext = new AuthenticationContext(authority); AuthenticationResult result = await authContext.AcquireTokenAsync( resourceId, (string)Application.Current.Resources["ida:ClientID"], WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), PromptBehavior.Auto); if (result.Status == AuthenticationStatus.Succeeded) { SaveInCache("TenantId", result.TenantId); SaveInCache("UserId", result.UserInfo.UserId); return(result.AccessToken); } else { string message = result.Error + ": " + result.ErrorDescription; await ShowErrorMessageAsync(message, "Error issuing an access token. " + message); return(null); } }
/// <summary> /// Begins a server-side authentication flow by navigating the /// <see cref="WebAuthenticationBroker"/> to the <paramref name="startUrl"/>. /// Considers if the <paramref name="useSingleSignOn"/> is being used and calls the /// correct overload of the <see cref="WebAuthenticationBroker"/>. /// </summary> /// <param name="startUrl">The URL that the browser-based control should /// first navigate to in order to start the authenication flow. /// </param> /// <param name="endUrl">The URL that indicates the authentication flow has /// completed. Upon being redirected to any URL that starts with the /// <paramref name="endUrl"/>, the browser-based control must stop navigating and /// return the response data to the <see cref="AuthenticationBroker"/>. /// </param> /// <param name="useSingleSignOn">Indicates if single sign-on should be used so /// that users do not have to re-enter his/her credentials every time. /// </param> /// <returns> /// The <see cref="WebAuthenticationResult"/> returned by the /// <see cref="WebAuthenticationBroker"/>. /// </returns> private Task <string> AuthenticateWithBroker(Uri startUrl, Uri endUrl, bool useSingleSignOn) { Debug.Assert(startUrl != null); Debug.Assert(endUrl != null); if (pendingLoginTask != null) { throw new InvalidOperationException(Resources.IAuthenticationBroker_LoginInProgress); } pendingLoginTask = new TaskCompletionSource <string>(); if (useSingleSignOn) { Uri ssoEndUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); Uri ssoStartUrl = GetUrlWithQueryStringParameter(startUrl, "sso_end_uri", ssoEndUri.AbsoluteUri); WebAuthenticationBroker.AuthenticateAndContinue(ssoStartUrl, null, null, WebAuthenticationOptions.None); } else { WebAuthenticationBroker.AuthenticateAndContinue(startUrl, endUrl, null, WebAuthenticationOptions.None); } return(pendingLoginTask.Task); }
private async void AttemptLogin() { if (_client != null) { return; } if (apiKey == null) { return; } _client = new FacebookClient(); _client.AppId = apiKey.APIKey; _client.AppSecret = apiKey.APISecret; //var scope = "public_profile, email"; var scope = "public_profile,user_friends,email, user_about_me, user_hometown, user_location, user_photos, user_posts, user_status, user_videos, user_website"; var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); var fb = new FacebookClient(); Uri loginUrl = fb.GetLoginUrl(new { client_id = apiKey.APIKey, redirect_uri = redirectUri, response_type = "token", scope = scope }); Uri startUri = loginUrl; Uri endUri = new Uri(redirectUri, UriKind.Absolute); WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri); ParseAuthenticationResult(result); }
public async Task <AccessInformation> AuthRequestAsync() { var callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString().Replace("ms-app://", "https://imacode.ninja/"); var state = Guid.NewGuid(); var requestUri = $"{TokenRequestUrl}?client_id={ClientId}&scope={AuthorizationScopes.ReadWriteSkills} {AuthorizationScopes.ReadModels} {AuthorizationScopes.TestingSkills} &response_type=code&state={state:N}&redirect_uri={callbackUri}"; var result = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, new Uri(requestUri, UriKind.Absolute), new Uri(callbackUri, UriKind.Absolute)); var queryParams = HttpUtility.ParseQueryString(new Uri(result.ResponseData).Query); if (result.ResponseStatus != WebAuthenticationStatus.Success || state.ToString("N") != queryParams["state"]) { return(null); } var authCode = queryParams["code"]; var dictionary = GetCodeDetails("authorization_code", "code", authCode); var authResponse = await new HttpClient().PostAsync(AccessRequestUrl, new FormUrlEncodedContent(dictionary)); if (!authResponse.IsSuccessStatusCode) { return(null); } using (var json = new JsonTextReader(new StreamReader(await authResponse.Content.ReadAsStreamAsync()))) { return(Serializer.Deserialize <AccessInformation>(json)); } }
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); } } }
/// <summary> /// Handles user logout. /// Does this by creating a logout URL and by opening this URL in webauthenticationbroker. /// Set acces token to 0; /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void FBLogout_Click(object sender, RoutedEventArgs e) { if (fbInfo.Values["token"].ToString() != "0") { string tokenValue = fbInfo.Values["token"].ToString(); var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); //await fbClient.DeleteTaskAsync("me/permissions"); Uri startUri = new Uri(@"https://www.facebook.com/logout.php?next=https://facebook.com/&access_token=" + fbClient.AccessToken); Uri endUri = new Uri(redirectUri, UriKind.Absolute); var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); Uri startUri = new Uri(@"https://www.facebook.com/logout.php?next=https://www.facebook.com/&access_token=" + fbClient.AccessToken); Uri endUri = new Uri(redirectUri, UriKind.Absolute); await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, startUri, endUri); this.accessToken = "0"; this.fbInfo.Values["token"] = "0"; fbProfilePic.Visibility = Visibility.Collapsed; } else { var dialog = new MessageDialog("It seems that you're already logged out!"); await dialog.ShowAsync(); } }
private string ParseAuthenticationResult(WebAuthenticationResult result) { string token = ""; switch (result.ResponseStatus) { case WebAuthenticationStatus.ErrorHttp: //Debug.WriteLine("Error"); break; case WebAuthenticationStatus.Success: var pattern = string.Format("{0}#access_token={1}&expires_in={2}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), "(?<access_token>.+)", "(?<expires_in>.+)"); var match = Regex.Match(result.ResponseData, pattern); var access_token = match.Groups["access_token"]; var expires_in = match.Groups["expires_in"]; token = access_token.Value; //TokenExpiry = DateTime.Now.AddSeconds(double.Parse(expires_in.Value)); break; case WebAuthenticationStatus.UserCancel: //Debug.WriteLine("Operation aborted"); break; default: break; } return(token); }
private async Task AuthPocketAsync() { if (!AuthPocketViaSavedAccessToken()) { pocketClient = new PocketClient(Secrets.PocketAPIConsumerKey); Uri callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); RequestToken requestToken = await pocketClient.ObtainRequestTokenAsync( callbackUri); Uri requestUri = pocketClient.ObtainAuthorizeRequestTokenRedirectUri(requestToken, callbackUri); WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateSilentlyAsync(requestUri); if (result.ResponseStatus != WebAuthenticationStatus.Success) { result = await WebAuthenticationBroker.AuthenticateAsync( WebAuthenticationOptions.None, requestUri); } AccessToken token = await pocketClient.ObtainAccessTokenAsync(requestToken); ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; string tokenString = JsonSerializer.Serialize(token); localSettings.Values.Add("accessToken", tokenString); } }
internal async Task <AccountSession> GetAccountSessionAsync() { var returnUrlForRequest = string.IsNullOrEmpty(this.ServiceInfo.ReturnUrl) ? WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString() : this.ServiceInfo.ReturnUrl; var requestUriStringBuilder = new StringBuilder(); requestUriStringBuilder.Append(this.ServiceInfo.AuthenticationServiceUrl); requestUriStringBuilder.AppendFormat("?{0}={1}", Constants.Authentication.RedirectUriKeyName, returnUrlForRequest); requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientIdKeyName, this.ServiceInfo.AppId); requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ScopeKeyName, string.Join("%20", this.ServiceInfo.Scopes)); requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ResponseTypeKeyName, Constants.Authentication.TokenResponseTypeValueName); var requestUri = new Uri(requestUriStringBuilder.ToString()); var authenticationResponseValues = await this.ServiceInfo.WebAuthenticationUi.AuthenticateAsync( requestUri, string.IsNullOrEmpty(this.ServiceInfo.ReturnUrl) ?null : new Uri(this.ServiceInfo.ReturnUrl)); OAuthErrorHandler.ThrowIfError(authenticationResponseValues); return(new AccountSession(authenticationResponseValues, this.ServiceInfo.AppId, AccountType.MicrosoftAccount) { CanSignOut = true }); }
private static async Task <NamedPipeAsAppServiceConnection> BuildConnection(bool launchFullTrust) { try { if (launchFullTrust) { // Launch fulltrust process ApplicationData.Current.LocalSettings.Values["PackageSid"] = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpperInvariant(); await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } var connection = new NamedPipeAsAppServiceConnection(); if (await connection.Connect(@"LOCAL\FilesInteropService_ServerPipe", TimeSpan.FromSeconds(15))) { return(connection); } connection.Dispose(); } catch (Exception ex) { App.Logger.Warn(ex, "Could not initialize FTP connection!"); } return(null); }
private async Task <string> AuthenticateFacebookAsync() { try { var fb = new FacebookClient(); var redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); var loginUri = fb.GetLoginUrl(new { client_id = AppId, redirect_uri = redirectUri, scope = ExtendedPermissions, display = "popup", response_type = "token" }); var callbackUri = new Uri(redirectUri, UriKind.Absolute); var authenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUri, callbackUri); return(ParseAuthenticationResult(fb, authenticationResult)); } catch (Exception ex) { return(ex.Message); } }
public MainPage() { InitializeComponent(); Uri s = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); _redirectUris.Add(SSORedirectUri); _redirectUris.Add("https://MyDirectorySearcherApp"); }
public Scenario1_Facebook() { this.InitializeComponent(); // Use these SIDs to register the app with Facebook. WindowsStoreSidTextBlock.Text = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host; WindowsPhoneStoreSidTextBlock.Text = "feaebe20-b974-4857-a51c-3525e4dfe2a8"; // copied from Package.appxmanifest }
private string GetAppPackageSid() { Uri redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri(); Debug.Assert(redirectUri != null); return(redirectUri.AbsoluteUri); }
public MainPage() { this.InitializeComponent(); var app = new QTB3.Client.LabResultPatterns.Common.App(); app.UpdateRedirectUri(WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString()); LoadApplication(app); }
/// <inheritdoc /> public override string GetDefaultRedirectUri(string clientId, bool useRecommendedRedirectUri = false) { if (useRecommendedRedirectUri) { return(WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString()); } return(Constants.DefaultRedirectUri); }
// https://docs.microsoft.com/en-us/windows/uwp/security/web-authentication-broker public async Task <BrowserResult> InvokeAsync(BrowserOptions options) { var wabOptions = GetWebAuthOptions(options, GlobalSettings.Instance.SilentMode); WebAuthenticationResult result; try { var brokerAbsolutePath = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri; result = await BrokerSigninAsync(options, brokerAbsolutePath, wabOptions, CancellationToken.None); } catch (Exception ex) { return(new BrowserResult { ResultType = BrowserResultType.UnknownError, Error = ex.ToString() }); } switch (result.ResponseStatus) { case WebAuthenticationStatus.Success: { return(new BrowserResult { ResultType = BrowserResultType.Success, Response = result.ResponseData }); } case WebAuthenticationStatus.ErrorHttp: { return(new BrowserResult { ResultType = BrowserResultType.HttpError, Error = result.ResponseErrorDetail.ToString() }); } case WebAuthenticationStatus.UserCancel: { return(new BrowserResult { ResultType = BrowserResultType.UserCancel }); } default: { return(new BrowserResult { ResultType = BrowserResultType.UnknownError, Error = "Invalid response from WebAuthenticationBroker" }); } } }
public async Task GetAccountSessionAsync_SingleSignOn() { const string code = "code"; const string token = "token"; var applicationCallbackUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(); this.signOut = false; this.webAuthenticationUi.responseValues = new Dictionary <string, string> { { OAuthConstants.CodeKeyName, code } }; this.webAuthenticationUi.OnAuthenticateAsync = (Uri requestUri, Uri callbackUri) => { Assert.IsTrue(requestUri.ToString().Contains("response_type=code"), "Unexpected request Uri."); Assert.IsTrue(callbackUri.ToString().Equals(applicationCallbackUrl), "Unexpected callback Uri."); }; using (var httpResponseMessage = new HttpResponseMessage()) using (var responseStream = new MemoryStream()) using (var streamContent = new StreamContent(responseStream)) { httpResponseMessage.Content = streamContent; var mockSerializer = new MockSerializer(); mockSerializer.OnDeserializeObjectStream = (Stream stream) => { mockSerializer.DeserializeObjectResponse = new Dictionary <string, string> { { OAuthConstants.AccessTokenKeyName, token } }; }; var httpProvider = new MockHttpProvider(httpResponseMessage, mockSerializer) { OnSendAsync = (HttpRequestMessage requestMessage) => { Assert.IsTrue( requestMessage.RequestUri.ToString().Equals(OAuthConstants.MicrosoftAccountTokenServiceUrl), "Unexpected token request URL."); } }; this.authenticationProvider = new MsaAuthenticationProvider( this.clientId, /* returnUrl */ null, this.scopes, this.credentialCache); this.authenticationProvider.webAuthenticationUi = this.webAuthenticationUi; await this.authenticationProvider.AuthenticateUserAsync(httpProvider).ConfigureAwait(false); Assert.IsNotNull(this.authenticationProvider.CurrentAccountSession, "No account session returned."); Assert.AreEqual(token, this.authenticationProvider.CurrentAccountSession.AccessToken, "Unexpected token returned."); } }
public async static Task <AuthorizeResponse> DoImplicitFlowAsync(Uri endpoint, string clientId, string responseType, string scope) { return(await DoImplicitFlowAsync( endpoint, clientId, responseType, scope, WebAuthenticationBroker.GetCurrentApplicationCallbackUri())); }