public static async Task Authenticate(string name, string token, bool forced = false) { if ((IsAuthenticated && !forced) || IsAuthenticating) { throw new APIError("Already authenticated or is currently authenticating."); } Debug.Log($"Attempting to authenticate as {name}..."); IsAuthenticating = true; try { await APIRequest("users/auth/", new string[] { $"username={name}", $"user_token={token}" }); UserName = name; UserToken = token; IsAuthenticated = true; IsAuthenticating = false; Debug.Log("Successfully authenticated."); OnAuthenticated?.Invoke(); } catch (APIError) { UserName = UserToken = ""; IsAuthenticated = false; IsAuthenticating = false; throw; } }
private async void WebAccountProviderCommandInvoked(WebAccountProviderCommand command) { string token = string.Empty; // AccountClientID is ignored by MSA WebTokenRequest webTokenRequest = new WebTokenRequest(command.WebAccountProvider, AccountScopeRequested, AccountClientId); // If the user selected a specific account, RequestTokenAsync will return a token for that account. // The user may be prompted for credentials or to authorize using that account with your app // If the user selected a provider, the user will be prompted for credentials to login to a new account WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); // If a token was successfully returned, then store the WebAccount Id into local app data // This Id can be used to retrieve the account whenever needed. To later get a token with that account // First retrieve the account with FindAccountAsync, and include that webaccount // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; } // We succeeded in getting a valid user. if (userAccount != null) { // save user ID in local storage _settings.Values["userID"] = userAccount.Id; _settings.Values["userEmail"] = userAccount.UserName; } AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested; OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(token)); }
public async void AuthenticateWithWNS() { IsRefreshInProgress = true; var urlEncodedSid = HttpUtility.UrlEncode(WNS_PACKAGE_SECURITY_IDENTIFIER); var urlEncodedSecret = HttpUtility.UrlEncode(WNS_SECRET_KEY); var body = string.Format(PayloadFormat, urlEncodedSid, urlEncodedSecret, AccessScope); string response = null; Exception exception = null; using (var client = new WebClient()) { client.Headers.Add("Content-Type", UrlEncoded); try { response = await client.UploadStringTaskAsync(new Uri(AccessTokenUrl), body); } catch (Exception e) { exception = e; Debug.WriteLine(string.Format("Failed WNS authentication. Error: {0}", e.Message)); } } if (exception == null && response != null) { oAuthToken = GetOAuthTokenFromJson(response); ScheduleTokenRefreshing(); } IsRefreshInProgress = false; OnAuthenticated?.Invoke(); }
private void Button_Click(object sender, RoutedEventArgs e) { //Validate the fields if (ValidateFields()) { //AuthenticateUser returns user if it finds a user with the same password User user = userModel.AuthenticateUser(Username, txtPassword.Password); //If user is null, something is wrong. if (user == null) { errors.Add("Username or password invalid!"); } else { //If a user is found, we create a login for that user and call the //onAuthenticated to tell for those interested that user and password match. Login.CreateLogin(user); OnAuthenticated?.Invoke(); } } if (errors.Any()) { lblError.Content = UIHelper.GetStringFromList(errors); } }
/// <summary> /// Establish an authenticated connection to the miniserver. Fires the OnAuthenticated event when successfull. /// After the event fired, the connection to the miniserver can be used. /// </summary> /// <param name="handler">The tokenhandler that should be used</param> public override async Task Authenticate(TokenHandler handler) { if (await MiniserverReachable()) { WebSocket = new ClientWebSocket(); await WebSocket.ConnectAsync(new Uri($"ws://{IP}:{Port}/ws/rfc6455"), CancellationToken.None); BeginListening(); string key = await Session.GetSessionKey(); string keyExchangeResponse = (await SendWebservice(new WebserviceRequest <string>($"jdev/sys/keyexchange/{key}", EncryptionType.None))).Value; TokenHandler = handler; if (TokenHandler?.Token != null) { string hash = await TokenHandler?.GetTokenHash(); string response = (await SendWebservice(new WebserviceRequest <string>($"authwithtoken/{hash}/{TokenHandler.Username}", EncryptionType.RequestAndResponse))).Value; AuthResponse authResponse = JsonConvert.DeserializeObject <AuthResponse>(response); if (authResponse.ValidUntil != default && authResponse.TokenRights != default) { OnAuthenticated.Invoke(this, new ConnectionAuthenticatedEventArgs(TokenHandler)); return; } } if (await TokenHandler.RequestNewToken()) { OnAuthenticated.Invoke(this, new ConnectionAuthenticatedEventArgs(TokenHandler)); return; } await HttpClient?.Authenticate(new TokenHandler(HttpClient, handler.Username, handler.Token, false)); } }
public async Task Connect(CancellationToken stoppingToken = default) { try { var auth = $"Authorization: Bearer {_configuration.Key}"; var uri = new Uri($"{_configuration.Url}{AnimusEndpoints.WebSocket}"); await _client.ConnectAsync(uri, CancellationToken.None); OnConnected?.Invoke(this, new OnConnectEventArgs()); var bytes = Encoding.UTF8.GetBytes(auth); await _client.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, stoppingToken); var(result, buffer) = await Receive(_client, stoppingToken); if (result.MessageType == WebSocketMessageType.Text) { var message = Encoding.UTF8.GetString(buffer, 0, result.Count); if (message.Equals("authenticated", StringComparison.InvariantCultureIgnoreCase)) { _logger.Information($"Laputa says: '{ message}'"); OnAuthenticated?.Invoke(this, new OnAuthenticatedEventArgs()); } } } catch (Exception ex) { Log.Error(ex, "Failed to connect to animus"); } }
public virtual void OnAuthenticatedInvoke(AuthenticationResponse x) { if (GameSparksManager.Instance().IsDebug) { var subs = OnAuthenticated?.GetInvocationList(); var debugStr = "OnAuthenticated InvokationList: "; subs?.ToList().ForEach(m => debugStr += "\n" + m.Method.Name); Debug.Log(debugStr); } OnAuthenticated?.Invoke(x); }
private void PasswordBox_OnPreviewKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter && Password.SecurePassword.Length > 0) { bool sucess; try { if (_passwordTries >= 3) { Thread.Sleep(3000); } if (OnlyVerifyPassword) { sucess = Hub.Instance.EncryptionManager.ValidatePassword(Password.SecurePassword); } else { sucess = Hub.Instance.EncryptionManager.Authenticate(true, Password.SecurePassword); } } catch (Exception) { sucess = false; } if (sucess) { //GlowBrush = (SolidColorBrush)FindResource("AccentColorBrush"); _passwordTries = 0; e.Handled = true; OnAuthenticated?.Invoke(); //DialogResult = true; //Close(); } else { //GlowBrush = (SolidColorBrush)FindResource("ValidationBrush5"); _passwordTries++; Password.SelectAll(); } } else if (e.Key == Key.Escape) { e.Handled = true; OnAuthentionCanceled?.Invoke(); //DialogResult = null; //Close(); } }
/// <summary> /// Starts the authentication process. /// </summary> public void SignInAndStartMPGame(uint variation) { Social.localUser.Authenticate(success => { if (!success) { OnAuthenticationError?.Invoke(); } else { OnAuthenticated?.Invoke(); StartMatchMaking(variation); } }); }
/// <summary> /// Runs when lobby succes /// </summary> /// <param name="reason"></param> void NetLobby_OnSucces(string reason) { _connection = new Connection(_client, _client.ServerConnection, (_client.ServerConnection.Tag as Handshake).CreateEncryption()); try { OnAuthenticated.Invoke(_connection); SetStep(AuthenticationStatus.Authenticated); } catch (InvalidOperationException) { OnAuthenticationFailed.Invoke("Error occured while creation Connection"); SetStep(AuthenticationStatus.HandshakeFailed); } }
private void Client_MessageReceived(object sender, MessageReceivedEventArgs e) { OnReceivedRawMessage?.Invoke(client, e.Message); // there's a number at the start of every message, figure out what it is, and remove it var raw = e.Message; if (raw.Contains("\"")) { var number = e.Message.Split('"')[0].Substring(0, e.Message.Split('"')[0].Length - 1); raw = e.Message.Substring(number.Length); } if (e.Message.StartsWith("40")) { handleAuthentication(); return; } if (e.Message.StartsWith("0{\"sid\"")) { handlePingInitialization(Parsing.Internal.handleSessionMetadata(JObject.Parse(raw))); } if (e.Message.StartsWith("42[\"authenticated\"")) { OnAuthenticated?.Invoke(client, Parsing.Internal.handleAuthenticated(JArray.Parse(raw))); return; } if (e.Message.StartsWith("42[\"unauthorized\"")) { OnAuthenticationFailure?.Invoke(client, null); } if (e.Message.StartsWith("42[\"event\",{\"_id\"")) { handleComplexObject(JArray.Parse(raw)); return; } if (e.Message.StartsWith("42[\"event:update\",{\"name\"")) { handleSimpleUpdate(JArray.Parse(raw)); return; } }
// Get an access token for the given context and resourceId. An attempt is first made to // acquire the token silently. If that fails, then we start the flow of interacting with the user // through. private async Task BeginGetAuthTokenAsync() { string token = null; // FindAccountProviderAsync returns the WebAccountProvider of an installed plugin // The Provider and Authority specifies the specific plugin // This scenario only supports Microsoft accounts. // The Microsoft account provider is always present in Windows 10 devices, as is the Azure AD plugin. // If a non-installed plugin or incorect identity is specified, FindAccountProviderAsync will return null accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, consumerAuthority); // Check if there's a record of the last account used with the app var userID = _settings.Values["userID"]; if (userID != null) { WebTokenRequest webTokenRequest = new WebTokenRequest(accountProvider, AccountScopeRequested, AccountClientId); // Get an account object for the user userAccount = await WebAuthenticationCoreManager.FindAccountAsync(accountProvider, (string)userID); // Ensure that the saved account works for getting the token we need //WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest, userAccount); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, userAccount); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success || webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.AccountSwitch) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; } else { // The saved account could not be used for getting a token // Make sure that the UX is ready for a new sign in SignOut(); } } else { // There is no recorded user. // Check if a default MSA account has been set already. accountProvider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId); // Check if the returned authority is "consumers" if (accountProvider?.Authority == consumerAuthority) { // If it is, then there’s a default MSA account present and there’s no need to show account control WebTokenRequest webTokenRequest = new WebTokenRequest(accountProvider, AccountScopeRequested, AccountClientId); // This is where most of the magic happens.The provider you specified takes over, trying to use the currently // signed in user(or any account saved on the system) to obtain the token you requested without prompting the user. //WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest); WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest); if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success) { WebTokenResponse webTokenResponse = webTokenRequestResult.ResponseData[0]; userAccount = webTokenResponse.WebAccount; token = webTokenResponse.Token; } } else { // There is no default account or the returned authority is not "consumer", so we must show account control // The AccountCommandsRequested event triggers before the Accounts settings pane is displayed AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested; AccountsSettingsPane.Show(); // Quit at this point - the user interacts with the AccountSettingsPane to enter MSA credentials, so // The OnAuthenticated event gets fired later on to complete this operation return; } } // We succeeded in getting a valid user. if (userAccount != null) { // save user ID in local storage _settings.Values["userID"] = userAccount.Id; _settings.Values["userEmail"] = userAccount.UserName; OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(token)); } // We didn't succeed in getting a valid user. Clear the app settings so that another user can sign in. else { SignOut(); OnAuthenticated?.Invoke(this, new AuthenticatedEventArgs(string.Empty)); } }
public async Task ConnectAsync() { OnConnected?.Invoke(this, EventArgs.Empty); OnAuthenticated?.Invoke(this, EventArgs.Empty); await Task.CompletedTask; }
public virtual Task Authenticated(LtiAuthenticatedContext context) { return(OnAuthenticated.Invoke(context)); }
protected virtual void InvokeAuthenticatedEvent() => OnAuthenticated?.Invoke(this, EventArgs.Empty);