• abp vnext 用户角色权限管理系统搭建


    通过abp vnext已有的模块,identity(.net core identity)、IdentityServer(基于IdentityServer4),以及基础设施包括审计日志、权限管理、设置管理、租户管理等模块搭建用户角色权限管理系统。

    搭建的服务

    本次搭建的服务包括:授权服务中心、用户管理服务、业务模块;

    授权服务中心

    1.创建项目

    .net core 5 webapi项目。

    2.引用NuGet包

    在项目中引入如下NuGet包:

    1.Identity基础服务,Redis缓存服务以及在Vs中使用Manager Console。

    2.Serilog日志管理。

    3.abp相关服务。

     

    3.添加Module服务

    1.添加依赖

    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpPermissionManagementEntityFrameworkCoreModule),
        typeof(AbpAuditLoggingEntityFrameworkCoreModule),
        typeof(AbpSettingManagementEntityFrameworkCoreModule),
        typeof(AbpIdentityEntityFrameworkCoreModule),
        typeof(AbpIdentityServerEntityFrameworkCoreModule),
        typeof(AbpTenantManagementEntityFrameworkCoreModule),
        typeof(AbpAccountWebIdentityServerModule),
        typeof(AbpAccountApplicationModule),
        typeof(AbpAspNetCoreMvcUiBasicThemeModule)
        )]

    2.添加服务及初始化

    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.UseMySQL();
                });
    
                Configure<AbpLocalizationOptions>(options =>
                {
                    options.Languages.Add(new LanguageInfo("en", "en", "English"));
                });
    
                context.Services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = configuration["Redis:Configuration"];
                });
                context.Services
                    .AddAuthentication()
                    .AddIdentityServerJwt();
                context.Services.TryAddEnumerable(
        ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>,
            ConfigureJwtBearerOptions>());
                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();
    
                AsyncHelper.RunSync(async () =>
                {
                    using (var scope = context.ServiceProvider.CreateScope())
                    {
                        await scope.ServiceProvider
                            .GetRequiredService<IDataSeeder>()
                            .SeedAsync();
                    }
                });
            }

    4.修改配置文件及其他部分代码

    4.1.修改AppSettings.json

    {
      "Kestrel": {
        "Endpoints": {
          "Http": {
            "Url": "http://localhost:5000"
          }
        }
      },
      "ConnectionStrings": {
        "IdentityServer": "Server=localhost;Database=yhgl;Uid=yhgl;Pwd=yhgl",
        "Default": "Server=localhost;Database=yhgl;Uid=yhgl;Pwd=yhgl"
      },
      "ElasticSearch": {
        "Url": "http://localhost:5000"
      },
      "CorsOrigins": "http://localhost:5001,http://localhost:51057",
      "Redis": {
        "Configuration": "localhost:6379,allowadmin=true,password=123,keepAlive=180"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "AllowedHosts": "*"
    }

    4.2.修改Program.cs

        public class Program
        {
            public static int Main(string[] args)
            {
                var configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .AddEnvironmentVariables()
                    .Build();
    
                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                    .Enrich.WithProperty("Application", "AuthServer")
                    .Enrich.FromLogContext()
                    .WriteTo.File("Logs/logs.txt")
                    .WriteTo.Console()
                    .CreateLogger();
                try
                {
                    Log.Information("Starting AuthServer.Host.");
                    CreateHostBuilder(args).Build().Run();
                    return 0;
                }
                catch (Exception ex)
                {
                    Log.Fatal(ex, "AuthServer.Host terminated unexpectedly!");
                    return 1;
                }
                finally
                {
                    Log.CloseAndFlush();
                }
            }
            internal static IHostBuilder CreateHostBuilder(string[] args) =>
                Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.ConfigureKestrel(serverOptions =>
                        {
                        })
                        .UseStartup<Startup>();
                    })
                    .UseAutofac()
                    .UseSerilog();
        }

    4.3.修改Startup.cs

    public class Startup
        {
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddApplication<AuthServerHostModule>();
            }
    
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
            {
                app.InitializeApplication();
            }
        }

    5.运行及调试

    选择项目启动,也就是通过Kestrel启动。

    使用Postman进行测试访问接口为:

    http://localhost:5000/connect/token

    http post

    Content-Type application/x-www-form-urlencoded

    数据为:

    client_id:basic-web
    client_secret:password
    grant_type:password
    username:admin
    password:password

    返回值:

    {
        "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjVBMTcyNTBBNkYyMEMxNDc2OThFREFBQzUzRjRFNDIyIiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2MTQ5MjY3MzUsImV4cCI6MTY0NjQ2MjczNSwiaXNzIjoiaHR0cDovLzE5Mi4xNjguMC4xMjM6NTAwMCIsImF1ZCI6WyJCYXNlU2VydmljZSIsIkJ1c2luZXNzU2VydmljZSIsIldlYkFwcEdhdGV3YXkiXSwiY2xpZW50X2lkIjoiYmFzaWMtd2ViIiwic3ViIjoiYWMxMjkzZDYtMDcyZi0yYmMyLTU4MzgtMzlmYTczY2EyZjEzIiwiYXV0aF90aW1lIjoxNjE0OTI2NzM1LCJpZHAiOiJsb2NhbCIsInJvbGUiOiJhZG1pbiIsInBob25lX251bWJlcl92ZXJpZmllZCI6IkZhbHNlIiwiZW1haWwiOiJhZG1pbkBhYnAuaW8iLCJlbWFpbF92ZXJpZmllZCI6IkZhbHNlIiwibmFtZSI6ImFkbWluIiwiaWF0IjoxNjE0OTI2NzM1LCJzY29wZSI6WyJCYXNlU2VydmljZSIsIkJ1c2luZXNzU2VydmljZSIsIldlYkFwcEdhdGV3YXkiLCJvZmZsaW5lX2FjY2VzcyJdLCJhbXIiOlsicHdkIl19.OS9xePwkiUZW8v4amBxEUW1rf35z2P08vD9ztwosdN-A6KDU4pvaTFJXo0NYucgQvtFS14sfteGHUXKQIxPgRrt-wRoaAyCO3wHtHVzPQurAzBc46iTFt9FLWhkjRLzFHhcX8qeRx_tSqZGDEh3wRM4e804WwNMIlWFLDT86NSlbMB7YtCR_zbZHMSWDJ1lEvkOlBGEoWOO3wVfxGG2EACs1yNOi5X32q6A_ZzUxCn_IZcMDO4hnS6SWGbsqdfRaR5WV3yzSi8cL46oLAdLW8su_SbzYK3jIC0vemuAsoHHl7hGJDLHQ_eIj8ErYEcUKqfS4YB_UARRsNTIHAPYm1w",
        "expires_in": 31536000,
        "token_type": "Bearer",
        "refresh_token": "872C40685BE4249712F57C2CEFD2DDC91552A12F9FA0807CCF348443FA8A6F5C",
        "scope": "BaseService BusinessService offline_access WebAppGateway"
    }

    下一篇创建其他两个服务。

  • 相关阅读:
    第一篇日志
    Spring mvc 4系列教程(三)—— Spring4.X的新特性
    Spring mvc 4系列教程(二)——依赖管理(Dependency Management)和命名规范(Naming Conventions)
    Spring mvc 4系列教程(一)
    【管理心得之三十六】《黄帝内经》中的一句话
    【管理心得之三十五】好习惯也能惹“骂名”
    【管理心得之三十四】“禅宗境界”的员工
    【管理心得之三十三】管理者的“眉头”
    【管理心得之三十二】PMP杂谈---------爱情必胜术
    【管理心得之三十一】我的位置
  • 原文地址:https://www.cnblogs.com/GiserPage/p/14486649.html
Copyright © 2020-2023  润新知