Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Create token controller, scheme for grand web

dkuciaaea20c134360
diff --git a/src/API/Grand.Api/Commands/Handlers/Common/GenerateGrandWebTokenCommandHandler.cs b/src/API/Grand.Api/Commands/Handlers/Common/GenerateGrandWebTokenCommandHandler.cs
new file mode 100644
index 000000000..fde3dccc8
--- /dev/null
+++ b/src/API/Grand.Api/Commands/Handlers/Common/GenerateGrandWebTokenCommandHandler.cs
@@ -0,0 +1,41 @@
+using Grand.Api.Commands.Models.Common;
+using Grand.Api.Infrastructure.Extensions;
+using Grand.Api.Jwt;
+using Grand.Infrastructure.Configuration;
+using MediatR;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace Grand.Api.Commands.Handlers.Common
+{
+ public class GenerateGrandWebTokenCommandHandler : IRequestHandler<GenerateGrandWebTokenCommand, string>
+ {
+ private readonly GrandWebApiConfig _grandWebApiConfig;
+
+ public GenerateGrandWebTokenCommandHandler(GrandWebApiConfig grandWebApiConfig)
+ {
+ _grandWebApiConfig = grandWebApiConfig;
+ }
+
+ public async Task<string> Handle(GenerateGrandWebTokenCommand request, CancellationToken cancellationToken)
+ {
+ var token = new JwtTokenBuilder();
+ token.AddSecurityKey(JwtSecurityKey.Create(_grandWebApiConfig.SecretKey));
+
+ if (_grandWebApiConfig.ValidateIssuer)
+ token.AddIssuer(_grandWebApiConfig.ValidIssuer);
+ if (_grandWebApiConfig.ValidateAudience)
+ token.AddAudience(_grandWebApiConfig.ValidAudience);
+
+ token.AddClaims(request.Claims);
+ token.AddExpiry(_grandWebApiConfig.ExpiryInMinutes);
+ token.Build();
+
+ return await Task.FromResult(token.Build().Value);
+ }
+ }
+}
diff --git a/src/API/Grand.Api/Commands/Models/Common/GenerateGrandWebTokenCommand.cs b/src/API/Grand.Api/Commands/Models/Common/GenerateGrandWebTokenCommand.cs
new file mode 100644
index 000000000..90989e07a
--- /dev/null
+++ b/src/API/Grand.Api/Commands/Models/Common/GenerateGrandWebTokenCommand.cs
@@ -0,0 +1,14 @@
+using MediatR;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Grand.Api.Commands.Models.Common
+{
+ public class GenerateGrandWebTokenCommand : IRequest<string>
+ {
+ public Dictionary<string, string> Claims { get; set; }
+ }
+}
diff --git a/src/API/Grand.Api/Grand.Api.csproj b/src/API/Grand.Api/Grand.Api.csproj
index e154ea6b6..9684f93e2 100644
--- a/src/API/Grand.Api/Grand.Api.csproj
+++ b/src/API/Grand.Api/Grand.Api.csproj
@@ -18,6 +18,7 @@
<ProjectReference Include="..\..\Business\Grand.Business.System\Grand.Business.System.csproj" />
<ProjectReference Include="..\..\Core\Grand.Infrastructure\Grand.Infrastructure.csproj" />
<ProjectReference Include="..\..\Core\Grand.SharedKernel\Grand.SharedKernel.csproj" />
+ <ProjectReference Include="..\..\Web\Grand.Web.Common\Grand.Web.Common.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OData" Version="7.5.8" />
diff --git a/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs b/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs
index e8c218279..c89d59c13 100644
--- a/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs
+++ b/src/API/Grand.Api/Infrastructure/ApiAuthenticationRegistrar.cs
@@ -47,6 +47,7 @@ namespace Grand.Api.Infrastructure
},
OnTokenValidated = async context =>
{
+
try
{
if (config.Enabled)
@@ -66,6 +67,59 @@ namespace Grand.Api.Infrastructure
};
});
+
+ builder.AddJwtBearer(GrandWebApiConfig.Scheme, options =>
+ {
+ var config = new GrandWebApiConfig();
+ configuration.GetSection("GrandWebApi").Bind(config);
+ options.TokenValidationParameters = new TokenValidationParameters {
+ ValidateIssuer = config.ValidateIssuer,
+ ValidateAudience = config.ValidateAudience,
+ ValidateLifetime = true,
+ ValidateIssuerSigningKey = true,
+ ValidIssuer = config.ValidIssuer,
+ ValidAudience = config.ValidAudience,
+ IssuerSigningKey = JwtSecurityKey.Create(config.SecretKey)
+ };
+
+ options.Events = new JwtBearerEvents {
+ OnAuthenticationFailed = async context =>
+ {
+ context.NoResult();
+ context.Response.StatusCode = 401;
+ context.Response.ContentType = "text/plain";
+ await context.Response.WriteAsync(context.Exception.Message);
+ },
+ OnChallenge = context =>
+ {
+ context.HandleResponse();
+ return Task.CompletedTask;
+ },
+ OnTokenValidated = async context =>
+ {
+ try
+ {
+ if (config.Enabled)
+ {
+ var jwtAuthentication = context.HttpContext.RequestServices.GetRequiredService<IJwtBearerCustomerAuthenticationService>();
+ var (isValid, customer) = await jwtAuthentication.Valid(context);
+ if (!isValid)
+ throw new Exception(await jwtAuthentication.ErrorMessage());
+ context.Success();
+ context.Result.Properties.Parameters.Add("Customer", customer);
+ }
+ else
+ throw new Exception("API is disable");
+ }
+ catch (Exception ex)
+ {
+ throw new Exception(ex.Message);
+ }
+ },
+ };
+ });
+
+
}
public int Priority => 900;
diff --git a/src/API/Grand.Api/Web/TokenController.cs b/src/API/Grand.Api/Web/TokenController.cs
new file mode 100644
index 000000000..2f76f4a45
--- /dev/null
+++ b/src/API/Grand.Api/Web/TokenController.cs
@@ -0,0 +1,65 @@
+using Grand.Api.Commands.Models.Common;
+using Grand.Business.Customers.Interfaces;
+using Grand.Domain.Customers;
+using Grand.Infrastructure;
+using Grand.Web.Common.Controllers;
+using MediatR;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Components;
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Grand.Api.Web
+{
+
+ public class TokenController : BaseController
+ {
+ private readonly ICustomerService _customerService;
+ private readonly IWorkContext _workContext;
+ private readonly ICustomerManagerService _customerManagerService;
+ private readonly IMediator _mediator;
+
+ public TokenController(ICustomerService customerService,IWorkContext workContext,ICustomerManagerService customerManagerService,IMediator mediator)
+ {
+ _customerService = customerService;
+ _workContext = workContext;
+ _customerManagerService = customerManagerService;
+ _mediator = mediator;
+ }
+
+ [AllowAnonymous]
+ [IgnoreAntiforgeryToken]
+ [HttpPost]
+ public async Task<IActionResult> Guest()
+ {
+ var customer=await _customerService.InsertGuestCustomer(_workContext.CurrentStore);
+ var claims = new Dictionary<string, string> {
+ { "Id", customer.Id}
+ };
+
+ var token = await _mediator.Send(new GenerateGrandWebTokenCommand() { Claims = claims });
+ return Ok(token);
+ }
+
+ [AllowAnonymous]
+ [IgnoreAntiforgeryToken]
+ [HttpPost]
+ public async Task<IActionResult> Create([FromBody] Models.Common.LoginModel model)
+ {
+ var result = await _customerManagerService.LoginCustomer(model.Email, model.Password);
+ if (!result.Equals(CustomerLoginResults.Successful))
+ {
+ return BadRequest(result.ToString());
+ }
+ var claims = new Dictionary<string, string> {
+ { "Email", model.Email}
+ };
+ var token = await _mediator.Send(new GenerateGrandWebTokenCommand() { Claims = claims });
+ return Ok(token);
+ }
+ }
+}
diff --git a/src/Business/Grand.Business.Authentication/Interfaces/IJwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Interfaces/IJwtBearerCustomerAuthenticationService.cs
new file mode 100644
index 000000000..9ac701059
--- /dev/null
+++ b/src/Business/Grand.Business.Authentication/Interfaces/IJwtBearerCustomerAuthenticationService.cs
@@ -0,0 +1,16 @@
+using Grand.Domain.Customers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Grand.Business.Authentication.Interfaces
+{
+ public interface IJwtBearerCustomerAuthenticationService
+ {
+ Task<(bool, Customer)> Valid(TokenValidatedContext context);
+ Task<string> ErrorMessage();
+ }
+}
diff --git a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
index 5029889cb..8b708e414 100644
--- a/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/ApiAuthenticationService.cs
@@ -2,6 +2,7 @@
using Grand.Business.Common.Interfaces.Directory;
using Grand.Business.Customers.Interfaces;
using Grand.Domain.Customers;
+using Grand.Infrastructure.Configuration;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
@@ -45,6 +46,17 @@ namespace Grand.Business.Authentication.Services
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith(JwtBearerDefaults.AuthenticationScheme))
return null;
+ if (!_httpContextAccessor.HttpContext.Request.Path.Value.StartsWith("/odata"))
+ {
+ customer = await ApiCustomer();
+ if (customer != null)
+ {
+ _cachedCustomer = customer;
+ return _cachedCustomer;
+ }
+ return null;
+ }
+
var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return null;
@@ -66,5 +78,19 @@ namespace Grand.Business.Authentication.Services
}
+ private async Task<Customer> ApiCustomer()
+ {
+ Customer customer = null;
+ var authResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandWebApiConfig.Scheme);
+ if (!authResult.Succeeded)
+ return null;
+
+ if(authResult.Properties.Parameters.TryGetValue("Customer", out var c))
+ {
+ customer = c as Customer;
+ }
+
+ return customer;
+ }
}
}
diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs
new file mode 100644
index 000000000..9aeeafb71
--- /dev/null
+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs
@@ -0,0 +1,58 @@
+using Grand.Business.Authentication.Interfaces;
+using Grand.Business.Customers.Interfaces;
+using Grand.Domain.Customers;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Grand.Business.Authentication.Services
+{
+ public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenticationService
+ {
+ private readonly ICustomerService _customerService;
+ private string _errorMessage;
+ public JwtBearerCustomerAuthenticationService(ICustomerService customerService)
+ {
+ _customerService = customerService;
+ }
+
+ public async Task<(bool, Customer)> Valid(TokenValidatedContext context)
+ {
+ var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;
+ Customer customer = null;
+ if(email is null)
+ {
+ //guest
+ var id= context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Id")?.Value;
+ customer = await _customerService.GetCustomerById(id);
+ }
+ else
+ {
+ customer = await _customerService.GetCustomerByEmail(email);
+ }
+ if (customer is null)
+ {
+ _errorMessage = "Not found customer";
+ return (false, null);
+ }
+
+ if (customer == null || !customer.Active || customer.Deleted)
+ {
+ _errorMessage = "Customer not exists/or not active in the customer table";
+ return (false, null);
+ }
+
+ return (true, customer);
+ }
+
+
+ public Task<string> ErrorMessage()
+ {
+ return Task.FromResult(_errorMessage);
+ }
+
+ }
+}
diff --git a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
index edb0c9a33..5948de8a5 100644
--- a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs
@@ -18,6 +18,7 @@ namespace Grand.Business.Authentication.Startup
services.AddScoped<IJwtBearerAuthenticationService, JwtBearerAuthenticationService>();
services.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();
services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();
+ services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();
}
public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
{
diff --git a/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs b/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs
new file mode 100644
index 000000000..7e0bb2c0e
--- /dev/null
+++ b/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs
@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Grand.Infrastructure.Configuration
+{
+ public class GrandWebApiConfig
+ {
+ public static string Scheme => "GrandWebBearerScheme";
+ public bool Enabled { get; set; }
+ public string SecretKey { get; set; }
+ public bool ValidateIssuer { get; set; }
+ public string ValidIssuer { get; set; }
+ public bool ValidateAudience { get; set; }
+ public string ValidAudience { get; set; }
+ public bool ValidateLifetime { get; set; }
+ public bool ValidateIssuerSigningKey { get; set; }
+ public int ExpiryInMinutes { get; set; }
+ }
+}
diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs
index 57d966861..fa20a6331 100644
--- a/src/Core/Grand.Infrastructure/StartupBase.cs
+++ b/src/Core/Grand.Infrastructure/StartupBase.cs
@@ -213,6 +213,8 @@ namespace Grand.Infrastructure
services.StartupConfig<HostingConfig>(configuration.GetSection("Hosting"));
//add api configuration parameters
services.StartupConfig<ApiConfig>(configuration.GetSection("Api"));
+ //add grand.web api token config
+ services.StartupConfig<GrandWebApiConfig>(configuration.GetSection("GrandWebApi"));
//set base application path
var provider = services.BuildServiceProvider();
diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.json
index ebc724143..7cd90f3ff 100644
--- a/src/Web/Grand.Web/App_Data/appsettings.json
+++ b/src/Web/Grand.Web/App_Data/appsettings.json
@@ -156,9 +156,21 @@
"UseSerilogRequestLogging": false
},
+ "GrandWebApi": {
+ "Enabled": true,
+ "SecretKey": "your private secret key",
+ "ValidateIssuer": false,
+ "ValidIssuer": "",
+ "ValidateAudience": false,
+ "ValidAudience": "",
+ "ValidateLifetime": true,
+ "ValidateIssuerSigningKey": true,
+ "ExpiryInMinutes": 1440
+ },
+
"Api": {
- "Enabled": false,
- "UseSwagger": false,
+ "Enabled": true,
+ "UseSwagger": true,
"SecretKey": "your private secret key",
"ValidateIssuer": false,
"ValidIssuer": "",