public WebAuthenticatorController (WebAuthenticator authenticator) { this.authenticator = authenticator; authenticator.Error += HandleError; authenticator.BrowsingCompleted += HandleBrowsingCompleted; // // Create the UI // Title = authenticator.Title; NavigationItem.LeftBarButtonItem = new UIBarButtonItem ( UIBarButtonSystemItem.Cancel, delegate { Cancel (); }); activity = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.White); NavigationItem.RightBarButtonItem = new UIBarButtonItem (activity); webView = new UIWebView (View.Bounds) { Delegate = new WebViewDelegate (this), AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, }; View.AddSubview (webView); View.BackgroundColor = UIColor.Black; // // Locate our initial URL // BeginLoadingInitialUrl (); }
protected override async Task <OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { var ta = authenticator as TwitterAuthenticator; OauthToken = ta.AuthCode; var resp = await PostMessage("https://api.twitter.com/oauth/access_token", new FormUrlEncodedContent(new Dictionary <string, string> { { "oauth_verifier", ta.CodeVerifier } }), authenticated : false); var data = HttpUtility.ParseQueryString(await resp.Content.ReadAsStringAsync()); var account = new TwitterAccount() { ExpiresIn = 0, Created = DateTime.UtcNow, RefreshToken = ta.AuthCode, Scope = authenticator.Scope?.ToArray(), TokenType = "Oauth", Token = data["oauth_token"], OAuthSecret = data["oauth_token_secret"], ClientId = ClientId, Identifier = identifier, }; return(account); }
public async Task Authenticate(string scheme) { // Check if the user is already authenticated if (IsAuthenticated()) { throw new AuthenticationException(); } Uri authUrl = new Uri(string.Format(_authenticationUrl, scheme)); Uri callbackUrl = new Uri(_callback); // Initiate browser based flow and wait until the callback is received WebAuthenticatorResult result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl); // Check if the user cancels the flow at any point if (result == null) { throw new AuthenticationException(); } // Store token informations in a key/value store Preferences.Set("access_token", result.Properties["access_token"]); Preferences.Set("refresh_token", result.Properties["refresh_token"]); Preferences.Set("provider", result.Properties["provider"]); Preferences.Set("expiration", DateTime.Parse(result.Properties["expiration"])); }
private async void ButtonLogin_Clicked(object sender, EventArgs e) { try { var service = new DropboxAuthService(); var url = service.CreateAuthorizationRequest(DropboxConfiguration.AuthorityUrl); authorizeUrl.Text = url; var authenticationResult = await WebAuthenticator.AuthenticateAsync( new Uri(url), new Uri(DropboxConfiguration.RedirectUri)); editorAuthResponse.Text = JsonSerializer.Serialize(authenticationResult); var code = authenticationResult.Properties["code"]; var result = await service.GetTokenAsync(code); editorTokenResponse.Text = JsonSerializer.Serialize(result); var refresh = await service.GetRefreshTokenAsync(result.RefreshToken); editorRefreshTokenResponse.Text = JsonSerializer.Serialize(refresh); } catch (Exception ex) { lblInfo.Text = ex.ToString(); } }
private async void Login(string url, string clientId, string responseType, string callback, string scope) { try { var loginService = new LoginService(); var fullUrl = loginService.BuildAuthenticationUrl(url, clientId, responseType, callback, scope); var authenticationResult = await WebAuthenticator.AuthenticateAsync( new Uri(fullUrl), new Uri(callback)); var accessToken = authenticationResult?.AccessToken; if (accessToken == null && authenticationResult.Properties != null && authenticationResult.Properties.ContainsKey("code")) { accessToken = authenticationResult.Properties["code"]; } lblInfo.Text = accessToken; } catch (Exception ex) { lblInfo.Text = ex.ToString(); } }
public static async void Login (WebAuthenticator authenticator) { var fbAuth = authenticator as FacebookAuthenticator; try { fb.CoreKit.Settings.AppID = fbAuth.ClientId; var loginManager = new fb.LoginKit.LoginManager(); var window = UIKit.UIApplication.SharedApplication.KeyWindow; var root = window.RootViewController; if (root != null) { var current = root; while (current.PresentedViewController != null) { current = current.PresentedViewController; } var resp = await loginManager.LogInWithReadPermissionsAsync(authenticator.Scope.ToArray(),current); if (resp.IsCancelled) { authenticator.OnCancelled(); return; } var date = (DateTime)resp.Token.ExpirationDate; var expiresIn = (long)(date - DateTime.Now).TotalSeconds; fbAuth.OnRecievedAuthCode(resp.Token.TokenString,expiresIn); } } catch (Exception ex) { authenticator.OnError(ex.Message); } }
void BeginLoadingInitialUrl() { authenticator.GetInitialUrlAsync().ContinueWith(t => { if (t.IsFaulted) { keepTryingAfterError = false; authenticator.OnError(t.Exception); } else { // Delete cookies so we can work with multiple accounts if (this.authenticator.ClearCookiesBeforeLogin) { WebAuthenticator.ClearCookies(); } // // Begin displaying the page // Uri uri = t.Result; LoadInitialUrl(uri); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { if (null == authenticator) { Type type_authenticator = e.Parameter.GetType(); if (type_authenticator == typeof(OAuth1Authenticator)) { authenticator = e.Parameter as OAuth1Authenticator; } else if (type_authenticator == typeof(OAuth2Authenticator)) { authenticator = e.Parameter as OAuth2Authenticator; } else { System.Diagnostics.Debug.WriteLine($"Invalid Authenticator {type_authenticator}"); throw new Xamarin.Auth.AuthException($"Invalid Authenticator {type_authenticator}"); } } url_initial = this.authenticator.GetInitialUrlAsync().Result; this.browser.Navigate(url_initial); System.Diagnostics.Debug.WriteLine("OnNavigatedTo authenticator = " + authenticator.Title); authenticator.Completed += auth_Completed; authenticator.Error += auth_Error; url_initial = await authenticator.GetInitialUrlAsync(); base.OnNavigatedTo(e); return; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { if (null == authenticator) { authenticator = e.Parameter as WebRedirectAuthenticator; if (authenticator == null) { System.Diagnostics.Debug.WriteLine($"Invalid Authenticator {e.Parameter?.GetType().ToString() ?? "null"}"); throw new Xamarin.Auth.Compat.AuthException($"Invalid Authenticator {e.Parameter?.GetType().ToString() ?? "null"}"); } } url_initial = this.authenticator.GetInitialUrlAsync().Result; this.browser.Navigate(url_initial); System.Diagnostics.Debug.WriteLine("OnNavigatedTo authenticator = " + authenticator.Title); authenticator.Completed += auth_Completed; authenticator.Error += auth_Error; url_initial = await authenticator.GetInitialUrlAsync(); base.OnNavigatedTo(e); return; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { authenticator = e.Parameter as OAuth2Authenticator; if (null == authenticator) { authenticator = e.Parameter as OAuth1Authenticator; } if (null == authenticator) { // Not OAuth1 and OAuth2 throw new InvalidOperationException("Unknown OAuth type"); } url_initial = this.authenticator.GetInitialUrlAsync().Result; this.browser.Navigate(url_initial); System.Diagnostics.Debug.WriteLine("OnNavigatedTo authenticator = " + authenticator.Title); authenticator.Completed += auth_Completed; authenticator.Error += auth_Error; url_initial = await authenticator.GetInitialUrlAsync(); base.OnNavigatedTo(e); return; }
async void Button_Clicked(System.Object sender, System.EventArgs e) { IRemoteAuthenticationClient authClient = new RemoteAuthenticationClient("", "", ""); var authUri = authClient.BuildAuthorizeUri("sample", "myhue"); var authResult = await WebAuthenticator.AuthenticateAsync( new Uri(authUri.AbsoluteUri), new Uri("mymeetings://")); var code = authResult?.Properties.FirstOrDefault(x => x.Key == "code").Value; if (String.IsNullOrEmpty(code)) { return; } var accessToken = await authClient.GetToken(code); IRemoteHueClient client = new RemoteHueClient(authClient.GetValidToken); var bridges = await client.GetBridgesAsync(); var currentBridge = bridges.FirstOrDefault().Id; try { //var key = await client.RegisterAsync(bridges.First().Id, "Sample App"); client.Initialize(bridges.First().Id, ""); var lights = await client.GetLightsAsync(); var lightResult = await client.SendCommandAsync(new LightCommand().TurnOff()); } catch (Exception ex) { } }
protected virtual async Task <OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { var postData = await authenticator.GetTokenPostData(ClientSecret); var reply = await Client.PostAsync("oauth2/token", new FormUrlEncodedContent(postData)); var resp = await reply.Content.ReadAsStringAsync(); var result = Deserialize <OauthResponse>(resp); if (!string.IsNullOrEmpty(result.Error)) { throw new Exception(result.ErrorDescription); } var account = new OAuthAccount() { ExpiresIn = result.ExpiresIn, Created = DateTime.UtcNow, RefreshToken = authenticator.AuthCode, Scope = authenticator.Scope.ToArray(), TokenType = result.TokenType, Token = result.AccessToken, ClientId = ClientId, Identifier = identifier, }; return(account); }
public async Task <(string response, Exception error)> Authenticate() { try { var storedToken = await this.GetAccessTokenFromSettings(); if (storedToken) { return(this.AccessToken, null); } else { var state = Guid.NewGuid().ToString("N"); var url = $"https://www.dropbox.com/oauth2/authorize?client_id={ClientId}&state={state}&response_type=token&redirect_uri={RedirectUri}"; var authResult = await WebAuthenticator.AuthenticateAsync( new Uri(url), new Uri(RedirectUri)); this.AccessToken = authResult?.AccessToken; await SaveDropboxToken(AccessToken); return(this.AccessToken, null); } } catch (Exception ex) { return(null, ex); } }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { try { var callbackUrl = string.IsNullOrEmpty(_callbackUrl) ? options.EndUrl : _callbackUrl; WebAuthenticatorResult authResult = // await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri(callbackUrl)); await WebAuthenticator.AuthenticateAsync(new WebAuthenticatorOptions { Url = new Uri(options.StartUrl), CallbackUrl = new Uri(callbackUrl), PrefersEphemeralWebBrowserSession = true }); var authorizeResponse = ToRawIdentityUrl(options.EndUrl, authResult); return(new BrowserResult { Response = authorizeResponse }); } catch (Exception ex) { Debug.WriteLine(ex); return(new BrowserResult() { ResultType = BrowserResultType.UnknownError, Error = ex.ToString() }); } }
public static async void Login(WebAuthenticator authenticator) { var fbAuth = authenticator as FacebookAuthenticator; try { fb.CoreKit.Settings.AppID = fbAuth.ClientId; var loginManager = new fb.LoginKit.LoginManager(); var window = UIKit.UIApplication.SharedApplication.KeyWindow; var root = window.RootViewController; if (root != null) { var current = root; while (current.PresentedViewController != null) { current = current.PresentedViewController; } var resp = await loginManager.LogInWithReadPermissionsAsync(authenticator.Scope.ToArray(), current); if (resp.IsCancelled) { authenticator.OnCancelled(); return; } var date = (DateTime)resp.Token.ExpirationDate; var expiresIn = (long)(date - DateTime.Now).TotalSeconds; fbAuth.OnRecievedAuthCode(resp.Token.TokenString, expiresIn); } } catch (Exception ex) { authenticator.OnError(ex.Message); } }
protected override async Task <OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { if (Implicit) { return(new OAuthAccount() { ExpiresIn = 31536000, Created = DateTime.UtcNow, RefreshToken = authenticator.AuthCode, Scope = authenticator.Scope?.ToArray(), TokenType = "Bearer", Token = authenticator.AuthCode, ClientId = ClientId, Identifier = identifier, Cookies = authenticator.Cookies, }); } //Fitbit does a weird AuthHeader before swaping tokens var authHeader = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{ClientId}:{ClientSecret}")); Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authHeader); var account = await base.GetAccountFromAuthCode(authenticator, identifier); return(account); }
static void Main(string[] args) { Authenticator = new WebAuthenticator(); if (!File.Exists($"{AppDirectory}setupcomplete.txt")) { FirstTimeSetup(); } // TODO: create json/xml settings file instead of this var FileContents = File.ReadAllText($"{AppDirectory}setupcomplete.txt"); AppState = Guid.Parse(FileContents); ConsoleHelper.WriteLine("Grabbing credentials from database..."); ChatBot = new TwitchChatBot(Authenticator, AppState); ConsoleHelper.WriteLine("Connecting to Twitch..."); ChatBot.Start(); // TODO: make playlists great again ConsoleHelper.WriteLine("Attempting to load the playlist..."); GlobalVariables.GlobalPlaylist.LoadFromFolder("C:/Users/rocki/OneDrive/Music/STREM III"); GlobalVariables.GlobalPlaylist.Shuffle(); GlobalVariables.GlobalPlaylist.Play(); object locker = new object(); List <char> charBuffer = new List <char>(); while (ChatBot.IsConnected) { var key = ConsoleHelper.ReadKey(); } ConsoleHelper.WriteLine("Press any key to exit..."); System.Console.ReadKey(true); }
// autenticacion public async Task <WebAuthenticatorResult> Login() { // efectua el login de linkedin string LoginUrl = $"https://www.linkedin.com/oauth/v2/authorization?response_type={responseType}&client_id={clientId}&state={state}&scope={scope}&redirect_uri={redirectUrl}"; return(await WebAuthenticator.AuthenticateAsync(new Uri(LoginUrl), new Uri(callbackUrl))); }
public SomeViewModel() { SomeAction = new CoreCommand(async(obj) => { LoadingMessageHUD = "Some action..."; IsLoadingHUD = true; await Task.Delay(new TimeSpan(0, 0, 4)); IsLoadingHUD = false; }); SeeFontAction = new Command(async() => { await Navigation.PushAsync(new FontDemo()); }); GoogleLoginAction = new CoreCommand(async(obj) => { var authResult = await WebAuthenticator.AuthenticateAsync( new Uri("https://cloudmovieweb.azurewebsites.net/mobileauth/Google"), new Uri("cloudmovie.mobile://")); AccountToken = authResult?.AccessToken; }); MicrosoftLoginAction = new CoreCommand(async(obj) => { var authResult = await WebAuthenticator.AuthenticateAsync( new Uri("https://cloudmovieweb.azurewebsites.net/mobileauth/Microsoft"), new Uri("cloudmovie.mobile://")); AccountToken = authResult?.AccessToken; }); }
private async void LoginButtonClicked(object sender, EventArgs e) { try { var callbackUrl = new Uri(OktaConfiguration.Callback); var loginUrl = new Uri(loginService.BuildAuthenticationUrl()); var authenticatorResult = await WebAuthenticator.AuthenticateAsync(loginUrl, callbackUrl); userToken = await loginService.ExchangeCodeForIdToken(authenticatorResult); var idToken = loginService.ParseAuthenticationResult(userToken.IdToken); var nameClaim = idToken.Claims.FirstOrDefault(claim => claim.Type == "name"); if (nameClaim != null) { WelcomeLabel.Text = $"Welcome to Xamarin.Forms {nameClaim.Value}!"; LogoutButton.IsVisible = !(LoginButton.IsVisible = false); } } catch (TaskCanceledException) { } }
public async Task <Tuple <Tuple <string, string>, UserInfo> > GetEmailByLoggingIn() { WebAuthenticatorResult authResult; try { authResult = await WebAuthenticator.AuthenticateAsync( new Uri($"https://{domain}/login?client_id={clientId}&response_type={responseType}&scope={scope}&redirect_uri={callbackUri}"), new Uri(callbackUri) ); } catch (Exception ex) { Console.WriteLine(ex.ToString()); authResult = null; } if (authResult == null) { return(null); } var claims = JWT.JsonWebToken.Base64UrlDecode(authResult.IdToken.Split('.')[1]); var cString = System.Text.Encoding.UTF8.GetString(claims); var c = JsonConvert.DeserializeObject <AuthClaims>(cString); var u = new UserInfo { Id = c.Email.ToLower(), Name = c.NickName }; var tokens = new Tuple <string, string>(authResult.IdToken, authResult.RefreshToken); return(new Tuple <Tuple <string, string>, UserInfo>(tokens, u)); }
public async Task <WebAuthenticatorResult> LaunchUriAsync(string url) { var authResult = await WebAuthenticator.AuthenticateAsync( new Uri(url), new Uri(Constants.RedirectUri)); return(authResult); }
/// <summary> /// Runs the Google OAuth process in two steps : /// - First step : retrieves the unique OAuth code from login UI web page /// - Second step : send the unique OAuth code to Google's token server to get the OAuth token /// </summary> /// <returns>Returns a GoogleOAuthResponse containing the OAuth token</returns> public async Task <GoogleToken?> DoGoogleOAuthLoginAsync() { _loggingService.Trace("Executing LoginProvider.DoGoogleOAuthLoginAsync"); WebAuthenticatorResult authenticatorResult; try { authenticatorResult = await WebAuthenticator.AuthenticateAsync( new Uri(_appSettings.GoogleAuthUrl), new Uri(_appSettings.RedirectUrl)); } catch (TaskCanceledException) { _loggingService.Trace("Task Canceled : DoGoogleOAuthLoginAsync"); return(null); } var code = authenticatorResult.Properties.FirstOrDefault(x => x.Key.Equals("code")).Value; if (string.IsNullOrWhiteSpace(code)) { _loggingService.Trace("No 'code' property found in authResult. Returning."); return(null); } using var client = new HttpClient(); var parameters = new Dictionary <string, string> { { "code", code }, { "client_id", _appSettings.ClientId }, { "redirect_uri", _appSettings.RedirectUrl }, { "grant_type", "authorization_code" } }; HttpResponseMessage response; var encodedContent = new FormUrlEncodedContent(parameters); try { response = await client.PostAsync(_appSettings.GoogleTokenUrl, encodedContent).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } catch (Exception e) { _loggingService.Error(e, "Error Executing LoginProvider.DoGoogleOAuthLoginAsync"); return(null); } var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var googleToken = JsonConvert.DeserializeObject <GoogleToken>(responseContent); return(googleToken); }
private void DisplayUI(WebAuthenticator auth) { #if __ANDROID__ Forms.Context.StartActivity(auth.GetUI(Forms.Context)); #endif #if __IOS__ SocialLogin.iOS.AppDelegate.GetController().PresentViewController(auth.GetUI(), true, null); #endif }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri(Constants.RedirectUri)); return(new BrowserResult() { Response = ParseAuthenticatorResult(authResult) }); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri("com.companyname.mycalendar://login")); return(new BrowserResult() { Response = ParseAuthenticatorResult(authResult) }); }
public async Task <BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = default) { WebAuthenticatorResult authResult = await WebAuthenticator.AuthenticateAsync(new Uri(options.StartUrl), new Uri("myapp://auth_callback")); return(new BrowserResult() { Response = Parse(authResult) }); }
public override async Task <AuthorizationResponse> Authorize(AuthorizationRequest request) { var authUrl = request.BuildUrl(); var callbackUrl = new Uri(request.RedirectUri); var result = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl); var serialized = JsonSerializer.Serialize(result.Properties); var authorizationResponse = JsonSerializer.Deserialize <AuthorizationResponse>(serialized); return(authorizationResponse !); }
protected override async Task <string> StartSecureNavigation(Uri startUrl, Uri redirectUrl) { var authenticationResult = await WebAuthenticator.AuthenticateAsync(startUrl, redirectUrl); if (!authenticationResult.Properties.Any()) { return(string.Empty); } return($"?{string.Join("&", authenticationResult.Properties.Select(x => $"{x.Key}={x.Value}"))}"); }
public void ProcessRequest(HttpContext context) { // without this, a parser error is displayed in some browsers context.Response.Write("<html></html>"); FormsAuthentication.SignOut(); WebAuthenticator wa = new WebAuthenticator(); wa.Logout(ResolveHostUrl("/")); }
public async Task Redirect(string urlBase, string callbackScheme, string accessToken, string refreshToken, int expires) { var r = await WebAuthenticator.AuthenticateAsync( new Uri($"{urlBase}?access_token={accessToken}&refresh_token={refreshToken}&expires={expires}"), new Uri($"{callbackScheme}://")); Assert.Equal(accessToken, r?.AccessToken); Assert.Equal(refreshToken, r?.RefreshToken); Assert.NotNull(r?.ExpiresIn); Assert.True(r?.ExpiresIn > DateTime.UtcNow); }
public virtual async Task <Token> Login(object?state = null, string?client_id = null, IDictionary <string, string?>?acr_values = null, CancellationToken cancellationToken = default) { var authResult = await WebAuthenticator.AuthenticateAsync(GetLoginUrl(state, client_id, acr_values), ClientAppProfile.OAuthRedirectUri).ConfigureAwait(false); Token token = authResult.Properties; string jsonToken = JsonConvert.SerializeObject(token); await StoreToken(jsonToken, cancellationToken).ConfigureAwait(false); return(token); }
public static async void Login(WebAuthenticator authenticator) { var fbAuthenticator = authenticator as FacebookAuthenticator; var currentActivity = activityLifecycleManager.CurrentActivity; FacebookSdk.SdkInitialize(currentActivity); callbackManager = CallbackManagerFactory.Create(); var loginManager = LoginManager.Instance; var fbHandler = new FbCallbackHandler(); loginManager.RegisterCallback(callbackManager, fbHandler); fbHandler.Reset(); if (RequestPublishPermissions) { loginManager.LogInWithPublishPermissions(currentActivity, fbAuthenticator.Scope); } else { loginManager.LogInWithReadPermissions(currentActivity, fbAuthenticator.Scope); } LoginResult result = null; try { result = await fbHandler.Task; } catch (Exception ex) { fbAuthenticator.OnError(ex.Message); return; } if (result == null) { fbAuthenticator.OnCancelled(); } DateTime?expires = null; long expiresIn = -1; if (result?.AccessToken.Expires != null) { expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(result.AccessToken.Expires.Time); expiresIn = (long)(expires.Value - DateTime.Now).TotalSeconds; } fbAuthenticator.OnRecievedAuthCode(result?.AccessToken.Token, expiresIn); }
static async void Login(WebAuthenticator authenticator) { var currentActivity = activityLifecycle.CurrentActivity; var googleAuth = authenticator as GoogleAuthenticator; googleSignInProvider = new GoogleSignInProvider(); GoogleSignInResult result = null; try { result = await googleSignInProvider.Authenticate(GoogleAuthenticator.GetGoogleClientId (googleAuth.ClientId), googleAuth.Scope.ToArray ()); if (result == null || result.Status.IsCanceled || result.Status.IsInterrupted) { googleAuth.OnCancelled(); return; } if (!result.IsSuccess) { googleAuth.OnError(result.Status.StatusMessage); return; } //var accessToken = Android.Gms.Auth.GoogleAuthUtil.GetToken(currentActivity, result.SignInAccount.Email, string.Join (" ", tokenScopes)); var androidAccount = Android.Accounts.AccountManager.FromContext(currentActivity) ?.GetAccounts() ?.FirstOrDefault(a => a.Name?.Equals(result?.SignInAccount?.Email, StringComparison.InvariantCultureIgnoreCase) ?? false); var tokenScopes = googleAuth.Scope.Select(s => "oauth2:" + s); var accessToken = await Task.Run(() => { return Android.Gms.Auth.GoogleAuthUtil.GetToken(currentActivity, androidAccount, string.Join (" ", tokenScopes)); }); googleAuth.OnRecievedAuthCode (accessToken); } catch (Exception ex) { googleAuth.OnError(ex.Message); } }
public static async void Login(WebAuthenticator authenticator) { var fbAuthenticator = authenticator as FacebookAuthenticator; var currentActivity = activityLifecycleManager.CurrentActivity; FacebookSdk.SdkInitialize(currentActivity); callbackManager = CallbackManagerFactory.Create(); var loginManager = LoginManager.Instance; var fbHandler = new FbCallbackHandler(); loginManager.RegisterCallback(callbackManager, fbHandler); fbHandler.Reset(); if (RequestPublishPermissions) loginManager.LogInWithPublishPermissions(currentActivity, fbAuthenticator.Scope); else loginManager.LogInWithReadPermissions(currentActivity, fbAuthenticator.Scope); LoginResult result = null; try { result = await fbHandler.Task; } catch (Exception ex) { fbAuthenticator.OnError(ex.Message); return; } if (result == null) fbAuthenticator.OnCancelled(); DateTime? expires = null; long expiresIn = -1; if (result?.AccessToken.Expires != null) { expires = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(result.AccessToken.Expires.Time); expiresIn = (long)(expires.Value - DateTime.Now).TotalSeconds; } fbAuthenticator.OnRecievedAuthCode(result?.AccessToken.Token, expiresIn); }
protected override Task<OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { var author = (DropBoxAuthenticator)authenticator; var account = new OAuthAccount() { ExpiresIn = -1, Created = DateTime.UtcNow, RefreshToken = null, Scope = new string[0], TokenType = author.TokenType, Token = author.Token, ClientId = ClientId, Identifier = identifier, }; account.UserData["Uid"] = author.Uid; return Task.FromResult(account); }
protected override Task<OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { var auth = authenticator as GoogleAuthenticator; if (IsUsingNative) { return Task.FromResult (new OAuthAccount() { ExpiresIn = -1, Created = DateTime.UtcNow, Scope = authenticator.Scope?.ToArray(), TokenType = "Bearer", Token = auth.AuthCode, ClientId = ClientId, Identifier = identifier, }); } return base.GetAccountFromAuthCode(authenticator, identifier); }
//Thanks you facebook for making your token exchange a get... protected override async Task<OAuthAccount> GetAccountFromAuthCode(WebAuthenticator authenticator, string identifier) { var auth = authenticator as FacebookAuthenticator; OauthResponse result; if (IsUsingNative) { result = new OauthResponse { ExpiresIn = auth.Expiration, TokenType = "Bearer", AccessToken = auth.AuthCode, RefreshToken = auth.AuthCode, }; } else { var postData = await authenticator.GetTokenPostData(ClientSecret); if (string.IsNullOrWhiteSpace(TokenUrl)) throw new Exception("Invalid TokenURL"); var url = new Uri(TokenUrl).AddParameters(postData); var reply = await Client.GetAsync(url); var resp = await reply.Content.ReadAsStringAsync(); result = Deserialize<OauthResponse>(resp); if (!string.IsNullOrEmpty(result.Error)) throw new Exception(result.ErrorDescription); } var account = new OAuthAccount() { ExpiresIn = result.ExpiresIn, Created = DateTime.UtcNow, RefreshToken = result.RefreshToken, Scope = authenticator.Scope?.ToArray(), TokenType = result.TokenType, Token = result.AccessToken, ClientId = ClientId, Identifier = identifier, }; return account; }
public WebAuthenticatorWebView(WebAuthenticator authenticator) { this.authenticator = authenticator; }
public void ProcessRequest(HttpContext context) { string url = context.Request.QueryString["ReturnUrl"]; if (url == null || url.Length == 0) context.Response.Redirect("~/"); if (context.User.Identity.IsAuthenticated) context.Response.Redirect(url); WebAuthenticator webAuth = new WebAuthenticator(); webAuth.UsesClientFrameset = true; // without this, a parser error is displayed in some browsers context.Response.Write("<html></html>"); if (webAuth.Login(Constants.APPLICATION_NAME)) { try { SouthernIdentity id = new SouthernIdentity(webAuth.SecurityToken); //TODO: OPTIONAL: Add Extra Application Data to Forms Ticket webAuth.UserData.Add("UserName", id.Name); Log.Write("Getting user information for {0}", Log.Mask.Diagnostic, id.Name); LPHSUser user = LPHSUser.GetBySid(id.SID); if (user != null) { if (!user.Active) { //FormsAuthentication.SignOut(); //webAuth.Logout("~/Account/DenyAccess?ReturnUrl=%2f&msg=Access%20Denied.%20This%20account%20is%20inactive.".ToAbsoluteUrl()); DenyAccess(context, "Access Denied. This account is inactive."); } webAuth.UserData.Add("Email", user.EmailAddress); webAuth.UserData.Add("DisplayName", user.DisplayName); webAuth.UserData.Add("ID", user.ID); webAuth.UserData.Add("Active", user.Active); webAuth.UserData.Add("SchoolID", user.SchoolID ?? -1); webAuth.UserData.Add("UserType", user.UserType.ToString()); webAuth.UserData.Add("SumTotalID", user.SumTotalID ?? ""); //webAuth.UserRoles.Add("Teacher"); webAuth.UserRoles.Add(user.UserType.ToString()); user.LastLoggedOn = DateTime.UtcNow; LPHSUser.Update(user); } else DenyAccess(context, "Access Denied. This account is not permitted to access Learning Power."); //Write the Forms Ticket webAuth.WriteTicket(); } catch (Exception ex) { Log.Write(ex, Log.Mask.Failure); DenyAccess(context, "An error ocurred logging into Learning Power."); //throw; //DenyAccess(context); } finally { } } }
protected void DenyAccess(HttpContext context, string message = "Access denied.") { try { FormsAuthentication.SignOut(); WebAuthenticator webAuth = new WebAuthenticator(); webAuth.Logout(("~/Account/DenyAccess?ReturnUrl=%2f&msg=" + HttpUtility.UrlEncode(message)).ToAbsoluteUrl()); //context.Response.Redirect("~/Account/DenyAccess?ReturnUrl=%2f&msg=Access%20Denied"); //context.Response.Redirect("~/NonSecure/AccessDenied.aspx"); } catch (Exception ex) { Log.Write(ex, Log.Mask.Failure); } finally { } }