ABP之IdentityServer4集成

源码模块:Volo.Abp.IdentityServer
 
初始化IdentityServer4
在ABP的分离部署模式中,有一个类库专门处理IdentityServer4,作为认证授权服务器。首先将IdentityServer设为启动项目,修改appsettings.json里面的ConnectionStrings节点,然后再Nuget管理器控制台中运行Update-Database,完成数据迁移。有一个数据种子生成器类 IdentityServerDataSeedContributor 专门处理初始化IdentityServer。
 
1. 依赖
默认的IdentityServer4主要依赖于 Volo.Abp.Account.Web.IdentityServer 这个Nuget包来支持基于IdentityServer4的登录和登出。从源码可以看到,这个包又依赖于AbpAccountWebModule、AbpIdentityServerDomainModule。前者处理登录界面,后者处理IdentityServer4(其实就是基于原生的IdentityServer4做了一层集成处理)。IdentityServerSupportedLoginModel、IdentityServerSupportedLogoutModel是仅有的两个类用于处理登录登出的,这里面涉及到大量的IdentityServer4的相关处理,可以好好看看。
 
初始化 Api服务器以及Web界面服务器
这两个东西就是.HttpApi.Host项目以及.Web.Host项目,主要就是修改appsettings.json里面的ConnectionStrings节点就可以了。在这里要特别说下需要部署redis,应该api项目依赖于它。而在Web项目中,需要配置OpenId Connect身份认证
private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies", options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = false;
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                    options.ClientId = configuration["AuthServer:ClientId"];
                    options.ClientSecret = configuration["AuthServer:ClientSecret"];

                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.Scope.Add("role");
                    options.Scope.Add("email");
                    options.Scope.Add("phone");
                    options.Scope.Add("ABPModuleSample_WithUI");

                    options.ClaimActions.MapJsonKey(AbpClaimTypes.UserName, "name");
                    options.ClaimActions.DeleteClaim("name");
                });
        }
虽然也有一个控制器,但是这个控制器并没有使用,主要还是web应用程序,即Pages目录下的Index.cshtml页面来处理,调用ChallengeAsync方法,直接重定向到指定AuthenticationScheme 的中间件。
 
总结
.Web.Host 项目使用OpenId Connect身份认证从.IdentityServer获取当前用户的身份和访问令牌. 然后使用访问令牌调用 .HttpApi.Host. HTTP API 服务器使用bearer token验证访问令牌获取当前用户声明并授权用户.
 
参考:

原文地址:https://www.cnblogs.com/zhiyong-ITNote/p/13773713.html