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.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Handle refresh token
dkucia13239e715ddd
diff --git a/src/API/Grand.Api/DTOs/TokenDto.cs b/src/API/Grand.Api/DTOs/TokenDto.csnew file mode 100644index 000000000..59ca83c27--- /dev/null+++ b/src/API/Grand.Api/DTOs/TokenDto.cs@@ -0,0 +1,14 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Text;+using System.Threading.Tasks;++namespace Grand.Api.DTOs+{+ public class TokenDto+ {+ public string AccessToken { get; set; }+ public string RefreshToken { get; set; }+ }+}diff --git a/src/API/Grand.Api/Infrastructure/AuthenticationStartup.cs b/src/API/Grand.Api/Infrastructure/AuthenticationStartup.csindex 16f088787..4fbb90c56 100644--- a/src/API/Grand.Api/Infrastructure/AuthenticationStartup.cs+++ b/src/API/Grand.Api/Infrastructure/AuthenticationStartup.cs@@ -1,4 +1,6 @@using Grand.Api.Constants;+using Grand.Business.Authentication.Interfaces;+using Grand.Business.Authentication.Services;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Microsoft.AspNet.OData.Extensions;@@ -24,7 +26,6 @@ namespace Grand.Api.InfrastructureIConfiguration configuration){var apiConfig = services.BuildServiceProvider().GetService<ApiConfig>();-if (apiConfig.Enabled){//corsdiff --git a/src/API/Grand.Api/Web/TokenController.cs b/src/API/Grand.Api/Web/TokenController.csindex d951b2a6d..f1566143f 100644--- a/src/API/Grand.Api/Web/TokenController.cs+++ b/src/API/Grand.Api/Web/TokenController.cs@@ -1,4 +1,7 @@using Grand.Api.Commands.Models.Common;+using Grand.Api.DTOs;+using Grand.Business.Authentication.Interfaces;+using Grand.Business.Common.Interfaces.Directory;using Grand.Business.Customers.Interfaces;using Grand.Domain.Customers;using Grand.Infrastructure;@@ -20,13 +23,18 @@ namespace Grand.Api.Webprivate readonly ICustomerManagerService _customerManagerService;private readonly IMediator _mediator;private readonly IStoreHelper _storeHelper;+ private readonly IRefreshTokenService _refreshTokenService;+ private readonly IUserFieldService _userFieldService;- public TokenController(ICustomerService customerService,ICustomerManagerService customerManagerService,IMediator mediator,IStoreHelper storeHelper)+ public TokenController(ICustomerService customerService, ICustomerManagerService customerManagerService, IMediator mediator, IStoreHelper storeHelper+ , IRefreshTokenService refreshTokenService,IUserFieldService userFieldService){_customerService = customerService;_customerManagerService = customerManagerService;_mediator = mediator;_storeHelper = storeHelper;+ _refreshTokenService = refreshTokenService;+ _userFieldService = userFieldService;}[AllowAnonymous]@@ -34,13 +42,13 @@ namespace Grand.Api.Web[HttpPost]public async Task<IActionResult> Guest(){- var customer=await _customerService.InsertGuestCustomer(_storeHelper.HostStore);+ var customer = await _customerService.InsertGuestCustomer(_storeHelper.HostStore);var claims = new Dictionary<string, string> {{ "Guid", customer.CustomerGuid.ToString()}};- var token = await _mediator.Send(new GenerateGrandWebTokenCommand() { Claims = claims });- return Ok(token);+ var tokenDto = await GetToken(claims, customer);+ return Ok(tokenDto);}[AllowAnonymous]@@ -53,11 +61,56 @@ namespace Grand.Api.Web{return BadRequest(result.ToString());}+ var customer = await _customerService.GetCustomerByEmail(model.Email);var claims = new Dictionary<string, string> {- { "Email", model.Email}+ { "Email", model.Email},+ { "Token",await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken) }};- var token = await _mediator.Send(new GenerateGrandWebTokenCommand() { Claims = claims });+ var tokenDto = await GetToken(claims, customer);+ return Ok(tokenDto);+ }++ [AllowAnonymous]+ [IgnoreAntiforgeryToken]+ [HttpPost]+ public async Task<IActionResult> Refresh([FromBody] TokenDto tokenDto)+ {+ string email = null, guid = null;+ Customer customer = null;+ var claims = new Dictionary<string, string>();+ var principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken);+ email= principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;+ if (!string.IsNullOrEmpty(email))+ {+ customer = await _customerService.GetCustomerByEmail(email);+ claims.Add("Email", email);+ claims.Add("Token", await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken));+ }+ else+ {+ guid = principal.Claims.ToList().FirstOrDefault(x => x.Type == "Guid")?.Value;+ customer = await _customerService.GetCustomerByGuid(Guid.Parse(guid));+ claims.Add("Guid", guid);+ }++ var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer);+ if(customerRefreshToken is null || !customerRefreshToken.Token.Equals(tokenDto.RefreshToken))+ {+ return BadRequest("Invalid refresh token");+ }+ var token= await GetToken(claims, customer); ;return Ok(token);}++ private async Task<TokenDto> GetToken(Dictionary<string,string> claims,Customer customer)+ {+ var token = await _mediator.Send(new GenerateGrandWebTokenCommand() { Claims = claims });+ var refreshToken = _refreshTokenService.GenerateRefreshToken();+ await _refreshTokenService.SaveRefreshTokenToCustomer(customer, refreshToken);+ return new TokenDto() {+ AccessToken = token,+ RefreshToken = refreshToken+ };+ }}}diff --git a/src/Business/Grand.Business.Authentication/Interfaces/IRefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Interfaces/IRefreshTokenService.csnew file mode 100644index 000000000..e2aaf8dbc--- /dev/null+++ b/src/Business/Grand.Business.Authentication/Interfaces/IRefreshTokenService.cs@@ -0,0 +1,19 @@+using Grand.Domain.Customers;+using Grand.Domain.Security;+using System;+using System.Collections.Generic;+using System.Linq;+using System.Security.Claims;+using System.Text;+using System.Threading.Tasks;++namespace Grand.Business.Authentication.Interfaces+{+ public interface IRefreshTokenService+ {+ string GenerateRefreshToken();+ Task SaveRefreshTokenToCustomer(Customer customer, string refreshToken);+ Task<RefreshToken> GetCustomerRefreshToken(Customer customer);+ ClaimsPrincipal GetPrincipalFromToken(string token);+ }+}diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.csindex d301d5e49..3cd2828bb 100644--- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs+++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs@@ -1,4 +1,5 @@using Grand.Business.Authentication.Interfaces;+using Grand.Business.Common.Interfaces.Directory;using Grand.Business.Common.Interfaces.Security;using Grand.Business.Common.Services.Security;using Grand.Business.Customers.Interfaces;@@ -16,17 +17,23 @@ namespace Grand.Business.Authentication.Services{private readonly ICustomerService _customerService;private readonly IPermissionService _permissionService;+ private readonly IUserFieldService _userFieldService;+ private readonly IGroupService _groupService;private string _errorMessage;- public JwtBearerCustomerAuthenticationService(ICustomerService customerService,IPermissionService permissionService)+ public JwtBearerCustomerAuthenticationService(ICustomerService customerService,IPermissionService permissionService+ ,IUserFieldService userFieldService,IGroupService groupService){_customerService = customerService;_permissionService = permissionService;+ _userFieldService = userFieldService;+ _groupService = groupService;}public async Task<bool> Valid(TokenValidatedContext context){var email = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Email")?.Value;+ var passwordToken = context.Principal.Claims.ToList().FirstOrDefault(x => x.Type == "Token")?.Value;Customer customer = null;if(email is null){@@ -49,12 +56,22 @@ namespace Grand.Business.Authentication.Services_errorMessage = "Customer not exists/or not active in the customer table";return false;}+if(!(await _permissionService.Authorize(StandardPermission.AllowUseApi,customer))){_errorMessage = "Customer not has perrmission";return false;}+ var customerPasswordtoken = await _userFieldService.GetFieldsForEntity<string>(customer, SystemCustomerFieldNames.PasswordToken);+ var isGuest = await _groupService.IsGuest(customer);+ if(!isGuest && (string.IsNullOrEmpty(passwordToken) || !passwordToken.Equals(customerPasswordtoken)))+ {+ _errorMessage = "Invalid password token, create new token";+ return false;+ }++return true;}diff --git a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.csnew file mode 100644index 000000000..34f8e1b16--- /dev/null+++ b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs@@ -0,0 +1,72 @@+using Grand.Business.Authentication.Interfaces;+using Grand.Business.Common.Interfaces.Directory;+using Grand.Domain.Customers;+using Grand.Domain.Security;+using Grand.Infrastructure.Configuration;+using Microsoft.IdentityModel.Tokens;+using System;+using System.IdentityModel.Tokens.Jwt;+using System.Security.Claims;+using System.Security.Cryptography;+using System.Text;+using System.Threading.Tasks;++namespace Grand.Business.Authentication.Services+{+ public class RefreshTokenService : IRefreshTokenService+ {+ private const string _userFieldRefreshToken = "RefreshToken";+ private readonly IUserFieldService _userFieldService;+ private readonly GrandWebApiConfig _grandWebApiConfig;++ public RefreshTokenService(IUserFieldService userFieldService, GrandWebApiConfig grandWebApiConfig)+ {+ _userFieldService = userFieldService;+ _grandWebApiConfig = grandWebApiConfig;+ }++ public string GenerateRefreshToken()+ {+ var randomNumber = new byte[32];+ using (var rng = RandomNumberGenerator.Create())+ {+ rng.GetBytes(randomNumber);+ return Convert.ToBase64String(randomNumber);+ }+ }++ public async Task SaveRefreshTokenToCustomer(Customer customer, string refreshToken)+ {+ await _userFieldService.SaveField(customer, _userFieldRefreshToken, new RefreshToken() {+ Token = refreshToken,+ IsActive = true,+ ValidTo = DateTime.UtcNow.AddMinutes(_grandWebApiConfig.RefreshTokenExpiryInMinutes)+ });+ }++ public async Task<RefreshToken> GetCustomerRefreshToken(Customer customer)+ {+ return await _userFieldService.GetFieldsForEntity<RefreshToken>(customer, _userFieldRefreshToken);+ }++ public ClaimsPrincipal GetPrincipalFromToken(string token)+ {+ var tokenValidationParameters = new TokenValidationParameters {+ ValidateAudience = _grandWebApiConfig.ValidateAudience,+ ValidateIssuer = _grandWebApiConfig.ValidateIssuer,+ ValidateIssuerSigningKey = _grandWebApiConfig.ValidateIssuerSigningKey,+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_grandWebApiConfig.SecretKey)),+ ValidateLifetime = _grandWebApiConfig.ValidateLifetime+ };++ var tokenHandler = new JwtSecurityTokenHandler();+ SecurityToken securityToken;+ var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out securityToken);+ var jwtSecurityToken = securityToken as JwtSecurityToken;+ if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))+ throw new SecurityTokenException("Invalid token");++ return principal;+ }+ }+}diff --git a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.csindex 5948de8a5..5dde9c4e7 100644--- a/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs+++ b/src/Business/Grand.Business.Authentication/Startup/StartupApplication.cs@@ -19,6 +19,7 @@ namespace Grand.Business.Authentication.Startupservices.AddScoped<ITwoFactorAuthenticationService, TwoFactorAuthenticationService>();services.AddScoped<IExternalAuthenticationService, ExternalAuthenticationService>();services.AddScoped<IJwtBearerCustomerAuthenticationService, JwtBearerCustomerAuthenticationService>();+ services.AddScoped<IRefreshTokenService, RefreshTokenService>();}public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment){diff --git a/src/Core/Grand.Domain/Security/RefreshToken.cs b/src/Core/Grand.Domain/Security/RefreshToken.csnew file mode 100644index 000000000..b28aeece0--- /dev/null+++ b/src/Core/Grand.Domain/Security/RefreshToken.cs@@ -0,0 +1,15 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Text;+using System.Threading.Tasks;++namespace Grand.Domain.Security+{+ public class RefreshToken+ {+ public string Token { get; set; }+ public DateTime ValidTo { get; set; }+ public bool IsActive { get; set; }+ }+}diff --git a/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs b/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.csindex 7e0bb2c0e..79ba95f0e 100644--- a/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/GrandWebApiConfig.cs@@ -18,5 +18,6 @@ namespace Grand.Infrastructure.Configurationpublic bool ValidateLifetime { get; set; }public bool ValidateIssuerSigningKey { get; set; }public int ExpiryInMinutes { get; set; }+ public int RefreshTokenExpiryInMinutes { get; set; }}}diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.csnew file mode 100644index 000000000..1fcbe40fd--- /dev/null+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs@@ -0,0 +1,63 @@+using Grand.Domain.Security;+using System;+using System.Collections.Generic;+using System.ComponentModel;+using System.Globalization;+using System.Linq;+using System.Text;+using System.Text.Json;+using System.Threading.Tasks;++namespace Grand.Infrastructure.TypeConverters.Converter+{+ public class RefreshTokenTypeConverter : TypeConverter+ {+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ {+ if (sourceType == typeof(string))+ {+ return true;+ }++ return base.CanConvertFrom(context, sourceType);+ }++ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is string)+ {+ RefreshToken refreshToken = null;+ var valueStr = value as string;+ if (!string.IsNullOrEmpty(valueStr))+ {+ try+ {+ refreshToken = JsonSerializer.Deserialize<RefreshToken>(valueStr);+ }+ catch+ {+ //deserialize error+ }+ }+ return refreshToken;+ }+ return base.ConvertFrom(context, culture, value);+ }++ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)+ {+ if (destinationType == typeof(string))+ {+ var refreshToken = value as RefreshToken;+ if (refreshToken != null)+ {+ return JsonSerializer.Serialize(refreshToken);+ }++ return "";+ }++ return base.ConvertTo(context, culture, value, destinationType);+ }+ }+}diff --git a/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.csindex 8e4567b4f..df9f41327 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs@@ -3,6 +3,7 @@ using Grand.Domain.Common;using Grand.Domain.Shipping;using System.Collections.Generic;using System.ComponentModel;+using Grand.Domain.Security;namespace Grand.Infrastructure.TypeConverters{@@ -28,6 +29,9 @@ namespace Grand.Infrastructure.TypeConvertersTypeDescriptor.AddAttributes(typeof(List<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));TypeDescriptor.AddAttributes(typeof(IList<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));+ TypeDescriptor.AddAttributes(typeof(RefreshToken), new TypeConverterAttribute(typeof(RefreshTokenTypeConverter)));++}public int Order => 0;diff --git a/src/Web/Grand.Web/App_Data/appsettings.json b/src/Web/Grand.Web/App_Data/appsettings.jsonindex 7cd90f3ff..753cc4916 100644--- a/src/Web/Grand.Web/App_Data/appsettings.json+++ b/src/Web/Grand.Web/App_Data/appsettings.json@@ -165,7 +165,8 @@"ValidAudience": "","ValidateLifetime": true,"ValidateIssuerSigningKey": true,- "ExpiryInMinutes": 1440+ "ExpiryInMinutes": 1440,+ "RefreshTokenExpiryInMinutes":2000},"Api": {