Skip to content

Commit bc64b02

Browse files
Refactor authentication services and middleware
1 parent 0c65741 commit bc64b02

File tree

5 files changed

+35
-33
lines changed

5 files changed

+35
-33
lines changed

src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using Grand.Infrastructure.Configuration;
66
using Microsoft.AspNetCore.Authentication;
77
using Microsoft.AspNetCore.Authentication.JwtBearer;
8+
using Microsoft.AspNetCore.Authorization;
89
using Microsoft.AspNetCore.Http;
910
using Microsoft.Net.Http.Headers;
1011

@@ -34,12 +35,12 @@ public virtual async Task<Customer> GetAuthenticatedCustomer()
3435
if (string.IsNullOrEmpty(authHeader))
3536
return null;
3637

37-
if (_httpContextAccessor.HttpContext.Request.Path.Value != null
38-
&& !_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/api"))
38+
if (IsApiFrontAuthenticated())
3939
{
4040
customer = await ApiCustomer();
4141
return customer;
4242
}
43+
4344
var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
4445
if (!authenticateResult.Succeeded)
4546
return null;
@@ -55,6 +56,15 @@ public virtual async Task<Customer> GetAuthenticatedCustomer()
5556

5657
return customer;
5758
}
59+
private bool IsApiFrontAuthenticated()
60+
{
61+
var endpoint = _httpContextAccessor.HttpContext.GetEndpoint();
62+
if (endpoint == null) return false;
63+
64+
var authorizeAttributes = endpoint.Metadata.GetOrderedMetadata<AuthorizeAttribute>();
65+
return authorizeAttributes.Any(attr => attr.AuthenticationSchemes?.Contains(FrontendAPIConfig.AuthenticationScheme) == true);
66+
}
67+
5868

5969
private async Task<Customer> ApiCustomer()
6070
{

src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs

Lines changed: 3 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ public CookieAuthenticationService(
5555
private readonly IGroupService _groupService;
5656
private readonly IHttpContextAccessor _httpContextAccessor;
5757
private readonly SecurityConfig _securityConfig;
58-
private Customer _cachedCustomer;
5958

6059
#endregion
6160

@@ -112,22 +111,15 @@ public virtual async Task SignIn(Customer customer, bool isPersistent)
112111
{
113112
_httpContextAccessor.HttpContext.Response.Cookies.Delete(CustomerCookieName);
114113

115-
await _httpContextAccessor.HttpContext.SignInAsync(
116-
GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
114+
await _httpContextAccessor.HttpContext.SignInAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authenticationProperties);
117115
}
118-
119-
//cache authenticated customer
120-
_cachedCustomer = customer;
121116
}
122117

123118
/// <summary>
124119
/// Sign out customer
125120
/// </summary>
126121
public virtual async Task SignOut()
127122
{
128-
//Firstly reset cached customer
129-
_cachedCustomer = null;
130-
131123
//and then sign out customer from the present scheme of authentication
132124
if (_httpContextAccessor.HttpContext != null)
133125
{
@@ -145,15 +137,7 @@ await _httpContextAccessor.HttpContext.SignOutAsync(GrandCookieAuthenticationDef
145137
/// <returns>Customer</returns>
146138
public virtual async Task<Customer> GetAuthenticatedCustomer()
147139
{
148-
//check if there is a cached customer
149-
if (_cachedCustomer != null)
150-
return _cachedCustomer;
151-
152-
//get the authenticated user identity
153-
if (_httpContextAccessor.HttpContext == null) return _cachedCustomer;
154-
var authenticateResult =
155-
await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults
156-
.AuthenticationScheme);
140+
var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme);
157141
if (!authenticateResult.Succeeded)
158142
return null;
159143

@@ -195,10 +179,7 @@ await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticati
195179
if (customer is not { Active: true } || customer.Deleted || !await _groupService.IsRegistered(customer))
196180
return null;
197181

198-
//Cache the authenticated customer
199-
_cachedCustomer = customer;
200-
201-
return _cachedCustomer;
182+
return customer;
202183
}
203184

204185
/// <summary>

src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public CultureSettingMiddleware(RequestDelegate next)
1515

1616
public async Task InvokeAsync(HttpContext context, IWorkContextAccessor workContextAccessor)
1717
{
18-
if (workContextAccessor.WorkContext.WorkingLanguage != null)
18+
if (workContextAccessor.WorkContext?.WorkingLanguage != null)
1919
{
2020
var culture = new CultureInfo(workContextAccessor.WorkContext.WorkingLanguage.LanguageCulture);
2121

src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Grand.Infrastructure;
22
using Microsoft.AspNetCore.Http;
3+
using Microsoft.AspNetCore.Routing;
34

45
namespace Grand.Web.Common.Middleware;
56

@@ -9,6 +10,8 @@ public class WorkContextMiddleware
910

1011
private readonly RequestDelegate _next;
1112

13+
private readonly List<string> skipRoutePattern = ["/scalar/{documentName}", "/openapi/{documentName}.json"];
14+
1215
#endregion
1316

1417
#region Ctor
@@ -35,6 +38,17 @@ public WorkContextMiddleware(RequestDelegate next)
3538
public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContextSetter, IWorkContextAccessor workContextAccessor)
3639
{
3740
if (context?.Request == null) return;
41+
42+
var endpoint = context.GetEndpoint();
43+
if (endpoint != null)
44+
{
45+
var routePattern = (endpoint as RouteEndpoint)?.RoutePattern.RawText;
46+
if (routePattern != null && skipRoutePattern.Any(pattern => routePattern.StartsWith(pattern, StringComparison.OrdinalIgnoreCase)))
47+
{
48+
await _next(context);
49+
return;
50+
}
51+
}
3852

3953
//set current context
4054
var workContext = await workContextSetter.InitializeWorkContext();

src/Web/Grand.Web.Common/WorkContextSetter.cs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -175,23 +175,21 @@ protected async Task<Customer> CurrentCustomer(Store store)
175175
var customer = await GetBackgroundTaskCustomer();
176176
if (customer != null) return customer;
177177

178-
customer = await GetSearchEngineCustomer();
178+
customer = await GetAllowAnonymousCustomer();
179179
if (customer != null) return customer;
180180

181-
customer = await GetAllowAnonymousCustomer();
181+
customer = await GetCookieAuthenticatedCustomer();
182182
if (customer != null) return customer;
183183

184184
customer = await GetGuestCustomer();
185185
if (customer != null) return customer;
186186

187-
customer = await GetAuthenticatedCustomer();
187+
customer = await GetSearchEngineCustomer();
188188
if (customer != null) return customer;
189189

190190
customer = await GetApiUserCustomer();
191191
if (customer != null) return customer;
192-
193192

194-
195193
//create guest if not exists
196194
customer = await CreateCustomerGuest(store);
197195

@@ -213,7 +211,7 @@ private async Task<Customer> GetAllowAnonymousCustomer()
213211
return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);
214212
}
215213

216-
private async Task<Customer> GetAuthenticatedCustomer()
214+
private async Task<Customer> GetCookieAuthenticatedCustomer()
217215
{
218216
var customer = await _authenticationService.GetAuthenticatedCustomer();
219217
if (customer == null) return null;
@@ -229,8 +227,7 @@ private async Task<Customer> GetAuthenticatedCustomer()
229227

230228
private async Task<Customer> GetApiUserCustomer()
231229
{
232-
var apiAuthenticationService =
233-
_httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();
230+
var apiAuthenticationService = _httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();
234231
return await apiAuthenticationService.GetAuthenticatedCustomer();
235232
}
236233

0 commit comments

Comments
 (0)