ASP.NET Core3.1使用Identity Server4創建Authorization Server-1

前言

網上關於Identity Server4的資料有挺多的,以前是一直看楊旭老師的,最近項目中有使用到,在使用.NET Core3.1的時候有一些不一樣。因此在此記錄一下。html

預備知識: http://www.javashuo.com/article/p-tepyssjv-q.htmlgit

本文內容參考程序員

如楊旭老師所說,官方文檔真的很詳細,有時間建議你們看下官方文檔。api

創建Authorization Server

創建ASP.Net Core項目使用空模板。服務器

項目創建以後,運行方式改成使用控制檯運行而不是IIS Express,以便查看各類debug信息。app

這個已成爲習慣,也是學習楊老師的,確實比較方便,固然若是不喜歡能夠不設置,只須要端口號配置的時候對應好就能夠的。asp.net


修改後文件代碼爲:async

{ 
  "profiles": { 
    "IdentityServer4.AuthServer": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

端口號爲5000,此時運行程序,會顯示出Hello World!,默認的,沒有修改。

安裝Identity Server4

點擊安裝就好啦。

配置Identity Server4

API和客戶端

API的配置和以前有所不一樣,以前是ApiResources,如今分爲ApiResourcesApiScopes,後續會說到。

using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic;

namespace IdentityServer4.AuthServer.Configuration
{
    public class InMemoryConfiguration
    {
        /// <summary>
        /// Api Scopes
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiScope> ApiScopes()
        {
            return new List<ApiScope>
            {
                new ApiScope("scope1","scope1")
            };
        }
        /// <summary>
        /// ApiResources
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> ApiResources()
        { 
            return new[]
            {
                new ApiResource
                {
                    Name = "api1",
                    DisplayName = "My Api1",
                    Scopes = { "scope1" }
                } 
            };
        }
        /// <summary>
        /// Clients
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> Clients()
        {
            return new[]
            { 
                new Client
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials, 
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    }, 
                    AllowedScopes = { "scope1" }
                }
            };
        }
        /// <summary>
        /// Users
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<TestUser> Users()
        {
            return new[]
            {
                new TestUser
                {
                    SubjectId = "1",
                    Username = "mail@qq.com",
                    Password = "password"
                }
            };
        }
    }
}

ApiScopes: 這個應該怎麼翻譯我也不清楚,API範圍?若是沒理解錯的話,就是給以前的ApiResources進行了一個分組。受權的時候會驗證Scope

ApiResources:好比官網的第一個demo,可能會有疑問,你怎麼知道我是api1呢?其實,就沒有驗證,只要有受權碼就能夠訪問的。若是說,我只要api1的話,那就用到ApiResources了,生產環境中,也必然是須要用到的。

加載資源和客戶端

修改Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddTestUsers(InMemoryConfiguration.Users().ToList())
        .AddInMemoryClients(InMemoryConfiguration.Clients())
        .AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
        .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
}

固然,也須要app.UseIdentityServer();

首次啓動時,Identity Server4將建立一個開發人員簽名密鑰,該文件名爲tempkey.rsa。沒必要將該文件簽入源代碼管理中,若是不存在該文件將被從新建立。也就是AddDeveloperSigningCredential()。 這個方法只適合用於Identity Server4在單個機器運行, 若是是生產環境你得使用AddSigningCredential()這個方法.

運行一下,發現並無什麼改變,不過打開:http://localhost:5000/.well-known/openid-configuration,則應該看到所謂的發現文檔。發現文檔是身份服務器中的標準端點。客戶端和API將使用發現文檔來下載必要的配置數據。

獲取Token

打開Postman,按照配置的輸入而後試一下

獲取到Token,控制檯輸出以下:

這裏是有用戶的信息的,可是咱們能夠把用戶信息去掉,而後GrantType改成client_credentials,咱們設置的是 ResourceOwnerPasswordAndClientCredentials 這個GrantType,因此使用用戶名密碼以及使用ClientCredentials均可以。

不過此時控制檯會有區別,沒有用戶信息了。

美化美化UI

Identity Server 4 提供了一套QuickStart UI

https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

此存儲庫包含UI所需的控制器,模型,視圖和CSS文件。只需下載/克隆並將其複製到Web項目中便可。

打開項目根目錄,運行Powershell,而後輸入命令:

iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/main/getmain.ps1'))

不過可能你會遇到我前三次那種錯誤,嗯,訪問不了,那就全局或者先下載下來人工粘貼過去吧~

好了之後咱們的項目是醬紫的:

因爲有wwwroot下不少靜態文件, 因此asp.net core 須要啓用服務靜態文件的功能: 修改Startup的Configure方法

先看修改前的樣子吧

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }

修改後

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                   name: "default",
                   pattern: "{controller=Home}/{action=Index}/{id?}"
               );
            });
        }

是否是拋異常了?

由於咱們如今有UI了,因此不要忘記在ConfigureServices裏面註冊MVC。

public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddControllersWithViews();

            services.AddIdentityServer()
              .AddDeveloperSigningCredential()
              .AddTestUsers(InMemoryConfiguration.Users().ToList())
              .AddInMemoryClients(InMemoryConfiguration.Clients())
              .AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
              .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
        }

而後運行一下試試:

登陸一下~

好了,如今咱們已經能夠登陸成功了。

登陸界面能夠自定義的~,OK,今天就到這裏

計劃

接下來會說一下

  • 創建咱們的API項目並使用Token測試接口
  • 創建一個MVC客戶端項目訪問咱們的API
  • 創建一個JS(Vue)客戶端訪問咱們的API項目

End

推廣下本身的公衆號一個逗逼的程序員,主要記錄本身工做中解決問題的思路分享及學習過程當中的筆記。絕對不會程序員販賣程序員的焦慮來割韭菜

相關文章
相關標籤/搜索