public async Task ValidatePrincipal(CookieValidatePrincipalContext context) { // TODO: uncomment this after next release of aspnet core // and fix the broken // it needs to resolve options per tenant //await securityStampValidator.ValidateAsync(context); TenantContext<SiteSettings> siteContext = await siteResolver.ResolveAsync(contextAccessor.HttpContext); if (siteContext == null) { context.RejectPrincipal(); } if (siteContext.Tenant == null) { context.RejectPrincipal(); } Claim siteGuidClaim = new Claim("SiteGuid", siteContext.Tenant.SiteGuid.ToString()); if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value)) { log.LogInformation("rejecting principal because it does not have siteguid"); context.RejectPrincipal(); } // return Task.FromResult(0); }
public async Task OnValidatePrincipalTestSuccess(bool isPersistent) { var user = new TestUser("test"); var userManager = MockHelpers.MockUserManager<TestUser>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var options = new Mock<IOptions<IdentityOptions>>(); options.Setup(a => a.Options).Returns(identityOptions); var httpContext = new Mock<HttpContext>(); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object, null); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable(); signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable(); var services = new ServiceCollection(); services.AddInstance(options.Object); services.AddInstance(signInManager.Object); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, IdentityOptions.ApplicationCookieAuthenticationScheme); var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Principal); await SecurityStampValidator.ValidatePrincipalAsync(context); Assert.NotNull(context.Principal); signInManager.VerifyAll(); }
public async Task OnValidatePrincipalThrowsWithEmptyServiceCollection() { var httpContext = new Mock<HttpContext>(); httpContext.Setup(c => c.RequestServices).Returns(new ServiceCollection().BuildServiceProvider()); var id = new ClaimsPrincipal(new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme)); var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }, IdentityOptions.ApplicationCookieAuthenticationScheme); var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => SecurityStampValidator.ValidatePrincipalAsync(context)); Assert.True(ex.Message.Contains("No service for type 'Microsoft.Framework.OptionsModel.IOptions")); }
public async Task ValidateAsync(CookieValidatePrincipalContext context) { string userId = context.Principal.GetUserId(); var principal = await ValidateSecurityStamp(context.Principal, userId); if (principal != null) { context.ReplacePrincipal(principal); context.ShouldRenew = true; } else { context.RejectPrincipal(); await context.HttpContext.Authentication.LogOffAsync(Options); } }
public Task ValidatePrincipal(CookieValidatePrincipalContext context) { ISiteSettings site = siteResolver.Resolve(); if (site == null) return Task.FromResult(0); Claim siteGuidClaim = new Claim("SiteGuid", site.SiteGuid.ToString()); if (!context.Principal.HasClaim(siteGuidClaim.Type, siteGuidClaim.Value)) { log.LogInformation("rejecting principal because it does not have siteguid"); context.RejectPrincipal(); } return Task.FromResult(0); }
public static async Task ValidateAsync(CookieValidatePrincipalContext context) { //// Pull database from registered DI services. //var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserIdentityService>(); //var userPrincipal = context.Principal; //// Look for the last changed claim. //string lastChanged; //lastChanged = (from c in userPrincipal.Claims // where c.Type == "LastUpdated" // select c.Value).FirstOrDefault(); //if (string.IsNullOrEmpty(lastChanged) || // !userRepository.ValidateLastChanged(userPrincipal, lastChanged)) //{ // context.RejectPrincipal(); // await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); //} }
public async Task OnValidateIdentityDoesNotRejectsWhenNotExpired() { var user = new TestUser("test"); var httpContext = new Mock<HttpContext>(); var userManager = MockHelpers.MockUserManager<TestUser>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.FromDays(1) }; var options = new Mock<IOptions<IdentityOptions>>(); options.Setup(a => a.Options).Returns(identityOptions); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object, null); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).Throws(new Exception("Shouldn't be called")); signInManager.Setup(s => s.SignInAsync(user, false, null)).Throws(new Exception("Shouldn't be called")); var services = new ServiceCollection(); services.AddInstance(options.Object); services.AddInstance(signInManager.Object); services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }, IdentityOptions.ApplicationCookieAuthenticationScheme); var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Principal); await SecurityStampValidator.ValidatePrincipalAsync(context); Assert.NotNull(context.Principal); }
/// <summary> /// Implements the interface method by invoking the related delegate method /// </summary> /// <param name="context"></param> /// <returns></returns> public virtual Task ValidatePrincipal(CookieValidatePrincipalContext context) { return(OnValidatePrincipal.Invoke(context)); }
/// <summary> /// Implements the interface method by invoking the related delegate method /// </summary> /// <param name="context"></param> /// <returns></returns> public virtual Task ValidatePrincipal(CookieValidatePrincipalContext context) { return OnValidatePrincipal.Invoke(context); }
/// <summary> /// Implements the interface method by invoking the related delegate method. /// </summary> /// <param name="context"></param> /// <returns></returns> public virtual Task ValidatePrincipal(CookieValidatePrincipalContext context) => OnValidatePrincipal(context);
/// <summary> /// Implements the interface method by invoking the related delegate method. /// </summary> /// <param name="context"></param> /// <returns></returns> public virtual Task ValidatePrincipal(CookieValidatePrincipalContext context) => OnValidatePrincipal(context);
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationTicket ticket = null; try { string cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName); if (string.IsNullOrWhiteSpace(cookie)) { return(null); } ticket = Options.TicketDataFormat.Unprotect(cookie); if (ticket == null) { _logger.LogWarning(@"Unprotect ticket failed"); return(null); } if (Options.SessionStore != null) { Claim claim = ticket.Principal.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim)); if (claim == null) { _logger.LogWarning(@"SessionId missing"); return(null); } _sessionKey = claim.Value; ticket = await Options.SessionStore.RetrieveAsync(_sessionKey); if (ticket == null) { _logger.LogWarning(@"Identity missing in session store"); return(null); } } DateTimeOffset currentUtc = Options.SystemClock.UtcNow; DateTimeOffset?issuedUtc = ticket.Properties.IssuedUtc; DateTimeOffset?expiresUtc = ticket.Properties.ExpiresUtc; if (expiresUtc != null && expiresUtc.Value < currentUtc) { if (Options.SessionStore != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } return(null); } bool allowRefresh = ticket.Properties.AllowRefresh ?? true; if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration && allowRefresh) { TimeSpan timeElapsed = currentUtc.Subtract(issuedUtc.Value); TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc); if (timeRemaining < timeElapsed) { _shouldRenew = true; _renewIssuedUtc = currentUtc; TimeSpan timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value); _renewExpiresUtc = currentUtc.Add(timeSpan); } } var context = new CookieValidatePrincipalContext(Context, ticket, Options); await Options.Notifications.ValidatePrincipal(context); return(new AuthenticationTicket(context.Principal, context.Properties, Options.AuthenticationScheme)); } catch (Exception exception) { CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options, CookieExceptionContext.ExceptionLocation.Authenticate, exception, ticket); Options.Notifications.Exception(exceptionContext); if (exceptionContext.Rethrow) { throw; } return(exceptionContext.Ticket); } }
public async Task OnValidateIdentityRejectsWhenNoIssuedUtc() { var user = new TestUser("test"); var httpContext = new Mock<HttpContext>(); var userManager = MockHelpers.MockUserManager<TestUser>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var options = new Mock<IOptions<IdentityOptions>>(); options.Setup(a => a.Value).Returns(identityOptions); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object, null); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(null).Verifiable(); var services = new ServiceCollection(); services.AddSingleton(options.Object); services.AddSingleton(signInManager.Object); services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<TestUser>()); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), new AuthenticationProperties(), identityOptions.Cookies.ApplicationCookieAuthenticationScheme); var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Principal); await SecurityStampValidator.ValidatePrincipalAsync(context); Assert.Null(context.Principal); signInManager.VerifyAll(); }