private bool TestCommand(SetToken evt, out IEvent e) { e = null; if (user == null) { return(false); } if (user.Tokens == null) { e = new TokenAdded(evt.LoginProvider, evt.Name, evt.Value); } else { ImmutableIdentityUserToken token = user.Tokens.FirstOrDefault(x => x.LoginProvider.Equals(evt.LoginProvider) && x.Name.Equals(evt.Name)); if (token == default(ImmutableIdentityUserToken)) { e = new TokenAdded(evt.LoginProvider, evt.Name, evt.Value); } else if (token.Value.Equals(evt.Value)) { e = new TokenUpdated(evt.LoginProvider, evt.Name, evt.Value); } } return(true); }
private void HandleEvent(IActorRef _, TokenUpdated evt) { var tokens = user.Tokens.Where(x => x.LoginProvider.Equals(evt.LoginProvider) && x.Name.Equals(evt.Name)).ToList(); foreach (var tkn in tokens) { user.Tokens.Remove(tkn); } user.Tokens.Add(new ImmutableIdentityUserToken(evt.LoginProvider, evt.Name, evt.Value)); }
public void TestSerializationOfTokenUpdated() { var evt = new TokenUpdated("LOGINPROVIDER", "NAME", "VALUE"); var bytes = LZ4MessagePackSerializer.Serialize <IEvent>(evt, AspnetIdentityResolver.Instance); var eventChk = LZ4MessagePackSerializer.Deserialize <IEvent>(bytes, AspnetIdentityResolver.Instance) as TokenUpdated; Assert.Equal(evt.LoginProvider, eventChk.LoginProvider); Assert.Equal(evt.Name, eventChk.Name); Assert.Equal(evt.Value, eventChk.Value); }
public async Task Initialize() { await _spotifyNativeApi.AttachToProcess(ProcessFound, ProcessExited); _songStatusWatcher = new Timer(SongTimerChanging, null, 1000, 1000); JoinBackgroundProcess(); _spotifyWebApi.TokenUpdated += (sender, args) => { TokenUpdated?.OnNext(args); }; }
public virtual async Task Initialize() { _timer = new Timer(async state => { await _client.Authenticate(_appSettings.SpotifyToken.RefreshToken, GrantType.RefreshToken).ConfigureAwait(false); }); _client = new SpotifyHttpClient(SpotifyApiUrl, _log, RedirectUrl, _appSettings, token => { TokenUpdated?.Invoke(this, null); _timer.Change((token.ExpiresIn - 15) * 1000, int.MaxValue); }); if (_appSettings.SpotifyToken != null) { await _client.Authenticate(_appSettings.SpotifyToken.RefreshToken, GrantType.RefreshToken).ConfigureAwait(false); } }
public async Task RefereshAuthenticationAsync() { _httpClient.DefaultRequestHeaders.Remove("Authorization"); if (!string.IsNullOrEmpty(_tokenHolder.RefreshToken.ToInsecureString())) { try { _logger.LogInformation($"Getting a new access token using refresh token"); var scopes = _tokenHolder.Scopes; var tokenInfoResponse = await RefreshOpenIdTokenAsync(_tokenHolder.RefreshToken, scopes); _logger.LogInformation($"Obtained a new access token using refresh token"); var tokens = new TokenHolder(tokenInfoResponse, scopes); SetTokens(tokens); // fire the 'token updated' event TokenUpdated?.Invoke(tokens); return; } catch (Exception ex) { _logger.LogInformation(ex, "Could not refersh access token using the refresh_token"); } } // authenticate again (using credentials or whatever the handler can do for us) if (_authHandler != null) { _logger.LogInformation($"Getting a new access token using {_authHandler.GetType()}"); var tokens = await _authHandler.AuthenticateAsync(); _logger.LogInformation($"Obtained a new access token using {_authHandler.GetType()}"); SetTokens(tokens); // fire the 'token updated' event TokenUpdated?.Invoke(tokens); } else { throw new AuthenticationException( "Unable to refresh access token and there is no way to re-authenticate."); } }
public async Task RefreshToken() { string commandUrl = "token?grant_type=refresh_token" + $"&refresh_token={Token.RefreshToken}" + $"&client_id={Client.ID}" + $"&client_secret={Client.Secret}"; JsonValue response = await Client.Auth.PostAsync(commandUrl); string accessToken = response["access_token"]; string refreshToken = response["refresh_token"]; int expiresIn = response["expires_in"]; string[] scopes = response["scope"].ToArray(); Token.Refresh(accessToken, refreshToken, expiresIn, scopes); SaveToken(_Token); TokenUpdated?.Invoke(this, EventArgs.Empty); }
public void BeginAuthentication() { if (Authenticated || Authenticating) { return; } Authenticating = true; redirectServer.Start(); string state = "555555"; RequestAuthentication(state); EndAuthentication(state) .ContinueWith(t => { Token = t.Result; TokenUpdated?.Invoke(this, EventArgs.Empty); }); }
public async Task <bool> Logout(User user) { _userRepository.RemoveAll(); _userUuid = Guid.Empty; try { using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse(user.AccessToken.ToString()); var response = await httpClient.PostAsync(LogoutUri, new StringContent("{}", Encoding.UTF8, BaseService.ApplicationJson)); var jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); } } catch (Exception e) { Console.WriteLine(e); } _userIsAuthorized = false; TokenUpdated?.Invoke(this, EventArgs.Empty); try { Mvx.IoCProvider.Resolve <IFirebaseService>()?.DeleteInstance(Secrets.SenderId); } catch (Exception e) { Console.WriteLine(e); } return(true); }
protected virtual void OnTokenUpdated(TokenUpdateEventArgs e) { TokenUpdated?.Invoke(this, e); }
/// <nodoc /> public void UpdateToken(SasToken token) { Contract.Requires(token != null); Token = token; TokenUpdated?.Invoke(this, token); }
public async Task <User> Login(AuthDto authData) { try { var service = Mvx.IoCProvider.Resolve <IFirebaseService>(); if (service != null) { authData.DeviceToken = await service.CreateToken(Secrets.SenderId); } } catch (Exception e) { Crashes.TrackError(e, new Dictionary <string, string>()); Console.WriteLine(e); } var json = JsonConvert.SerializeObject(authData); Debug.WriteLine(json); var response = await _httpClient.PostAsync(LoginUri, new StringContent(json, Encoding.UTF8, BaseService.ApplicationJson)); var jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); if (string.IsNullOrEmpty(jsonString)) { Error = "Нет ответа от сервера"; return(null); } var data = JsonConvert.DeserializeObject <ResponseDto <UserDto> >(jsonString); if (response.IsSuccessStatusCode) { if (!data.Success) { return(_mapper.Map <User>(data.Data)); } var user = _mapper.Map <User>(data.Data.Client); var userInfo = _mapper.Map <User>(data.Data.ClientInfo); userInfo.Role = user.Role; userInfo.Uuid = user.Uuid; userInfo.Email = user.Email ?? string.Empty; userInfo.Phone = user.Phone ?? string.Empty; userInfo.Name = user.Name ?? string.Empty; userInfo.Login = user.Login ?? string.Empty; userInfo.AccessToken = new AccessToken { Body = data.Data.Body, Type = data.Data.Type }; if (string.IsNullOrEmpty(userInfo.AccessToken.Body) && userInfo.Uuid != Guid.Empty) { return(userInfo); } _userUuid = userInfo.Uuid; _userRepository.RemoveAll(); _userRepository.Add(userInfo); _userIsAuthorized = true; TokenUpdated?.Invoke(this, EventArgs.Empty); return(userInfo); } if (data.ErrorDetails != null) { ErrorDetails = data.ErrorDetails; } Error = data.Error; return(null); }
public async Task <User> AuthorizationAnExternalService(string email, string accessToken, ExternalAuthService authServiceType) { var request = new Dictionary <string, string> { { "email", email }, { "access_token", accessToken }, }; switch (authServiceType) { case ExternalAuthService.Vk: request.Add("service", "vk"); break; case ExternalAuthService.Facebook: request.Add("service", "facebook"); break; default: throw new ArgumentOutOfRangeException(nameof(authServiceType), authServiceType, null); } try { var service = Mvx.IoCProvider.Resolve <IFirebaseService>(); if (service != null) { var deviceToken = await service.CreateToken(Secrets.SenderId); if (!string.IsNullOrWhiteSpace(deviceToken)) { request.Add("device_token", deviceToken); } } } catch (Exception e) { Crashes.TrackError(e, new Dictionary <string, string>()); Console.WriteLine(e); } var response = await _httpClient.PostAsync(AuthorizationAnExternalServiceUri, new FormUrlEncodedContent(request)); var jsonString = await response.Content.ReadAsStringAsync(); Debug.WriteLine(jsonString); if (string.IsNullOrEmpty(jsonString)) { Error = "Нет ответа от сервера"; return(null); } var data = JsonConvert.DeserializeObject <ResponseDto <UserDto> >(jsonString); if (response.IsSuccessStatusCode) { if (!data.Success) { return(_mapper.Map <User>(data.Data)); } var user = _mapper.Map <User>(data.Data.Client); var userInfo = _mapper.Map <User>(data.Data.ClientInfo); userInfo.Role = user.Role; userInfo.Uuid = user.Uuid; userInfo.Email = user.Email ?? string.Empty; userInfo.Phone = user.Phone ?? string.Empty; userInfo.Name = user.Name ?? string.Empty; userInfo.Login = user.Login ?? string.Empty; userInfo.AccessToken = new AccessToken { Body = data.Data.Body, Type = data.Data.Type }; if (string.IsNullOrEmpty(userInfo.AccessToken.Body) && userInfo.Uuid != Guid.Empty) { return(userInfo); } _userUuid = userInfo.Uuid; _userRepository.Add(userInfo); TokenUpdated?.Invoke(this, EventArgs.Empty); return(userInfo); } if (data.ErrorDetails != null) { ErrorDetails = data.ErrorDetails; } Error = data.Error; return(null); }