[從0到1搭建ABP微服務] - 搭建授權服務


一、簡介

授權中心是微服務架構中最為核心重要的環節,不僅為web、app等客戶端提供身份授權服務,還對其他微服務提供身份認證服務。ABP微服務架構中使用identityServer4框架進行身份管理,並且ABP對ids4框架進行了進一步封裝,足以提供強大的統一授權服務。

二、創建工程

創建AuthServer.Host服務

在AuthServer目錄中創建解決方案,不啟用https配置

三、安裝模塊組件

在剛剛創建的空 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 Microsoft.Extensions.Caching.StackExchangeRedis -Version 3.1.0
PM> Install-Package Microsoft.AspNetCore.DataProtection.StackExchangeRedis -Version 3.1.0
PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.0
PM> Install-Package Volo.Abp.Account.Application -Version 2.0.1
PM> Install-Package Volo.Abp.Account.Web.IdentityServer -Version 2.0.1
PM> Install-Package Volo.Abp.AspNetCore.Mvc.UI.Theme.Basic -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.EntityFrameworkCore -Version 2.0.1
PM> Install-Package Volo.Abp.IdentityServer.EntityFrameworkCore -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

四、添加DbContext

在項目中添加DbContext並配置ef core遷移模型。

4.1 添加AuthServerDbContext

在EntityFrameworkCore目錄下添加AuthServerDbContext.cs配置所有ABP模型,代碼如下:

    public class AuthServerDbContext : AbpDbContext<AuthServerDbContext>
    {
        public AuthServerDbContext(DbContextOptions<AuthServerDbContext> options) 
            : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ConfigureIdentity();
            modelBuilder.ConfigureIdentityServer();
            modelBuilder.ConfigureAuditLogging();
            modelBuilder.ConfigurePermissionManagement();
            modelBuilder.ConfigureSettingManagement();
            modelBuilder.ConfigureTenantManagement();
        }
    }

4.2 添加AuthServerDbContextFactory

在EntityFrameworkCore目錄下創建AuthServerDbContextFactory.cs用於code first數據庫遷移

    public class AuthServerDbContextFactory : IDesignTimeDbContextFactory<AuthServerDbContext>
    {
        public AuthServerDbContext CreateDbContext(string[] args)
        {
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<AuthServerDbContext>()
                .UseSqlServer(configuration.GetConnectionString("Default"));

            return new AuthServerDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false);

            return builder.Build();
        }
    }

五、配置Module

5.1 添加AuthServerHostModule

在AuthServer.Host根目錄中添加AuthServerHostModule.cs

5.2 引用依賴

在AuthServerHostModule依次引用以下依賴
AbpAutofacModule
AbpPermissionManagementEntityFrameworkCoreModule
AbpAuditLoggingEntityFrameworkCoreModule
AbpSettingManagementEntityFrameworkCoreModule
AbpIdentityEntityFrameworkCoreModule
AbpIdentityServerEntityFrameworkCoreModule
AbpTenantManagementEntityFrameworkCoreModule
AbpEntityFrameworkCoreSqlServerModule
AbpAccountWebIdentityServerModule
AbpAccountApplicationModule
AbpAspNetCoreMvcUiBasicThemeModule

5.3 注冊服務與初始化應用

AuthServer中不需要注冊認證方式和Swagger服務,服務注冊和初始化應用代碼如下:

    public class AuthServerHostModule : AbpModule
    {
        private const string DefaultCorsPolicyName = "Default";

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();

            context.Services.AddAbpDbContext<AuthServerDbContext>(options =>
            {
                options.AddDefaultRepositories();
            });

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

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

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

            context.Services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName,
                builder =>
                {
                    builder.WithOrigins(configuration["CorsOrigins"]
                                .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray())
                        .WithAbpExposedHeaders()
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });

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

            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.UseCors(DefaultCorsPolicyName);
            app.UseAuthentication();
            app.UseMultiTenancy();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseAbpRequestLocalization();
            app.UseAuditing();
            app.UseMvcWithDefaultRouteAndArea();

            AsyncHelper.RunSync(async () =>
            {
                using (var scope = context.ServiceProvider.CreateScope())
                {
                    await scope.ServiceProvider
                        .GetRequiredService<IDataSeeder>()
                        .SeedAsync();
                }
            });
        }
    }

六、種子文件和配置文件

目前沒有使用ids4身份管理界面,暫時使用種子文件將client信息添加到數據庫。
詳細代碼可見Github

七、啟動

7.1 遷移數據庫

使用ef core遷移模型到數據庫
PM> Add-Migration init
PM> Update-Database

7.2 運行

使用Ctrl+F5啟動項目

啟動成功后種子文件已經添加到數據庫

7.3 登錄

使用postman獲取token

token成功返回

注:后期項目中作者直接使用了vue-element-admin登錄頁面進行授權登錄,所以刪除了授權服務不必要的登錄頁面,啟動授權服務時會有404找不到頁面異常,但並不影響功能。

搭建授權服務的全部過程已經介紹完畢,后續文章中會繼續介紹其他ABP服務的搭建,項目代碼地址:https://github.com/WilliamXu96/ABP-MicroService
文章目錄:https://www.cnblogs.com/william-xu/p/12537155.html


免責聲明!

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



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