add cached on logout with revoke cookie identity key (#605)

* add cached on logout with revoke cookie identity key

* properly signout as recommended : https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0#react-to-back-end-changes

* add remark regarding multi-host scenario

* Update src/Web/Configuration/RevokeAuthenticationEvents.cs

Co-authored-by: Steve Smith <steve@kentsmiths.com>
This commit is contained in:
Cédric Michel
2021-11-01 14:49:53 +01:00
committed by GitHub
parent 68beb21f07
commit 5d34222f28
3 changed files with 64 additions and 7 deletions

View File

@@ -7,6 +7,9 @@ namespace Microsoft.eShopWeb.Web.Configuration
{
public static class ConfigureCookieSettings
{
public const int ValidityMinutesPeriod = 60;
public const string IdentifierCookieName = "EshopIdentifier";
public static IServiceCollection AddCookieSettings(this IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
@@ -18,16 +21,20 @@ namespace Microsoft.eShopWeb.Web.Configuration
});
services.ConfigureApplicationCookie(options =>
{
options.EventsType = typeof(RevokeAuthenticationEvents);
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(1);
options.ExpireTimeSpan = TimeSpan.FromMinutes(ValidityMinutesPeriod);
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.Cookie = new CookieBuilder
{
Name = IdentifierCookieName,
IsEssential = true // required for auth to work without explicit user consent; adjust to suit your privacy policy
};
});
services.AddScoped<RevokeAuthenticationEvents>();
return services;
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.Web.Configuration
{
//TODO : replace IMemoryCache with a distributed cache if you are in multi-host scenario
public class RevokeAuthenticationEvents : CookieAuthenticationEvents
{
private readonly IMemoryCache _cache;
private readonly ILogger _logger;
public RevokeAuthenticationEvents(IMemoryCache cache, ILogger<RevokeAuthenticationEvents> logger)
{
_cache = cache;
_logger = logger;
}
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
var userId = context.Principal.Claims.First(c => c.Type == ClaimTypes.Name);
var identityKey = context.Request.Cookies[ConfigureCookieSettings.IdentifierCookieName];
if (_cache.TryGetValue($"{userId.Value}:{identityKey}", out var revokeKeys))
{
_logger.LogDebug($"Access has been revoked for: {userId.Value}.");
context.RejectPrincipal();
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
}