IdentityServer(12)- 使用 ASP.NET Core Identity


IdentityServer具有非常好的擴展性,其中用戶及其數據(包括密碼)部分你可以使用任何想要的數據庫進行持久化。 如果需要一個新的用戶數據庫,那么ASP.NET Core Identity是你的一個選擇。 本快速入門介紹了如何將ASP.NET Core Identity 和 IdentityServer4一起使用。

在閱讀這篇文章是,希望你能把前面的文章全部看一遍,了解基本使用和相關的理論。 這個快速入門使用ASP.NET Core Identity的方法是從Visual Studio中的ASP.NET Core Identity模板創建一個新項目。 這個新的項目將取代之前在之前的快速入門中從頭開始構建的IdentityServer項目。 此解決方案中的所有其他項目(對於客戶端和API)將保持不變。

建立ASP.NET Identity新項目

第一步是為您的解決方案添加一個ASP.NET Core Identity的新項目。 鑒於ASP.NET Core Identity需要大量代碼,因此使用Visual Studio中的模板是最好的。 你最終將刪除IdentityServer的舊項目,但有幾個項目需要遷移(或按照之前的快速入門所述從頭開始重新編寫)。

創建一個ASP.NET Core Web應用程序

然后選擇Web應用程序(MVC)

然后點擊“更改身份驗證”按鈕,選擇“個人用戶賬戶”

最后,你的設置應該是和下圖一樣:

修改hosting

不要忘記修改hosting以在端口5000上運行。這非常重要,這將關系到繼續使用現有的客戶端和API項目。

添加IdentityServer組件

添加IdentityServer4.AspNetIdentity NuGet包。

Scopes 和 Clients 配置

盡管這是IdentityServer的一個新項目,但我們仍然需要與之前的快速入門一樣的配置Scopes 和 Clients。 將之前快速入門的配置類(在Config.cs中)復制到此新項目中。

對於現在的配置需要改變的是禁用MVC客戶端的許可。 我們還沒有復制之前的IdentityServer項目的許可代碼,所以現在對MVC客戶端進行一次修改,並設置RequireConsent = false

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
}

配置IdentityServer

和以前一樣,IdentityServer需要在Startup.cs的ConfigureServices和Configure中進行配置。

ConfigureServices

以前我們使用AddTestUsers擴展方法用於注冊用戶,但在這種現在的解決方案下,我們用AddAspNetIdentity替換該擴展方法來使用ASP.NET Identity用戶。AddAspNetIdentity擴展方法需要一個通用參數,它是你的ASP.NET Ientity用戶類型(與模板中的AddIdentity方法一樣)

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

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

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

    services.AddMvc();

    // configure identity server with in-memory stores, keys, clients and scopes
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddInMemoryPersistedGrants()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients())
        .AddAspNetIdentity<ApplicationUser>();
}

我們在將Asp.Net Identity添加到DI容器中時,一定要把注冊IdentityServer放在Asp.Net Identity之后,因為注冊IdentityServer會覆蓋Asp.Net Identity的一些配置,這個非常重要。

Configure

使用UseIdentityServer代替了對UseIdentity的調用

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    // app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
    app.UseIdentityServer();

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

創建用戶數據庫

鑒於這是一個新的ASP.NET Identity項目,您將需要創建數據庫。 您可以通過從項目目錄運行命令提示符並運行dotnet ef database update -c ApplicationDbContext來完成此操作:

在VS程序包控制台使用命令也是一樣的Update-Database

創建用戶

此時,您應該能夠運行項目並在數據庫中創建/注冊用戶。 啟動應用程序,並從主頁點擊“Register”鏈接:

並在注冊頁面上創建一個新的用戶帳戶:

現在你有一個用戶帳戶,你應該可以登錄,使用客戶端,並調用API。

在MVC客戶端登錄

啟動MVC客戶端應用程序,你應該能夠點擊“Secure”鏈接登錄。

您應該被重定向到ASP.NET Identity登錄頁面。 用新創建的用戶登錄:

登錄后,您應該跳過同意頁面(給出我們上面所做的更改),並立即重定向到MVC客戶端應用程序,會顯示你的用戶信息。

您還應該能夠單擊“Call API using application identity”來調用API:

現在,您已經從ASP.NET Ientity的用戶登錄。

本文代碼:https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Quickstarts/8_AspNetIdentity
原文:https://identityserver4.readthedocs.io/en/latest/quickstarts/8_aspnet_identity.html

額外,同時使用ASP.NET Identity和EF的示例請看:https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Quickstarts/Combined_AspId_and_EFStorage


免責聲明!

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



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