经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » 编程经验 » 查看文章
ABP微服务系列学习-搭建自己的微服务结构(三)
来源:cnblogs  作者:饭勺oO  时间:2023/3/3 8:53:09  对本文有异议

上一篇我们基础服务初步搭建完毕,接下来我们整一下认证和网关。

搭建认证服务

认证服务的话,ABP CLI生成的所有模板都包括了一个AuthServer。我们直接生成模板然后微调一下就可以直接用了。

  1. abp new FunShow -t app --tiered

使用命令创建模板后,我们可以找到一个AuthServer。把项目移动到Apps目录下,然后我们开始改造一下这个项目。
首先修改项目文件的引用配置
修改EFCore项目引用为AdministrationService.EntityFrameworkCore和IdentityService.EntityFrameworkCore,
然后添加Shared.Localization和Shared.Hosting.AspNetCore项目引用,别的基本不用怎么修改,完整项目配置为:

  1. <Project Sdk="Microsoft.NET.Sdk.Web">
  2. <Import Project="..\..\..\..\common.props" />
  3. <PropertyGroup>
  4. <TargetFramework>net7.0</TargetFramework>
  5. <UserSecretsId>b83bc18b-a6ca-4e2d-a827-26ffaff35dce</UserSecretsId>
  6. <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
  7. <DockerfileContext>..\..\..\..</DockerfileContext>
  8. </PropertyGroup>
  9. <ItemGroup>
  10. <PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="6.0.5" />
  11. <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" />
  12. </ItemGroup>
  13. <ItemGroup>
  14. <PackageReference Include="Volo.Abp.Caching.StackExchangeRedis" Version="7.0.0" />
  15. <PackageReference Include="Volo.Abp.EventBus.RabbitMQ" Version="7.0.0" />
  16. <PackageReference Include="Volo.Abp.BackgroundJobs.RabbitMQ" Version="7.0.0" />
  17. <PackageReference Include="Volo.Abp.Account.Web.OpenIddict" Version="7.0.0" />
  18. <PackageReference Include="Volo.Abp.Account.Application" Version="7.0.0" />
  19. <PackageReference Include="Volo.Abp.Account.HttpApi" Version="7.0.0" />
  20. </ItemGroup>
  21. <ItemGroup>
  22. <ProjectReference Include="..\..\..\..\services\administration\src\FunShow.AdministrationService.EntityFrameworkCore\FunShow.AdministrationService.EntityFrameworkCore.csproj" />
  23. <ProjectReference Include="..\..\..\..\services\identity\src\FunShow.IdentityService.EntityFrameworkCore\FunShow.IdentityService.EntityFrameworkCore.csproj" />
  24. <ProjectReference Include="..\..\..\..\shared\FunShow.Shared.Hosting.AspNetCore\FunShow.Shared.Hosting.AspNetCore.csproj" />
  25. <ProjectReference Include="..\..\..\..\shared\FunShow.Shared.Localization\FunShow.Shared.Localization.csproj" />
  26. </ItemGroup>
  27. <ItemGroup>
  28. <PackageReference Include="Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonXLite" Version="2.0.0-*" />
  29. </ItemGroup>
  30. <ItemGroup>
  31. <Compile Remove="Logs\**" />
  32. <Content Remove="Logs\**" />
  33. <EmbeddedResource Remove="Logs\**" />
  34. <None Remove="Logs\**" />
  35. </ItemGroup>
  36. </Project>

然后修改Program文件,主要是日志配置修改一下,别的不用改动

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Hosting;
  6. using FunShow.Shared.Hosting.AspNetCore;
  7. using Serilog;
  8. namespace FunShow.AuthServer;
  9. public class Program
  10. {
  11. public async static Task<int> Main(string[] args)
  12. {
  13. var assemblyName = typeof(Program).Assembly.GetName().Name;
  14. SerilogConfigurationHelper.Configure(assemblyName);
  15. try
  16. {
  17. Log.Information($"Starting {assemblyName}.");
  18. var builder = WebApplication.CreateBuilder(args);
  19. builder.Host
  20. .AddAppSettingsSecretsJson()
  21. .UseAutofac()
  22. .UseSerilog();
  23. await builder.AddApplicationAsync<FunShowAuthServerModule>();
  24. var app = builder.Build();
  25. await app.InitializeApplicationAsync();
  26. await app.RunAsync();
  27. return 0;
  28. }
  29. catch (Exception ex)
  30. {
  31. Log.Fatal(ex, $"{assemblyName} terminated unexpectedly!");
  32. return 1;
  33. }
  34. finally
  35. {
  36. Log.CloseAndFlush();
  37. }
  38. }
  39. }

修改module.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography.X509Certificates;
  6. using Microsoft.AspNetCore.Builder;
  7. using Microsoft.AspNetCore.Cors;
  8. using Microsoft.AspNetCore.DataProtection;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.DependencyInjection.Extensions;
  11. using Microsoft.Extensions.Hosting;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.Extensions.Configuration;
  14. using FunShow.AdministrationService.EntityFrameworkCore;
  15. using FunShow.IdentityService.EntityFrameworkCore;
  16. using FunShow.Shared.Hosting.AspNetCore;
  17. using Prometheus;
  18. using StackExchange.Redis;
  19. using Volo.Abp;
  20. using Volo.Abp.Account;
  21. using Volo.Abp.Account.Web;
  22. using Volo.Abp.AspNetCore.Mvc.UI.Bundling;
  23. using Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonXLite;
  24. using Volo.Abp.AspNetCore.Mvc.UI.Theme.LeptonXLite.Bundling;
  25. using Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared;
  26. using Volo.Abp.Auditing;
  27. using Volo.Abp.BackgroundJobs.RabbitMQ;
  28. using Volo.Abp.Caching;
  29. using Volo.Abp.Caching.StackExchangeRedis;
  30. using Volo.Abp.Emailing;
  31. using Volo.Abp.EventBus.RabbitMq;
  32. using Volo.Abp.Modularity;
  33. using Volo.Abp.MultiTenancy;
  34. using Volo.Abp.OpenIddict;
  35. using Volo.Abp.UI.Navigation.Urls;
  36. using Volo.Abp.VirtualFileSystem;
  37. using Microsoft.AspNetCore.HttpOverrides;
  38. using FunShow.Shared.Localization;
  39. namespace FunShow.AuthServer;
  40. [DependsOn(
  41. typeof(AbpCachingStackExchangeRedisModule),
  42. typeof(AbpEventBusRabbitMqModule),
  43. typeof(AbpBackgroundJobsRabbitMqModule),
  44. typeof(AbpAspNetCoreMvcUiLeptonXLiteThemeModule),
  45. typeof(AbpAccountWebOpenIddictModule),
  46. typeof(AbpAccountApplicationModule),
  47. typeof(AbpAccountHttpApiModule),
  48. typeof(AdministrationServiceEntityFrameworkCoreModule),
  49. typeof(IdentityServiceEntityFrameworkCoreModule),
  50. typeof(FunShowSharedHostingAspNetCoreModule),
  51. typeof(FunShowSharedLocalizationModule)
  52. )]
  53. public class FunShowAuthServerModule : AbpModule
  54. {
  55. public override void PreConfigureServices(ServiceConfigurationContext context)
  56. {
  57. var hostingEnvironment = context.Services.GetHostingEnvironment();
  58. var configuration = context.Services.GetConfiguration();
  59. PreConfigure<OpenIddictBuilder>(builder =>
  60. {
  61. builder.AddValidation(options =>
  62. {
  63. options.AddAudiences("AccountService");
  64. options.UseLocalServer();
  65. options.UseAspNetCore();
  66. });
  67. });
  68. if (!hostingEnvironment.IsDevelopment())
  69. {
  70. PreConfigure<AbpOpenIddictAspNetCoreOptions>(options =>
  71. {
  72. options.AddDevelopmentEncryptionAndSigningCertificate = false;
  73. });
  74. PreConfigure<OpenIddictServerBuilder>(builder =>
  75. {
  76. builder.AddSigningCertificate(GetSigningCertificate(hostingEnvironment, configuration));
  77. builder.AddEncryptionCertificate(GetSigningCertificate(hostingEnvironment, configuration));
  78. });
  79. }
  80. }
  81. public override void ConfigureServices(ServiceConfigurationContext context)
  82. {
  83. //You can disable this setting in production to avoid any potential security risks.
  84. Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
  85. var hostingEnvironment = context.Services.GetHostingEnvironment();
  86. var configuration = context.Services.GetConfiguration();
  87. ConfigureBundles();
  88. ConfigureSwagger(context, configuration);
  89. ConfigureSameSiteCookiePolicy(context);
  90. ConfigureExternalProviders(context);
  91. Configure<AbpMultiTenancyOptions>(options =>
  92. {
  93. options.IsEnabled = true;
  94. });
  95. Configure<AbpAuditingOptions>(options =>
  96. {
  97. options.ApplicationName = "AuthServer";
  98. });
  99. Configure<AppUrlOptions>(options =>
  100. {
  101. options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"];
  102. options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"].Split(','));
  103. });
  104. Configure<AbpDistributedCacheOptions>(options =>
  105. {
  106. options.KeyPrefix = "FunShow:";
  107. });
  108. var dataProtectionBuilder = context.Services.AddDataProtection().SetApplicationName("FunShow");
  109. var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
  110. dataProtectionBuilder.PersistKeysToStackExchangeRedis(redis, "FunShow-Protection-Keys");
  111. context.Services.AddCors(options =>
  112. {
  113. options.AddDefaultPolicy(builder =>
  114. {
  115. builder
  116. .WithOrigins(
  117. configuration["App:CorsOrigins"]
  118. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  119. .Select(o => o.Trim().RemovePostFix("/"))
  120. .ToArray()
  121. )
  122. .WithAbpExposedHeaders()
  123. .SetIsOriginAllowedToAllowWildcardSubdomains()
  124. .AllowAnyHeader()
  125. .AllowAnyMethod()
  126. .AllowCredentials();
  127. });
  128. });
  129. #if DEBUG
  130. context.Services.Replace(ServiceDescriptor.Singleton<IEmailSender, NullEmailSender>());
  131. #endif
  132. if (hostingEnvironment.IsDevelopment())
  133. {
  134. Configure<AbpVirtualFileSystemOptions>(options =>
  135. {
  136. options.FileSets.ReplaceEmbeddedByPhysical<FunShowSharedLocalizationModule>(Path.Combine(
  137. hostingEnvironment.ContentRootPath,
  138. $"..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}shared{Path.DirectorySeparatorChar}FunShow.Shared.Localization"));
  139. });
  140. }
  141. }
  142. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  143. {
  144. var app = context.GetApplicationBuilder();
  145. var env = context.GetEnvironment();
  146. var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
  147. if (env.IsDevelopment())
  148. {
  149. app.UseDeveloperExceptionPage();
  150. }
  151. app.UseAbpRequestLocalization();
  152. if (!env.IsDevelopment())
  153. {
  154. app.UseErrorPage();
  155. }
  156. var forwardOptions = new ForwardedHeadersOptions
  157. {
  158. ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
  159. RequireHeaderSymmetry = false
  160. };
  161. forwardOptions.KnownNetworks.Clear();
  162. forwardOptions.KnownProxies.Clear();
  163. // ref: https://github.com/aspnet/Docs/issues/2384
  164. app.UseForwardedHeaders(forwardOptions);
  165. app.UseCorrelationId();
  166. app.UseAbpSecurityHeaders();
  167. app.UseStaticFiles();
  168. app.UseRouting();
  169. app.UseCors();
  170. app.UseCookiePolicy();
  171. app.UseHttpMetrics();
  172. app.UseAuthentication();
  173. app.UseAbpOpenIddictValidation();
  174. app.UseAbpSerilogEnrichers();
  175. app.UseUnitOfWork();
  176. app.UseAuthorization();
  177. app.UseSwagger();
  178. app.UseAbpSwaggerUI(options =>
  179. {
  180. options.SwaggerEndpoint("/swagger/v1/swagger.json", "Account Service API");
  181. options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
  182. });
  183. app.UseAuditing();
  184. app.UseConfiguredEndpoints(endpoints =>
  185. {
  186. endpoints.MapMetrics();
  187. });
  188. }
  189. private void ConfigureBundles()
  190. {
  191. Configure<AbpBundlingOptions>(options =>
  192. {
  193. options.StyleBundles.Configure(
  194. LeptonXLiteThemeBundles.Styles.Global,
  195. bundle =>
  196. {
  197. bundle.AddFiles("/global-styles.css");
  198. }
  199. );
  200. });
  201. }
  202. private void ConfigureExternalProviders(ServiceConfigurationContext context)
  203. {
  204. context.Services.AddAuthentication();
  205. }
  206. private X509Certificate2 GetSigningCertificate(IWebHostEnvironment hostingEnv, IConfiguration configuration)
  207. {
  208. var fileName = "authserver.pfx";
  209. var passPhrase = "2D7AA457-5D33-48D6-936F-C48E5EF468ED";
  210. var file = Path.Combine(hostingEnv.ContentRootPath, fileName);
  211. if (!File.Exists(file))
  212. {
  213. throw new FileNotFoundException($"Signing Certificate couldn't found: {file}");
  214. }
  215. return new X509Certificate2(file, passPhrase);
  216. }
  217. private void ConfigureSwagger(ServiceConfigurationContext context, IConfiguration configuration)
  218. {
  219. SwaggerConfigurationHelper.ConfigureWithAuth(
  220. context: context,
  221. authority: configuration["AuthServer:Authority"],
  222. scopes: new Dictionary<string, string> {
  223. /* Requested scopes for authorization code request and descriptions for swagger UI only */
  224. { "AccountService", "Account Service API" }
  225. },
  226. apiTitle: "Account Service API"
  227. );
  228. }
  229. private void ConfigureSameSiteCookiePolicy(ServiceConfigurationContext context)
  230. {
  231. context.Services.AddSameSiteCookiePolicy();
  232. }
  233. }

最后修改配置文件

  1. {
  2. "App": {
  3. "SelfUrl": "https://localhost:44322",
  4. "CorsOrigins": "http://localhost:4200,http://localhost:9527,https://localhost:44307,https://localhost:44325,https://localhost:44353,https://localhost:44367,https://localhost:44388,https://localhost:44381,https://localhost:44361",
  5. "RedirectAllowedUrls": "http://localhost:4200,https://localhost:44307,https://localhost:44321,http://localhost:9527"
  6. },
  7. "AuthServer": {
  8. "Authority": "https://localhost:44322",
  9. "RequireHttpsMetadata": "true",
  10. "SwaggerClientId": "WebGateway_Swagger"
  11. },
  12. "Logging": {
  13. "LogLevel": {
  14. "Default": "Information",
  15. "Microsoft": "Warning",
  16. "Microsoft.Hosting.Lifetime": "Information"
  17. }
  18. },
  19. "AllowedHosts": "*",
  20. "ConnectionStrings": {
  21. "AdministrationService": "Host=localhost;Port=5432;User ID=postgres;password=myPassw0rd;Pooling=true;Database=FunShow_Administration;",
  22. "IdentityService": "Host=localhost;Port=5432;User ID=postgres;password=myPassw0rd;Pooling=true;Database=FunShow_Identity;"
  23. },
  24. "StringEncryption": {
  25. "DefaultPassPhrase": "fCrJICTG3WoyissG"
  26. },
  27. "Redis": {
  28. "Configuration": "localhost:6379"
  29. },
  30. "RabbitMQ": {
  31. "Connections": {
  32. "Default": {
  33. "HostName": "localhost"
  34. }
  35. },
  36. "EventBus": {
  37. "ClientName": "FunShow_AuthServer",
  38. "ExchangeName": "FunShow"
  39. }
  40. },
  41. "ElasticSearch": {
  42. "Url": "http://localhost:9200"
  43. }
  44. }

这样我们认证服务即修改完成。

搭建网关服务

网关服务我们直接新建一个空asp.net core项目。
然后只需要添加一个我们的Shared.Hosting.Gateways项目引用即可。

  1. <Project Sdk="Microsoft.NET.Sdk.Web">
  2. <Import Project="..\..\..\..\common.props" />
  3. <PropertyGroup>
  4. <TargetFramework>net7.0</TargetFramework>
  5. </PropertyGroup>
  6. <ItemGroup>
  7. <ProjectReference Include="..\..\..\..\shared\FunShow.Shared.Hosting.Gateways\FunShow.Shared.Hosting.Gateways.csproj" />
  8. </ItemGroup>
  9. <ItemGroup>
  10. <Compile Remove="Logs\**" />
  11. <Content Remove="Logs\**" />
  12. <EmbeddedResource Remove="Logs\**" />
  13. <None Remove="Logs\**" />
  14. </ItemGroup>
  15. </Project>

修改Program.cs

  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Hosting;
  6. using FunShow.Shared.Hosting.AspNetCore;
  7. using Serilog;
  8. namespace FunShow.WebGateway;
  9. public class Program
  10. {
  11. public async static Task<int> Main(string[] args)
  12. {
  13. var assemblyName = typeof(Program).Assembly.GetName().Name;
  14. SerilogConfigurationHelper.Configure(assemblyName);
  15. try
  16. {
  17. Log.Information($"Starting {assemblyName}.");
  18. var builder = WebApplication.CreateBuilder(args);
  19. builder.Host
  20. .AddAppSettingsSecretsJson()
  21. .AddYarpJson()
  22. .UseAutofac()
  23. .UseSerilog();
  24. await builder.AddApplicationAsync<FunShowWebGatewayModule>();
  25. var app = builder.Build();
  26. await app.InitializeApplicationAsync();
  27. await app.RunAsync();
  28. return 0;
  29. }
  30. catch (Exception ex)
  31. {
  32. Log.Fatal(ex, $"{assemblyName} terminated unexpectedly!");
  33. return 1;
  34. }
  35. finally
  36. {
  37. Log.CloseAndFlush();
  38. }
  39. }
  40. }

这里和认证服务基本一致,就是多了一个AddYarpJson()来添加我们的yarp的配置文件。
在目录下新建yarp.json文件,添加我们的yarp配置内容。配置集群和路由如下:

  1. {
  2. "ReverseProxy": {
  3. "Routes": {
  4. "Account Service": {
  5. "ClusterId": "accountCluster",
  6. "Match": {
  7. "Path": "/api/account/{**everything}"
  8. }
  9. },
  10. "Identity Service": {
  11. "ClusterId": "identityCluster",
  12. "Match": {
  13. "Path": "/api/identity/{**everything}"
  14. }
  15. },
  16. "Administration Service": {
  17. "ClusterId": "administrationCluster",
  18. "Match": {
  19. "Path": "/api/abp/{**everything}"
  20. }
  21. },
  22. "Logging Service": {
  23. "ClusterId": "loggingCluster",
  24. "Match": {
  25. "Path": "/api/LoggingService/{**everything}"
  26. }
  27. },
  28. "feature-management-route": {
  29. "ClusterId": "feature-management-cluster",
  30. "Match": {
  31. "Path": "/api/feature-management/{**everything}"
  32. }
  33. },
  34. "permission-management-route": {
  35. "ClusterId": "permission-management-cluster",
  36. "Match": {
  37. "Path": "/api/permission-management/{**everything}"
  38. }
  39. },
  40. "setting-management-route": {
  41. "ClusterId": "setting-management-cluster",
  42. "Match": {
  43. "Path": "/api/setting-management/{**everything}"
  44. }
  45. }
  46. },
  47. "Clusters": {
  48. "accountCluster": {
  49. "Destinations": {
  50. "destination1": {
  51. "Address": "https://localhost:44322"
  52. }
  53. }
  54. },
  55. "identityCluster": {
  56. "Destinations": {
  57. "destination1": {
  58. "Address": "https://localhost:44388"
  59. }
  60. }
  61. },
  62. "administrationCluster": {
  63. "Destinations": {
  64. "destination1": {
  65. "Address": "https://localhost:44367"
  66. }
  67. }
  68. },
  69. "loggingCluster": {
  70. "Destinations": {
  71. "destination1": {
  72. "Address": "https://localhost:45124"
  73. }
  74. }
  75. },
  76. "feature-management-cluster": {
  77. "Destinations": {
  78. "destination1": {
  79. "Address": "https://localhost:44367"
  80. }
  81. }
  82. },
  83. "permission-management-cluster": {
  84. "Destinations": {
  85. "destination1": {
  86. "Address": "https://localhost:44367"
  87. }
  88. }
  89. },
  90. "setting-management-cluster": {
  91. "Destinations": {
  92. "destination1": {
  93. "Address": "https://localhost:44367"
  94. }
  95. }
  96. }
  97. }
  98. }
  99. }

在appsettings.json文件添加我们认证服务的地址

  1. {
  2. "App": {
  3. "SelfUrl": "https://localhost:44325",
  4. "CorsOrigins": "http://localhost:4200,https://localhost:44307,http://localhost:9527"
  5. },
  6. "AuthServer": {
  7. "Authority": "https://localhost:44322",
  8. "RequireHttpsMetadata": "true",
  9. "SwaggerClientId": "WebGateway_Swagger"
  10. },
  11. "Logging": {
  12. "LogLevel": {
  13. "Default": "Information",
  14. "Microsoft": "Warning",
  15. "Microsoft.Hosting.Lifetime": "Information"
  16. }
  17. },
  18. "AllowedHosts": "*",
  19. "Redis": {
  20. "Configuration": "localhost:6379"
  21. },
  22. "ElasticSearch": {
  23. "Url": "http://localhost:9200"
  24. }
  25. }

最后我们添加FunShowWebGatewayModule文件。配置我们yarp的服务。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Cors;
  6. using Microsoft.AspNetCore.Rewrite;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Hosting;
  10. using FunShow.Shared.Hosting.AspNetCore;
  11. using FunShow.Shared.Hosting.Gateways;
  12. using Volo.Abp;
  13. using Volo.Abp.Modularity;
  14. namespace FunShow.WebGateway;
  15. [DependsOn(
  16. typeof(FunShowSharedHostingGatewaysModule)
  17. )]
  18. public class FunShowWebGatewayModule : AbpModule
  19. {
  20. public override void ConfigureServices(ServiceConfigurationContext context)
  21. {
  22. // Enable if you need hosting environment
  23. // var hostingEnvironment = context.Services.GetHostingEnvironment();
  24. var configuration = context.Services.GetConfiguration();
  25. var hostingEnvironment = context.Services.GetHostingEnvironment();
  26. SwaggerConfigurationHelper.ConfigureWithAuth(
  27. context: context,
  28. authority: configuration["AuthServer:Authority"],
  29. scopes: new
  30. Dictionary<string, string> /* Requested scopes for authorization code request and descriptions for swagger UI only */ {
  31. { "AccountService", "Account Service API" },
  32. { "IdentityService", "Identity Service API" },
  33. { "AdministrationService", "Administration Service API" },
  34. { "LoggingService", "Logging Service API" }
  35. },
  36. apiTitle: "Web Gateway API"
  37. );
  38. context.Services.AddCors(options =>
  39. {
  40. options.AddDefaultPolicy(builder =>
  41. {
  42. builder
  43. .WithOrigins(
  44. configuration["App:CorsOrigins"]
  45. .Split(",", StringSplitOptions.RemoveEmptyEntries)
  46. .Select(o => o.Trim().RemovePostFix("/"))
  47. .ToArray()
  48. )
  49. .WithAbpExposedHeaders()
  50. .SetIsOriginAllowedToAllowWildcardSubdomains()
  51. .AllowAnyHeader()
  52. .AllowAnyMethod()
  53. .AllowCredentials();
  54. });
  55. });
  56. }
  57. public override void OnApplicationInitialization(ApplicationInitializationContext context)
  58. {
  59. var app = context.GetApplicationBuilder();
  60. var env = context.GetEnvironment();
  61. if (env.IsDevelopment())
  62. {
  63. app.UseDeveloperExceptionPage();
  64. }
  65. app.UseCorrelationId();
  66. app.UseAbpSerilogEnrichers();
  67. app.UseCors();
  68. app.UseSwaggerUIWithYarp(context);
  69. app.UseRewriter(new RewriteOptions()
  70. // Regex for "", "/" and "" (whitespace)
  71. .AddRedirect("^(|\\|\\s+)$", "/swagger"));
  72. app.UseRouting();
  73. app.UseEndpoints(endpoints =>
  74. {
  75. endpoints.MapReverseProxy();
  76. });
  77. }
  78. }

UseSwaggerUIWithYarp是从我们Yarp配置文件中读取服务信息去构造swagger路由配置。
好了,到这我们认证服务和网关服务也搭建完毕,下一篇我们开始迁移数据库。

原文链接:https://www.cnblogs.com/fanshaoO/p/17166952.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号