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驗證訪問令牌獲取當前用戶聲明並授權用戶.
 
參考:


免責聲明!

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



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