public async Task ValidateAsync(CookieValidatePrincipalContext context) { var authChanges = new AuthChanges(); var extraContext = context.HttpContext.RequestServices.GetRequiredService <ExtraAuthorizeDbContext>(); var newClaims = new List <Claim>(); var originalClaims = context.Principal.Claims.ToList(); if (originalClaims.All(x => x.Type != PermissionConstants.PackedPermissionClaimType) || authChanges.IsOutOfDateOrMissing(AuthChangesConsts.FeatureCacheKey, originalClaims.SingleOrDefault(x => x.Type == PermissionConstants.LastPermissionsUpdatedClaimType)?.Value, extraContext)) { var rtoPCalcer = new CalcAllowedPermissions(extraContext); var dataKeyCalc = new CalcDataKey(extraContext); //Handle the feature permissions var userId = originalClaims.GetUserIdFromClaims(); newClaims.AddRange(await BuildFeatureClaimsAsync(userId, rtoPCalcer)); newClaims.AddRange(BuildDataClaims(userId, dataKeyCalc)); //Something has changed so we replace the current ClaimsPrincipal with a new one newClaims.AddRange(RemoveUpdatedClaimsFromOriginalClaims(originalClaims, newClaims)); //Copy over unchanged claims //Build a new ClaimsPrincipal and use it to replace the current ClaimsPrincipal var identity = new ClaimsIdentity(newClaims, "Cookie"); var newPrincipal = new ClaimsPrincipal(identity); context.ReplacePrincipal(newPrincipal); //THIS IS IMPORTANT: This updates the cookie, otherwise this calc will be done every HTTP request context.ShouldRenew = true; } }
public void TestIsOutOfDateOrMissing(string key, string ticksToTry, bool expectedResult) { //SETUP var fakeTimeStore = new FakeTimeStore("test", 200); var authChange = new AuthChanges(); //ATTEMPT var isOutOfDate = authChange.IsOutOfDateOrMissing(key, ticksToTry, fakeTimeStore); //VERIFY isOutOfDate.ShouldEqual(expectedResult); }
public void TestIsOutOfDateOrMissingNoOriginalValue() { //SETUP var fakeTimeStore = new FakeTimeStore("test", null); var authChange = new AuthChanges(); //ATTEMPT var ex = Assert.Throws <ApplicationException>(() => authChange.IsOutOfDateOrMissing("test", "100", fakeTimeStore)); //VERIFY ex.Message.ShouldStartWith("You must seed the database with a cache value for the key "); }
public void TestIsOutOfDateOrMissingNoOriginalValue() { //SETUP var fakeTimeStore = new FakeTimeStore("test", 200); var authChange = new AuthChanges(); //ATTEMPT var isOutOfDate = authChange.IsOutOfDateOrMissing("test", "100", fakeTimeStore); //VERIFY isOutOfDate.ShouldEqual(true); fakeTimeStore.Key.ShouldNotBeNull(); }