From 2f295cfac21dc2320c79331f70f535dadc1898e3 Mon Sep 17 00:00:00 2001 From: Galip Tolga Erdem Date: Thu, 27 Jan 2022 12:18:48 +0300 Subject: [PATCH 1/3] Added anonymous user middleware --- .../AnonymousUser/AnonymousUserMiddleware.cs | 46 +++++++++++++++++++ .../EShopOnAbpPublicWebModule.cs | 2 + 2 files changed, 48 insertions(+) create mode 100644 apps/public-web/src/EShopOnAbp.PublicWeb/AnonymousUser/AnonymousUserMiddleware.cs diff --git a/apps/public-web/src/EShopOnAbp.PublicWeb/AnonymousUser/AnonymousUserMiddleware.cs b/apps/public-web/src/EShopOnAbp.PublicWeb/AnonymousUser/AnonymousUserMiddleware.cs new file mode 100644 index 00000000..8ab53717 --- /dev/null +++ b/apps/public-web/src/EShopOnAbp.PublicWeb/AnonymousUser/AnonymousUserMiddleware.cs @@ -0,0 +1,46 @@ +using System; +using System.Threading.Tasks; +using EShopOnAbp.Shared.Hosting.AspNetCore; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +namespace EShopOnAbp.PublicWeb.AnonymousUser; + +public class AnonymousUserMiddleware +{ + private readonly RequestDelegate _next; + + public AnonymousUserMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + if (context.Request.Method == "GET") + { + context.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, out string anonymousUserId); + // Generate guid for anonymous user id and set to cookie for 14 days + if (string.IsNullOrEmpty(anonymousUserId)) + { + anonymousUserId = Guid.NewGuid().ToString(); + context.Response.Cookies.Append(EShopConstants.AnonymousUserClaimName, anonymousUserId, + new CookieOptions + { + SameSite = SameSiteMode.Lax, + Expires = DateTimeOffset.UtcNow.AddDays(14) + }); + } + } + await _next(context); + } +} + +public static class AnonymousUserApplicationBuilderExtensions +{ + public static IApplicationBuilder UseAnonymousUser(this IApplicationBuilder app) + { + app.UseMiddleware(); + return app; + } +} \ No newline at end of file diff --git a/apps/public-web/src/EShopOnAbp.PublicWeb/EShopOnAbpPublicWebModule.cs b/apps/public-web/src/EShopOnAbp.PublicWeb/EShopOnAbpPublicWebModule.cs index a6b63092..65a2ffca 100644 --- a/apps/public-web/src/EShopOnAbp.PublicWeb/EShopOnAbpPublicWebModule.cs +++ b/apps/public-web/src/EShopOnAbp.PublicWeb/EShopOnAbpPublicWebModule.cs @@ -38,6 +38,7 @@ using Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic.Bundling; using EShopOnAbp.PublicWeb.Components.Toolbar.Cart; using EShopOnAbp.PublicWeb.PaymentMethods; using EShopOnAbp.PaymentService.PaymentMethods; +using EShopOnAbp.PublicWeb.AnonymousUser; using Microsoft.Extensions.Configuration; namespace EShopOnAbp.PublicWeb; @@ -202,6 +203,7 @@ public class EShopOnAbpPublicWebModule : AbpModule app.UseAuthentication(); app.UseAbpSerilogEnrichers(); app.UseAuthorization(); + app.UseAnonymousUser(); app.UseConfiguredEndpoints(endpoints => { endpoints.MapReverseProxy(); From bb56419b3301c08311d0f42ccdd15864967b07eb Mon Sep 17 00:00:00 2001 From: Galip Tolga Erdem Date: Thu, 27 Jan 2022 12:19:01 +0300 Subject: [PATCH 2/3] removed anonymous user component --- .../AnonymousUserViewComponent.cs | 48 ------------------- .../Components/AnonymousUser/Default.cshtml | 3 -- .../Pages/_ViewStart.cshtml | 6 +-- 3 files changed, 2 insertions(+), 55 deletions(-) delete mode 100644 apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/AnonymousUserViewComponent.cs delete mode 100644 apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/Default.cshtml diff --git a/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/AnonymousUserViewComponent.cs b/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/AnonymousUserViewComponent.cs deleted file mode 100644 index 3d27a364..00000000 --- a/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/AnonymousUserViewComponent.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System.Threading.Tasks; -using EShopOnAbp.Shared.Hosting.AspNetCore; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Logging; -using Volo.Abp.AspNetCore.Mvc; -using Volo.Abp.AspNetCore.Mvc.UI.Widgets; -using Volo.Abp.Guids; - -namespace EShopOnAbp.PublicWeb.Components.AnonymousUser; - -/* TODO: Convert this to an ASP.NET Core middleware */ -[Widget( - AutoInitialize = true -)] -public class AnonymousUserViewComponent : AbpViewComponent -{ - private readonly ILogger _logger; - private readonly IGuidGenerator _guidGenerator; - - public AnonymousUserViewComponent(ILogger logger, IGuidGenerator guidGenerator) - { - _logger = logger; - _guidGenerator = guidGenerator; - } - - public async Task InvokeAsync() - { - // Get anonymous user id from cookie - HttpContext.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, - out string anonymousUserId); - _logger.LogInformation($"========= Anonymous User Id from Cookie:{anonymousUserId} ========= "); - - // Generate new id for anonymous user - if (string.IsNullOrEmpty(anonymousUserId)) - { - anonymousUserId = _guidGenerator.Create().ToString(); - HttpContext.Response.Cookies.Append(EShopConstants.AnonymousUserClaimName, anonymousUserId, - new CookieOptions - { - SameSite = SameSiteMode.Lax - }); - _logger.LogInformation( - $"========= Generated new User Id:{anonymousUserId} ========= APPENDED TO COOKIE ====== "); - } - return await Task.FromResult(View("~/Components/AnonymousUser/Default.cshtml")); - } -} \ No newline at end of file diff --git a/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/Default.cshtml b/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/Default.cshtml deleted file mode 100644 index 42eb8c53..00000000 --- a/apps/public-web/src/EShopOnAbp.PublicWeb/Components/AnonymousUser/Default.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -
- -
\ No newline at end of file diff --git a/apps/public-web/src/EShopOnAbp.PublicWeb/Pages/_ViewStart.cshtml b/apps/public-web/src/EShopOnAbp.PublicWeb/Pages/_ViewStart.cshtml index 2f921a29..0372fa28 100644 --- a/apps/public-web/src/EShopOnAbp.PublicWeb/Pages/_ViewStart.cshtml +++ b/apps/public-web/src/EShopOnAbp.PublicWeb/Pages/_ViewStart.cshtml @@ -1,7 +1,5 @@ -@using EShopOnAbp.PublicWeb.Components.AnonymousUser -@using Volo.Abp.AspNetCore.Mvc.UI.Theming +@using Volo.Abp.AspNetCore.Mvc.UI.Theming @inject IThemeManager ThemeManager @{ Layout = ThemeManager.CurrentTheme.GetPublicLayout(); -} -@await Component.InvokeAsync(typeof(AnonymousUserViewComponent)) \ No newline at end of file +} \ No newline at end of file From 634c5fd2dce26d6fcf2a79a19791d339b03a64dc Mon Sep 17 00:00:00 2001 From: Galip Tolga Erdem Date: Thu, 27 Jan 2022 12:19:37 +0300 Subject: [PATCH 3/3] removed user claim factory for anonymous user claim --- .../AnonymousUserItem.cs | 6 -- .../EShopUserClaimsPrincipalFactory.cs | 82 ------------------- .../EShopConstants.cs | 1 - 3 files changed, 89 deletions(-) delete mode 100644 apps/auth-server/src/EShopOnAbp.AuthServer/AnonymousUserItem.cs delete mode 100644 apps/auth-server/src/EShopOnAbp.AuthServer/EShopUserClaimsPrincipalFactory.cs diff --git a/apps/auth-server/src/EShopOnAbp.AuthServer/AnonymousUserItem.cs b/apps/auth-server/src/EShopOnAbp.AuthServer/AnonymousUserItem.cs deleted file mode 100644 index 3679543d..00000000 --- a/apps/auth-server/src/EShopOnAbp.AuthServer/AnonymousUserItem.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace EShopOnAbp.AuthServer; - -public class AnonymousUserItem -{ - public string AnonymousUserId { get; set; } -} \ No newline at end of file diff --git a/apps/auth-server/src/EShopOnAbp.AuthServer/EShopUserClaimsPrincipalFactory.cs b/apps/auth-server/src/EShopOnAbp.AuthServer/EShopUserClaimsPrincipalFactory.cs deleted file mode 100644 index d4368878..00000000 --- a/apps/auth-server/src/EShopOnAbp.AuthServer/EShopUserClaimsPrincipalFactory.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using EShopOnAbp.Shared.Hosting.AspNetCore; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Caching.Distributed; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Volo.Abp.Caching; -using Volo.Abp.DependencyInjection; -using Volo.Abp.Identity; -using Volo.Abp.Security.Claims; -using IdentityRole = Volo.Abp.Identity.IdentityRole; -using IdentityUser = Volo.Abp.Identity.IdentityUser; - -namespace EShopOnAbp.AuthServer; - -[Dependency(ReplaceServices = true)] -[ExposeServices(typeof(AbpUserClaimsPrincipalFactory))] -public class EShopUserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory -{ - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly ILogger _logger; - private readonly IDistributedCache _cache; - protected HttpContext HttpContext => _httpContextAccessor.HttpContext; - - public EShopUserClaimsPrincipalFactory( - UserManager userManager, - RoleManager roleManager, - IOptions options, - ICurrentPrincipalAccessor currentPrincipalAccessor, - IAbpClaimsPrincipalFactory abpClaimsPrincipalFactory, - IHttpContextAccessor httpContextAccessor, - ILogger logger, - IDistributedCache cache) : base(userManager, - roleManager, - options, - currentPrincipalAccessor, - abpClaimsPrincipalFactory) - { - _httpContextAccessor = httpContextAccessor; - _logger = logger; - _cache = cache; - } - - public override async Task CreateAsync(IdentityUser user) - { - var principal = await base.CreateAsync(user); - - if (HttpContext.Request.Cookies.ContainsKey(EShopConstants.AnonymousUserClaimName)) - { - HttpContext.Request.Cookies.TryGetValue(EShopConstants.AnonymousUserClaimName, out var anonymousUserId); - await _cache.SetAsync(user.Id, new AnonymousUserItem {AnonymousUserId = anonymousUserId}, - options: new DistributedCacheEntryOptions() - { - AbsoluteExpiration = DateTimeOffset.UtcNow.AddSeconds(60) - }); - - _logger.LogInformation($"Cached anonymousUserId:{anonymousUserId}."); - } - - var cachedItem = await _cache.GetAsync(user.Id); - if (cachedItem == null) - { - _logger.LogWarning($"Could not retrieve anonymousUserId from cache."); - return principal; - } - - _logger.LogInformation($"Retrieved anonymousUserId:{cachedItem.AnonymousUserId} from cache."); - - principal.Identities.First().AddClaim( - new Claim( - EShopConstants.AnonymousUserClaimName, - cachedItem.AnonymousUserId - ) - ); - - return principal; - } -} \ No newline at end of file diff --git a/shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopConstants.cs b/shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopConstants.cs index 2e023cea..6f7d0db7 100644 --- a/shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopConstants.cs +++ b/shared/EShopOnAbp.Shared.Hosting.AspNetCore/EShopConstants.cs @@ -2,6 +2,5 @@ public static class EShopConstants { - // public const string AnonymousUserCookieName = "eshop_anonymousId"; public const string AnonymousUserClaimName = "anonymous_id"; } \ No newline at end of file