[從0到1搭建ABP微服務] - 搭建ABP用戶管理服務


簡介

上一章中介紹了ABP微服務架構中授權服務的搭建,本篇將繼續介紹ABP微服務架構的搭建。ABP微服務架構中授權服務僅用來管理client身份的授權和驗證,並沒有用戶、角色、權限管理的業務,我們需要使用ABP搭建一個用來統一管理用戶權限業務的服務,以下將介紹ABP用戶模塊的服務搭建。

新建項目

在IdentityService目錄中創建一個新的 asp.net core項目IdentityService.Host

空項目結構如下

安裝模塊組件

在創建的空 asp.net core項目中安裝 .net core、ef core、ids4、abp等官方組件。
PM> Install-Package Serilog.Extensions.Hosting -Version 3.0.0
PM> Install-Package Serilog.Sinks.File -Version 4.0.0
PM> Install-Package Serilog.Sinks.Elasticsearch -Version 6.5.0
PM> Install-Package Swashbuckle.AspNetCore -Version 5.0.0-rc4
PM> Install-Package IdentityServer4.AccessTokenValidation -Version 3.0.0
PM> Install-Package Microsoft.Extensions.Caching.StackExchangeRedis -Version 3.1.0
PM> Install-Package Microsoft.AspNetCore.DataProtection.StackExchangeRedis -Version 3.1.0
PM> Install-Package Volo.Abp.AspNetCore.MultiTenancy -Version 2.0.1
PM> Install-Package Volo.Abp.AuditLogging.EntityFrameworkCore -Version 2.0.1
PM> Install-Package Volo.Abp.Autofac -Version 2.0.1
PM> Install-Package Volo.Abp.EntityFrameworkCore.SqlServer -Version 2.0.1
PM> Install-Package Volo.Abp.Identity.Application -Version 2.0.1
PM> Install-Package Volo.Abp.Identity.EntityFrameworkCore -Version 2.0.1
PM> Install-Package Volo.Abp.Identity.HttpApi -Version 2.0.1
PM> Install-Package Volo.Abp.PermissionManagement.EntityFrameworkCore -Version 2.0.1
PM> Install-Package Volo.Abp.SettingManagement.EntityFrameworkCore -Version 2.0.1
PM> Install-Package Volo.Abp.TenantManagement.EntityFrameworkCore -Version 2.0.1

配置Module

添加IdentityServiceHostModule

在項目根目錄下添加IdentityServiceHostModule.cs

引用依賴

在IdentityServiceHostModule中依次引用以下依賴:
AbpAutofacModule
AbpAspNetCoreMultiTenancyModule
AbpEntityFrameworkCoreSqlServerModule
AbpAuditLoggingEntityFrameworkCoreModule
AbpPermissionManagementEntityFrameworkCoreModule
AbpSettingManagementEntityFrameworkCoreModule
AbpTenantManagementEntityFrameworkCoreModule
AbpIdentityHttpApiModule
AbpIdentityEntityFrameworkCoreModule
AbpIdentityApplicationModule

注冊服務與初始化應用

注冊認證方式、swagger、redis等服務,代碼如下:

    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpAspNetCoreMultiTenancyModule),
        typeof(AbpEntityFrameworkCoreSqlServerModule),
        typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        typeof(AbpPermissionManagementEntityFrameworkCoreModule),
        typeof(AbpSettingManagementEntityFrameworkCoreModule),
        typeof(AbpTenantManagementEntityFrameworkCoreModule),
        typeof(AbpIdentityHttpApiModule),
        typeof(AbpIdentityEntityFrameworkCoreModule),
        typeof(AbpIdentityApplicationModule)
    )]
    public class IdentityServiceHostModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();

            context.Services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.ApiName = configuration["AuthServer:ApiName"];
                    options.RequireHttpsMetadata = false;
                });

            context.Services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "Identity Service API", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);
                options.CustomSchemaIds(type => type.FullName);
            });

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
            });

            Configure<AbpDbContextOptions>(options =>
            {
                options.UseSqlServer();
            });

            context.Services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = configuration["Redis:Configuration"];
            });

            Configure<AbpAuditingOptions>(options =>
            {
                options.IsEnabledForGetRequests = true;
                options.ApplicationName = "IdentityService";
            });

            var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
            context.Services.AddDataProtection()
                .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            app.UseCorrelationId();
            app.UseVirtualFiles();
            app.UseRouting();
            app.UseAuthentication();

            app.Use(async (ctx, next) =>
            {
                var currentPrincipalAccessor = ctx.RequestServices.GetRequiredService<ICurrentPrincipalAccessor>();
                var map = new Dictionary<string, string>()
                {
                    { "sub", AbpClaimTypes.UserId },
                    { "role", AbpClaimTypes.Role },
                    { "email", AbpClaimTypes.Email },
                };
                var mapClaims = currentPrincipalAccessor.Principal.Claims.Where(p => map.Keys.Contains(p.Type)).ToList();
                currentPrincipalAccessor.Principal.AddIdentity(new ClaimsIdentity(mapClaims.Select(p => new Claim(map[p.Type], p.Value, p.ValueType, p.Issuer))));
                await next();
            });

            app.UseAbpRequestLocalization(); 
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Identity Service API");
            });
            app.UseAuditing();
            app.UseMvcWithDefaultRouteAndArea();
        }
    }

添加swagger路由

將服務index首頁配置為swagger頁面,方便獲取api文檔。配置十分簡單,將Home控制器的Index頁跳轉至swagger路由:

    public class HomeController : AbpController
    {
        public ActionResult Index()
        {
            return Redirect("/swagger");
        }
    }

種子文件和配置文件

授權服務中已經加入了所有ABP服務的種子信息,該服務無需再添加。配置文件如下:

{
  "AuthServer": {
    "Authority": "http://localhost:53362",
    "ApiName": "IdentityService"
  },
  "ConnectionStrings": {
    "Default": "Server=localhost;Database=ABP;User Id=sa;Password=123456;"
  },
  "ElasticSearch": {
    "Url": "http://localhost:9200"
  },
  "Redis": {
    "Configuration": "localhost"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

授權地址配的是上篇文章中搭建的授權服務地址,自己搭建需要根據授權服務host地址進行修改。

啟動

無需遷移數據庫,直接Ctrl+F5運行

可以看到啟動成功並成功跳轉swagger頁面。此時再Ctrl+F5運行授權服務,然后獲取token測試Identity Service API

請求結果可以看出Identity Service已經認證通過並返回角色信息。

代碼地址:https://github.com/WilliamXu96/ABP-MicroService
文章目錄:https://www.cnblogs.com/william-xu/p/12537155.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM