/// <summary> /// Determines whether or the access is near expiration. /// </summary> /// <returns><c>true</c> if near expiration; otherwise <c>false</c>.</returns> public bool IsNearExpiry() { return(DateTime.UtcNow > ExpiresOn.AddMinutes(-1)); }
/// <summary> /// Update token if token has been expired. /// </summary> public void UpdateToken() { if (ExpiresOn > DateTime.UtcNow) { return; } Debug.WriteLine("Need new token"); lock (lockUpdateProcess) { Debug.WriteLine("Enter to critical section of getting token"); if (ExpiresOn <= DateTime.UtcNow && !IsProcessing) { Debug.WriteLine("Start getting token"); string newToken = null; Exception exception = null; try { if (_authenticationService != null) { IsProcessing = true; #if DEBUG //Thread.Sleep(3000); #endif //get url for scope authenticate var dataServicesBaseUri = new Uri(BaseUrl); // get new token newToken = _authenticationService.AuthenticateUser(UserName, Password, dataServicesBaseUri); Debug.WriteLine("Token updated"); if (!String.IsNullOrEmpty(newToken)) { // Parse token var swToken = Foundation.Security.Swt.SimpleWebToken.Parse(newToken); Token = newToken; ExpiresOn = swToken.ExpiresOn; ExpiresOn = ExpiresOn.AddMinutes(-(ExpiresOn - DateTime.UtcNow).TotalMinutes / 2); CurrentUserId = swToken.Claims.Where(x => x.Key == ClaimTypes.NameIdentifier) .Select(x => x.Value) .FirstOrDefault(); CurrentUserName = swToken.Claims.Where(x => x.Key == ClaimTypes.Name) .Select(x => x.Value) .FirstOrDefault(); var registrationType = swToken.Claims.Where(x => x.Key == SecurityClaims.AccountRegistrationType).Select(x => x.Value).FirstOrDefault(); if (!String.IsNullOrEmpty(registrationType)) { RegistrationType = (RegisterType)Enum.Parse(typeof(RegisterType), registrationType); } var permissions = swToken.Claims.Where(x => x.Key == SecurityClaims.AccountPermission) .Select(x => x.Value) .ToArray(); Permissions = permissions; } } } catch (Exception e) { exception = new GetTokenException(e.Message); } finally { IsProcessing = false; } if (exception == null && String.IsNullOrEmpty(newToken)) { exception = new GetTokenException(Resources.Login_or_password_is_incorrect); } if (exception != null) { throw exception; } } Debug.WriteLine("Exit from critical section of getting token"); } }