public static async Task ValidateAsync(CookieValidatePrincipalContext context) { Console.WriteLine($"VALIDATING {context.Request.Path}"); //Get user per request var user = UserDatabase.GetUser(); //User has been deleted in the back end so invalidate the cookie if (user == null) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync("MyCookieMW"); return; } var claims = new List <Claim>(new[] { new Claim(ClaimTypes.Name, user.Name), new Claim("Age", user.Age.ToString()), }); //Backend user has changed details and differs from cookie so update cookie if (!context.Principal.Claims.Select(x => x.Value).SequenceEqual(claims.Select(y => y.Value))) { Console.WriteLine("UPDATE COOKIE"); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "MyCookieMW")); context.ReplacePrincipal(claimsPrincipal); context.ShouldRenew = true; } }
public void Configure(IApplicationBuilder app) { app.UseCookieAuthentication(GetCookieOptions()); app.MapWhen(x => x.Request.Path == "/", y => y.Run(async(context) => { if (!context.User.Identity.IsAuthenticated) { context.Response.StatusCode = 401; //This will rediret to login route return; } await context.Response.WriteAsync($"Hello World, you are current logged in as user {context.User.FindFirst(ClaimTypes.Name).Value} aged {context.User.FindFirst("Age").Value}"); })); app.MapWhen(x => x.Request.Path == "/login", y => y.Run(async(context) => { //verify user when logging in and get it back var user = UserDatabase.GetUser(); var claims = new List <Claim>(new[] { new Claim(ClaimTypes.Name, user.Name), new Claim("Age", user.Age.ToString()), }); var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "MyCookieMW")); await context.Authentication.SignInAsync("MyCookieMW", claimsPrincipal);//Sign user in context.Response.Redirect("/"); })); app.MapWhen(x => x.Request.Path == "/changeuser", y => y.Run(context => { UserDatabase.ChangeUser("Elliot", 29); //Update user details context.Response.Redirect("/"); //Go to root and hope we see our updated info return(Task.CompletedTask); })); }