[从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

posted @ 2020-03-24 17:19  一曲肝腸斷  阅读(2833)  评论(22编辑  收藏