IdentityServer4使用教程1--搭建ID4網(wǎng)站。

簡(jiǎn)介

Identity Server 4(以下簡(jiǎn)稱ID4)是一個(gè)基于oauth2和OpenID的身份認(rèn)證組件,基于這個(gè)組件可以快速開發(fā)自己的身份認(rèn)證網(wǎng)站,支持單點(diǎn)登錄,快速完成工業(yè)級(jí)的身份認(rèn)證系統(tǒng)。ID4也是dotnetcore推薦的身份認(rèn)證組件。
本教程將基于dotnetcore1.1.2來實(shí)現(xiàn)一個(gè)完整的ID4身份網(wǎng)站,并搭配各種應(yīng)用來使用這個(gè)認(rèn)證系統(tǒng)。

目前ID4對(duì)于dotnetcore2.0.0的支持還有問題,在問題修復(fù)后,會(huì)升級(jí)到.net core 2.0.0

和core一樣,ID4也完全支持linux和Mac,大家可以按照下面的步驟,在linux上運(yùn)行。當(dāng)然windows上有一個(gè)ubuntu的子系統(tǒng),可以用來驗(yàn)證,就不需要單獨(dú)去安裝linux虛擬機(jī)了。關(guān)于windows上的ubuntu子系統(tǒng),可以參看這個(gè)教程

環(huán)境準(zhǔn)備

首先我們需要配置好環(huán)境,這里我們使用chocolatey來快速把環(huán)境準(zhǔn)備好。 關(guān)于chocolatey的使用請(qǐng)參看chocolate使用教程。從上到下,我們安裝了:

  1. curl用于下載文件.
  2. git用于管理代碼,在本教程中主要是比較修改的文件。
  3. visualstudiocode主要是用于編輯代碼。
  4. dotnetcore-sdk安裝了兩個(gè),主要是ID4目前還不支持.net core 2.0.
 choco install cUrl -y
 choco install git -y
 choco install visualstudiocode -y
 choco install dotnetcore-sdk --version 1.1.2 -y
 choco install dotnetcore-sdk --version 2.0.0 -y

準(zhǔn)備asp.net core MVC基礎(chǔ)代碼

  1. 使用管理員權(quán)限打開一個(gè)CMD窗口
  2. 創(chuàng)建目錄并進(jìn)入這個(gè)目錄mkdir ID4.Learn && cd ID4.Learn
  3. 在根目錄下創(chuàng)建global.json文件以便切換dotnet 2.0.0 到1.0.4版本
    {
        "sdk": { "version": "1.0.4"  }
     }
    

    也可以使用下面的命令從github直接下載這個(gè)文件
    curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/global.json

  4. 運(yùn)行dotnet CLI命令創(chuàng)建一個(gè)帶Identity的MVC框架程序ID4.Server
    dotnet new mvc -au Individual -o ID4.Server

    dotnet CLI的命令參數(shù),可以通過dotnet -h來查看
    此處的-au Individual表示生成的MVC文件帶有認(rèn)證信息, -o ID4.Server表示輸出到ID4.Server目錄,項(xiàng)目名稱也是ID4.Server.

  5. 轉(zhuǎn)到ID4.Server目錄下,運(yùn)行下面命令來查看生成的MVC程序
    cd ID4.Server
    dotnet restore
    dotnet build
    dotnet run
    

    在dotnet 2.0以后,運(yùn)行dotnet run的時(shí)候會(huì)自動(dòng)運(yùn)行dotnet restoredotnet build。
    運(yùn)行結(jié)果如下:

運(yùn)行輸出

好了,web服務(wù)已經(jīng)啟動(dòng)監(jiān)聽5000端口,我們打開瀏覽器訪問 http://localhost:5000。結(jié)果如下圖: asp.net core的網(wǎng)站已經(jīng)成功跑起來了??!
網(wǎng)站輸出

添加ID4的支持

1. 添加ID4的組件

首先我們需要添加ID4的assembly, 在ID4.Server目錄下運(yùn)行dotnet add package IdentityServer4.AspNetIdentity。因?yàn)?code>IdentityServer4.AspNetIdentity會(huì)引用IdentityServer4,所以我們不需要單獨(dú)在添加它了。

2. 增加oauth2的配置信息

我們現(xiàn)在來為mvc程序添加ID4所需要的配置信息。主要是添加三個(gè)靜態(tài)方法GetIdentityResources來返回支持的Claim種類。GetApiResources來返回支持的webapi資源,GetClients來返回支持的客戶端信息。包括客戶ID,密碼等信息。

    public class Config
    {
        // scopes define the resources in your system
        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
            };
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("api1", "My API")
            };
        }

        // clients want to access resources (aka scopes)
        public static IEnumerable<Client> GetClients()
        {
            // client credentials client
            return new List<Client>
            {
                new Client
                {
                    ClientId = "mvc",
                    ClientName = "MVC Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    RequireConsent = false,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    RedirectUris           = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1"
                    },
                    AllowOfflineAccess = true
                }
            };
        }
    }

運(yùn)行下面的命令,可以直接從github下載上述config.cs
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Config.cs

3. 注冊(cè)ID4的服務(wù)

準(zhǔn)備好了ID4的配置文件后,現(xiàn)在需要來注入ID4的服務(wù)了。在startup.cs文件的ConfigureServices方法中注入IdentityService。

 public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

            // Adds IdentityServer
           services.AddIdentityServer()
                    .AddTemporarySigningCredential()
                    .AddInMemoryIdentityResources(Config.GetIdentityResources())
                    .AddInMemoryApiResources(Config.GetApiResources())
                    .AddInMemoryClients(Config.GetClients())
                    .AddAspNetIdentity<ApplicationUser>(); 
        }

4. 使用ID4的服務(wù)

在注入了ID4的服務(wù)后,我們需要使用ID4的服務(wù)了。在startup.cs文件的Configure方法中使用Identity。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Adds IdentityServer
            app.UseIdentityServer(); 

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

修改完成的Startup.cs文件,可以通過下面的命令直接下載
curl -k -O https://raw.githubusercontent.com/miemengniao/ID4.Learn/step-1/ID4.Server/Startup.cs

5. 重新編譯運(yùn)行

好了,所有的工作都做完了,我們可以運(yùn)行新的網(wǎng)站了,使用下面的命令重新運(yùn)行網(wǎng)站。

dotnet restore
dotnet build
dotnet run

檢查確認(rèn)ID4服務(wù)器已經(jīng)配置好了。

在瀏覽器中訪問http://localhost:5000/.well-known/openid-configuration地址,查看ID4的配置信息,如果返回結(jié)果類似于下圖,那么恭喜,ID4的認(rèn)證服務(wù)器已經(jīng)成功建立!!??

OpenID信息

下一節(jié),我們會(huì)配置一個(gè)MVC客戶端來使用這個(gè)ID4認(rèn)證服務(wù)器

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容