public string RequestToken(string password) { if (string.IsNullOrEmpty(password)) { throw new InvalidOperationException("Cannot request a token without a password provided."); } if (IsAuthenticated) { throw new InvalidOperationException("Already authenticated."); } var jObject = new JObject(); jObject["pass"] = password ?? Password; try { var response = Requester.PostRequest(Methods.GetToken, jObject); var obj = JsonConvert.DeserializeObject(response) as JObject; var token = obj["chat_token"].ToString(); var eventArgs = new AuthenticationEventArgs(token); Token = token; Authenticated?.Invoke(this, eventArgs); return(token); } catch (RequestException e) { ErrorOccured?.Invoke(this, new ErrorEventArgs(e)); return(string.Empty); } }
public ApiAuthentication(INotificationService notificationService) { NotificationService = notificationService; Authenticator = new ExtendedOAuth2Authenticator("webapi", "webapi", new Uri("https://laco-wiki.net/identity/connect/authorize"), new Uri("laco-wiki-app://"), null, true); Authenticator.Completed += async(sender, args) => { if (args.IsAuthenticated) { string accessToken = args.Account.Properties["access_token"]; JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(accessToken); await SecureStorage.SetAsync(ApiAuthentication.AccessTokenKey, accessToken); await SecureStorage.SetAsync(ApiAuthentication.UserIdKey, jwtSecurityToken.UserId().ToString()); await SecureStorage.SetAsync(ApiAuthentication.UserNameKey, jwtSecurityToken.UserName()); await SecureStorage.SetAsync(ApiAuthentication.ProviderNameKey, jwtSecurityToken.ProviderName()); Authenticated?.Invoke(this, EventArgs.Empty); } }; Authenticator.Error += (sender, args) => { }; }
private void Awake() { Connected.AddListener(OnRoomClientConnected); Authenticated.AddListener(OnRoomClientAuthenticated); Disconnected.AddListener(OnRoomClientDisConnected); //_networkManager.SceneManager.ClientChangeScene.AddListener((str, load) => { Debug.Log("[Client Scene Changed!]"); }); }
IAuthenticated IConfigurable.Authenticate(AzureCredentials credentials) { var authenticated = new Authenticated(BuildRestClient(credentials), credentials.TenantId); authenticated.SetDefaultSubscription(credentials.DefaultSubscriptionId); return(authenticated); }
private static void Client_Authenticated(object sender, EventArgs e) { if (Authenticated != null) { Authenticated.Invoke(sender, e); } }
/// <summary> /// Invokes <see cref="Authenticated"/> event into the current context. /// </summary> internal void OnAuthenticated() { ContextPost(delegate { Authenticated?.Invoke(); }); }
private void OnAuthenticated(bool isAuthenticated, ResponseMessage authReponseMessage) { IsAuthenticated = isAuthenticated; OnResultReceived(authReponseMessage); Authenticated?.Invoke(this, EventArgs.Empty); }
public async void Register() { bool result = await FirebaseAuthHelper.Register(User); if (result) { Authenticated?.Invoke(this, new EventArgs()); } }
internal void OnAuthenticated(NetConnection con, UserHandle handle) { _awaitingActions.Enqueue(() => { var uID = con.RemoteUniqueIdentifier; Handles[uID] = handle; _connections.Add(Handles[uID], con); Authenticated?.Invoke(this, new ConnectionEventArgs(Handles[uID])); }); }
internal void OnAuthenticated(INetworkPlayer player) { if (logger.LogEnabled()) { logger.Log("Server authenticate client:" + player); } Authenticated?.Invoke(player); }
internal void OnAuthenticated(INetworkConnection conn) { if (logger.LogEnabled()) { logger.Log("Server authenticate client:" + conn); } Authenticated?.Invoke(conn); }
public async Task Login() { bool result = await FirebaseAuthHelper.Login(User); if (result) { Authenticated?.Invoke(this, new EventArgs()); } }
public AuthenticationStatus Authenticate(NetIncomingMessage msg, out UserHandle handle) { handle = new UserHandle() { UserID = 0, ConnectionID = msg.SenderConnection.RemoteUniqueIdentifier }; Authenticated?.Invoke(this, handle); return(AuthenticationStatus.OK); }
void Awake() { Started.AddListener(OnRoomStartServer); Stopped.AddListener(OnRoomStopServer); Connected.AddListener(OnRoomServerConnected); Authenticated.AddListener(OnRoomServerAuthenticated); Disconnected.AddListener(OnRoomServerDisConnected); OnStartHost.AddListener(OnRoomStartHost); OnStopHost.AddListener(OnRoomStopHost); }
public async Task Authenticate(string successUrl = null, string errorUrl = null, params Scope[] scopes) { Log.Debug("Authenticating with HSReplay.net..."); Authenticating?.Invoke(true); try { var data = await GetAuthData(successUrl ?? SuccessUrl, errorUrl ?? ErrorUrl); if (data == null) { Log.Error("Authentication failed, received no data"); AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); return; } _data.Code = data.Code; _data.RedirectUrl = data.RedirectUrl; _data.TokenData = null; } catch (Exception e) { Log.Error(e); AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); return; } Log.Debug("Authentication complete"); try { await UpdateToken(); Log.Debug("Claiming upload token if necessary"); if (_account.TokenStatus == TokenStatus.Unknown) { await _api.UpdateTokenStatus(); } if (_account.TokenStatus == TokenStatus.Unclaimed) { await ClaimUploadToken(_account.UploadToken); } Log.Debug("Updating account data"); if (!await UpdateAccountData()) { AuthenticationError?.Invoke(AuthenticationErrorType.AccountData); } } catch (Exception e) { AuthenticationError?.Invoke(AuthenticationErrorType.Unknown); Log.Error(e); } finally { Authenticating?.Invoke(false); Authenticated?.Invoke(); } }
public static async Task <bool> Authenticate(string successUrl = null, string errorUrl = null) { Log.Info("Authenticating with HSReplay.net..."); string url; try { url = Client.Value.GetAuthenticationUrl(_requiredScopes, Ports); } catch (Exception e) { Log.Error(e); return(false); } if (string.IsNullOrEmpty(url)) { Log.Error("Authentication failed, could not create callback listener"); return(false); } var callbackTask = Client.Value.ReceiveAuthenticationCallback(successUrl ?? SuccessUrl, errorUrl ?? ErrorUrl); if (!Helper.TryOpenUrl(url)) { ErrorManager.AddError("Could not open your browser.", "Please open the following url in your browser to continue:\n\n" + url, true); } Log.Info("Waiting for callback..."); var data = await callbackTask; if (data == null) { Log.Error("Authentication failed, received no data"); return(false); } Data.Value.Code = data.Code; Data.Value.RedirectUrl = data.RedirectUrl; Data.Value.TokenData = null; Log.Info("Authentication complete"); await UpdateToken(); Save(); Log.Info("Claiming upload token if necessary"); if (!Account.Instance.TokenClaimed.HasValue) { await ApiWrapper.UpdateUploadTokenStatus(); } if (Account.Instance.TokenClaimed == false) { await ClaimUploadToken(Account.Instance.UploadToken); } Authenticated?.Invoke(); return(true); }
public virtual Task <IEnumerable <ResourceGroup> > GetResourceGroupsBySubscriptionAsync(string subscriptionId) { var groups = Authenticated .WithSubscription(subscriptionId) .ResourceGroups .List(); var result = groups.Select(g => new ResourceGroup { Name = g.Name, }); return(Task.FromResult(result)); }
protected override void Execute(CodeActivityContext context) { using (var principalContext = new PrincipalContext(ContextType.Domain)) { using (SecureStringToStringMarshaler sm = new SecureStringToStringMarshaler(Password.Get(context))) { bool authenticated = principalContext.ValidateCredentials(Username.Get(context), sm.String); UserPrincipal principal = UserPrincipal.FindByIdentity(principalContext, Username.Get(context)); Authenticated.Set(context, authenticated); Email.Set(context, principal.EmailAddress); GivenName.Set(context, principal.GivenName); } } }
private void ServerReadyReceived(AsynchronousSocket socket) { byte[] message = SRP6.SubArray( socket.ReceiveBuffer, 0, socket.ReceiveBufferLength); string strMessage = SRP6.ArrayToString(message, 0, message.Length); // Server and client are now both ready for encrypted communications if (strMessage.Equals("READY")) { OnDebug("Received \"READY\" from server"); step++; if (Authenticated != null) { Authenticated.Invoke(this, new EventArgs()); } if (crashReportOnly) { // Request to send a crash report to the server OnDebug("Telling server we want to upload a crash report"); try { byte[] serializedObject = CrashException.SerializeObject(); socket.SendStream = new MemoryStream(serializedObject); socket.EncryptedSendStream = srpClient.Encrypt(socket.SendStream); srpClient.EncryptAndSend(socket, "SUBMIT_CRASH " + socket.SendStream.Length + " " + socket.EncryptedSendStream.Length); } catch (Exception ex) { OnDebug("Exception: " + ex.Message); } } else { // Request the current version OnDebug("Sending version-check request to server"); isCheckingVersion = true; srpClient.EncryptAndSend(socket, "VERSION"); } } else { OnDebug("Authentication Failed"); socket.Disconnect(); } }
/// <summary> /// Prüft ob der CLient auch wirklich der ist, der er zu sein scheint. /// </summary> /// <param name="iar"></param> private void FirstCommand(IAsyncResult iar) { int len = _IcSckt.EndReceive(iar); if (len != sizeof(int)) { Disconnect(); return; } int packetLen = _Br.ReadInt32(); if (packetLen > _InBuffer.Length) { Disconnect(); return; } if (!NetUtils.ReceiveAll(_InBuffer, _IcSckt, packetLen, (int)_MsIn.Position)) { Disconnect(); return; } InterComCommand cmd = (InterComCommand)_Br.ReadInt32(); if (cmd != InterComCommand.Initiate) { Disconnect(); return; } ulong auth = _Br.ReadUInt64(); if (auth != _AuthToken) { Disconnect(); return; } if (Authenticated == null) { Disconnect(); return; } Authenticated.Invoke(this); }
public async Task <bool> IsAuthenticatedAsync() { var result = await authenticationStateProvider.GetAuthenticationStateAsync(); _principal = result.User; if (_principal != null) { var userId = _principal.FindFirstValue("sub"); if (userId != null) { _user = await GetUserById(userId); Authenticated?.Invoke(); } } return(IsAuthenticated()); }
public async Task <bool> InitializeAsync(AuthenticationStateProvider authenticationStateProvider) { var authenticationState = await authenticationStateProvider.GetAuthenticationStateAsync(); Principal = authenticationState.User; var name = Principal.Identity.Name; if (env.EnvironmentName == "Development" && name == "admin") { user = new ApplicationUser { UserName = name }; } if (user == null && name != null) { await semaphoreSlim.WaitAsync(); try { user = await userManager.FindByEmailAsync(name); if (user == null) { user = await userManager.FindByNameAsync(name); } } finally { semaphoreSlim.Release(); } } var result = IsAuthenticated(); if (result) { Authenticated?.Invoke(); } return(result); }
public void WebBrowser1_Navigated(object o, WebBrowserNavigatedEventArgs e) { if (webBrowser1.Url.OriginalString.StartsWith("http://localhost/")) { int start = webBrowser1.Url.OriginalString.IndexOf("access_token") + "access_token".Length + 1; int stop = webBrowser1.Url.OriginalString.IndexOf("&", start); string token = webBrowser1.Url.OriginalString.Substring(start, stop - start); string[] headers = new string[] { "Authorization: OAuth " + token, "Client-ID: " + ChatForm.client_id }; string name = HelperFunctions.JsonGet("https://api.twitch.tv/kraken/user?authorization=oauth+" + token + "&client_id=" + ChatForm.client_id, headers).name; dynamic auth = new Auth(); auth.username = name; auth.oauth = token; Authenticated?.Invoke(this, auth); Close(); } }
void onAuthenticated(Authenticated ev) { if (ev.IsAuthenticated) { string accountName = (ev.Target.Tag as PlayerData).AccountName; Actor actor = Context.Server.SpawnActor <PlayerActorDefinition>(ev.Target, new SlimMath.Vector3(0, 10, 0)); actor.GetValue <string>("Name").Value = accountName; base.PlayerJoined(ev.Target); actor.RaiseEvent <ChatMessage>((chat) => { chat.Message = string.Format("<{0} joined the game>", accountName); }); } else { if ((ev.Target.Tag as PlayerData).LoginAttempts++ == 3) { ev.Target.Disconnect(); } } }
protected virtual void OnAuthenticated() { Authenticated?.Invoke(this, EventArgs.Empty); }
void onAuthenticated(Authenticated ev) { if (ev.IsAuthenticated) { string accountName = (ev.Target.Tag as PlayerData).AccountName; Actor actor = Context.Server.SpawnActor<PlayerActorDefinition>(ev.Target, new SlimMath.Vector3(0, 10, 0)); actor.GetValue<string>("Name").Value = accountName; base.PlayerJoined(ev.Target); actor.RaiseEvent<ChatMessage>((chat) => { chat.Message = string.Format("<{0} joined the game>", accountName); }); } else { if ((ev.Target.Tag as PlayerData).LoginAttempts++ == 3) { ev.Target.Disconnect(); } } }
internal void onPenAuthenticated() { Authenticated?.Invoke(PenClient, new object()); }
private void ParsePacket(UsbPacket pk) { Cmd cmd = (Cmd)pk.Cmd; //System.Diagnostics.Debug.WriteLine( "Cmd : {0}", cmd.ToString() ); switch (cmd) { case Cmd.START: { isFirstStatus = true; int protocolVersion = pk.GetInt(); bool available = pk.GetByte() == 0x01; if (available) { GetDeviceInfoRequest(); } else { ConnectionRefused?.Invoke(this, null); } } break; case Cmd.GETDEVINFO: { DeviceName = pk.GetString(16); FirmwareVersion = pk.GetString(16); BluetoothProtocolVersion = pk.GetString(8); SubName = pk.GetString(16); MacAddress = BitConverter.ToString(pk.GetBytes(6)).Replace("-", ":"); BluetoothModelName = pk.GetString(32); GetConfigRequest(ConfigType.AutoPowerOffTime, ConfigType.AutoPowerOn, ConfigType.Beep, ConfigType.DownSampling, ConfigType.PenCapOff, ConfigType.SaveOfflineData); } break; case Cmd.GETDISKINFO: { pk.Move(1); var total = pk.GetInt(); var free = pk.GetInt(); StorageStatusReceived?.Invoke(this, new StorageStatusReceivedEventArgs(total, free)); } break; case Cmd.GETCONFIG: { int typeCount = pk.GetByteToInt(); for (int i = 0; i < typeCount; i++) { int type = pk.GetByteToInt(); switch ((ConfigType)type) { case ConfigType.DateTime: long timestamp = pk.GetLong(); DateTimeReceived?.Invoke(this, new DateTimeReceivedEventArgs(timestamp)); break; case ConfigType.AutoPowerOffTime: //AutoPowerOffTime = new TimeSpan( 0, pk.GetShort(), 0); AutoPowerOffTime = TimeSpan.FromMinutes(pk.GetShort()); if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.AutoPowerOffTime, true)); } break; case ConfigType.AutoPowerOn: IsAutoPowerOnEnabled = pk.GetByteToInt() == 0x01; if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.AutoPowerOn, true)); } break; case ConfigType.PenCapOff: IsPenCapOffEnabled = pk.GetByteToInt() == 0x01; if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.PenCapOff, true)); } break; case ConfigType.Beep: IsBeepEnabled = pk.GetByteToInt() == 0x01; if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.Beep, true)); } break; case ConfigType.SaveOfflineData: CanSaveOfflineData = pk.GetByteToInt() == 0x01; if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.SaveOfflineData, true)); } break; case ConfigType.DownSampling: IsDownsamplingEnabled = pk.GetByteToInt() == 0x01; if (!isFirstStatus) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.DownSampling, true)); } break; case ConfigType.Battery: var battery = pk.GetByteToInt(); BatteryStatusReceived?.Invoke(this, new BatteryStatusReceivedEventArgs(battery)); break; } } if (isFirstStatus) { IsActive = true; Authenticated?.Invoke(this, null); isFirstStatus = false; } } break; case Cmd.SETCONFIG: { int typeCount = pk.GetByteToInt(); for (int i = 0; i < typeCount; i++) { int type = pk.GetByteToInt(); bool result = pk.GetByteToInt() == 0x00; if (result) { if ((ConfigType)type == ConfigType.DateTime) { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs(ConfigType.DateTime, true)); } else { GetConfigRequest((ConfigType)type); } } else { ConfigSetupResultReceived?.Invoke(this, new ConfigSetupResultReceivedEventArgs((ConfigType)type, false)); } } } break; case Cmd.FORMAT: { bool result = pk.GetByteToInt() == 0x00; FormatResultReceived?.Invoke(this, new ResultReceivedEventArgs(result ? ResultReceivedEventArgs.ResultType.Success : ResultReceivedEventArgs.ResultType.Failed)); } break; case Cmd.GETOFFLINEDATALIST: case Cmd.GETLOGFILELIST: { int result = pk.GetByteToInt(); int fileCount = pk.GetInt(); var resultList = new List <string>(); for (int i = 0; i < fileCount; i++) { string fileName = pk.GetString(16); resultList.Add(fileName); } FileListReceivedEventArgs.ResultType resultType; if (result == 0) { resultType = FileListReceivedEventArgs.ResultType.Success; } else if (result == 1) { resultType = FileListReceivedEventArgs.ResultType.Failed; } else if (result == 2) { resultType = FileListReceivedEventArgs.ResultType.TooManyFileExists; } else { resultType = FileListReceivedEventArgs.ResultType.UnknownError; } if (pk.Cmd == Cmd.GETOFFLINEDATALIST) { OfflineFileListReceived?.Invoke(this, new FileListReceivedEventArgs(resultType, resultList.ToArray())); } else { LogFileListReceived?.Invoke(this, new FileListReceivedEventArgs(resultType, resultList.ToArray())); } } break; case Cmd.GETFILE_H: { bool result = pk.GetByteToInt() == 0x00; int fileSize = pk.GetInt(); int packetSize = pk.GetInt() - 8; if (fileRequestInfo) { FileInfoReceived?.Invoke(this, new FileInfoReceivedEventArgs(result ? FileInfoReceivedEventArgs.ResultType.Success : FileInfoReceivedEventArgs.ResultType.FileNotExists, requestFileName, fileSize)); } else { if (!result) { FileDownloadResultReceived?.Invoke(this, new FileDownloadResultReceivedEventArgs(FileDownloadResultReceivedEventArgs.ResultType.FileNotExists)); } else { fileSerializer = new FileBuilder(targetFilePath, fileSize, packetSize); downloadRetryCount = 0; FileDownloadProgressChanged?.Invoke(this, new ProgressChangedEventArgs(0)); GetFilePacketRequest(0); } } } break; case Cmd.GETFILE_D: { int result = pk.GetByteToInt(); int offset = pk.GetInt(); int dataLength = pk.GetInt(); byte[] data = pk.GetBytes(dataLength); if (result == 0x00) { fileSerializer.Put(data, offset); int progress = (int)((double)offset / (double)(fileSerializer.FileSize - 1)); if (fileSerializer.GetNextOffset() < fileSerializer.FileSize) { FileDownloadProgressChanged?.Invoke(this, new ProgressChangedEventArgs(progress)); GetFilePacketRequest(fileSerializer.GetNextOffset()); } else { bool fileCreated = fileSerializer.MakeFile(); if (fileCreated) { FileDownloadProgressChanged?.Invoke(this, new ProgressChangedEventArgs(100)); } FileDownloadResultReceived?.Invoke(this, new FileDownloadResultReceivedEventArgs(fileCreated ? FileDownloadResultReceivedEventArgs.ResultType.Success : FileDownloadResultReceivedEventArgs.ResultType.Failed)); } } else { if (downloadRetryCount++ > 3) { FileDownloadResultReceivedEventArgs.ResultType resultType; if (result == 0x1) { resultType = FileDownloadResultReceivedEventArgs.ResultType.Failed; } else if (result == 0x10) { resultType = FileDownloadResultReceivedEventArgs.ResultType.OffsetInvalid; } else if (result == 0x11) { resultType = FileDownloadResultReceivedEventArgs.ResultType.CannotOpenFile; } else { resultType = FileDownloadResultReceivedEventArgs.ResultType.UnknownError; } FileDownloadResultReceived?.Invoke(this, new FileDownloadResultReceivedEventArgs(resultType)); } else { GetFilePacketRequest(offset); } } } break; case Cmd.DELETEFILE: { bool result = pk.GetByteToInt() == 0x00; DeleteFileResultReceived?.Invoke(this, new ResultReceivedEventArgs(result ? ResultReceivedEventArgs.ResultType.Success : ResultReceivedEventArgs.ResultType.Failed)); } break; case Cmd.POWEROFF: { bool result = pk.GetByteToInt() == 0x00; PowerOffResultReceived?.Invoke(this, new ResultReceivedEventArgs(result ? ResultReceivedEventArgs.ResultType.Success : ResultReceivedEventArgs.ResultType.Failed)); } break; case Cmd.UPDATE_START: { int result = pk.GetByteToInt(); int packetSize = pk.GetInt() - 8; if (result == 0x00 && fileSplitter != null) { updateRetryCount = 0; if (fileSplitter.Split(packetSize) && fileSplitter.PacketCount > 0) { UpdateProgressChanged?.Invoke(this, new ProgressChangedEventArgs(0)); UpdatePacketUploadRequest(0, fileSplitter.GetBytes(0)); } else { isUpdating = false; UpdateResultReceived?.Invoke(this, new UpdateResultReceivedEventArgs(UpdateResultReceivedEventArgs.ResultType.DeviceIsNotCorrect)); } } else { isUpdating = false; UpdateResultReceived?.Invoke(this, new UpdateResultReceivedEventArgs(result == 1 ? UpdateResultReceivedEventArgs.ResultType.DeviceIsNotCorrect : UpdateResultReceivedEventArgs.ResultType.FirmwareVersionIsNotCorrect)); } } break; case Cmd.UPDATE_DO: { if (!isUpdating) { return; } int result = pk.GetByteToInt(); int offset = pk.GetInt(); if (result == 0x00) { updateRetryCount = 0; if (offset + fileSplitter.PacketSize >= fileSplitter.FileSize - 1) { UpdateProgressChanged?.Invoke(this, new ProgressChangedEventArgs(100)); UpdateResultReceived?.Invoke(this, new UpdateResultReceivedEventArgs(UpdateResultReceivedEventArgs.ResultType.Complete)); } else { int progress = (int)((double)offset / (double)(fileSplitter.FileSize - 1) * 100); UpdateProgressChanged?.Invoke(this, new ProgressChangedEventArgs(progress)); UpdatePacketUploadRequest(offset + fileSplitter.PacketSize, fileSplitter.GetBytes(offset + fileSplitter.PacketSize)); } } else { System.Diagnostics.Debug.WriteLine("UPDATE_DO : {0} {1}", offset, result); if (updateRetryCount++ > 3) { UpdateResultReceived?.Invoke(this, new UpdateResultReceivedEventArgs(UpdateResultReceivedEventArgs.ResultType.UnknownError)); } else { UpdatePacketUploadRequest(offset, fileSplitter.GetBytes(offset)); } } } break; } }
internal void OnAuthenticated(INetworkPlayer player) { Authenticated?.Invoke(player); }
private void smartCardState_Authenticated(object sender, SmartCardEventArgs e) { Authenticated.InvokeIfAssigned(sender, e); }
protected virtual void OnAuthentication(ITwitchAccount account, bool authenticated) { Authenticated?.Invoke(this, new ChatConnectionAuthenticatedEventArgs(account, authenticated)); }