private async Task <User> GetUserAndSaveOnStoreAsync(string key) { IEnumerable <Claim> claims; ClaimsPrincipal user; if (_context.Items[GlobalConstants.TemporaryUserKey] is ClaimsPrincipal temporaryUser) { claims = temporaryUser.Claims; user = temporaryUser; } else if (_context.User.Identity is WindowsIdentity) { claims = _windowsIdentityService.GetIdentityClaims(); user = _context.User; } else { claims = _context.User.Claims; user = _context.User; } var applicationUser = new User { FirstName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value, LastName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname)?.Value, Email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value, AdAccount = (AdAccount)claims.FirstOrDefault(c => c.Type == ClaimTypes.WindowsAccountName)?.Value, IsAuthenticated = user.HasClaim(c => c.Type == RuleTypes.User) }; if (Guid.TryParse(claims.FirstOrDefault(c => c.Type == RuleTypes.Guid)?.Value, out Guid windowsGuid)) { applicationUser.AdGuid = (Token)windowsGuid; } var options = new DistributedCacheEntryOptions(); if (DateTime.TryParseExact( user.FindFirst(c => c.Type == RuleTypes.ValidTo)?.Value, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime expiresUtc)) { options.SetAbsoluteExpiration(expiresUtc); } else { options.SetSlidingExpiration(TimeSpan.FromMinutes(30)); } await _cache.SetAsync(key, applicationUser, options, _cancel); return(applicationUser); }
public async Task InvokeAsync( HttpContext context, IWindowsIdentityService windowsIdentityService, IMediator mediator) { if (!context.User.HasClaim(claim => claim.Type == RuleTypes.User) && windowsIdentityService.Identity != null) { try { var token = await mediator.Send( new AuthenticateOnRestServiceQuery { TemporaryToken = (Token)windowsIdentityService.Identity.Guid.Value }); (ClaimsPrincipal principal, SecurityToken authToken) = _jsonWebTokenService.ValidateToken(token); var claims = new List <Claim> { new Claim( RuleTypes.User, "true", ClaimValueTypes.Boolean, authToken.Issuer, authToken.Issuer), new Claim( RuleTypes.Token, token, ClaimValueTypes.String, authToken.Issuer, authToken.Issuer), new Claim( RuleTypes.ValidTo, authToken.ValidTo.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), ClaimValueTypes.DateTime, authToken.Issuer, authToken.Issuer) }; claims.AddRange(principal.Claims); claims.AddRange(windowsIdentityService.GetIdentityClaims()); var user = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)); var authenticationProperties = new AuthenticationProperties() { ExpiresUtc = authToken.ValidTo, AllowRefresh = true, IsPersistent = true }; await context.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, user, authenticationProperties); context.Items[GlobalConstants.TemporaryUserKey] = user; } catch (System.Exception ex) { throw new RestAuthenticationException( context.User != null, windowsIdentityService.Identity != null, ex); } } }