Identity Server 4資源擁有者密碼認證控制訪問API

基於上一篇文章中的代碼進行繼續延伸,只需要小小的改動即可,不明白的地方可以先看看本人上一篇文章及源碼 Identity Server 4客戶端認證控制訪問API

 

 

一、QuickStartIdentityServer4項目中Config.cs增加如下配置

// 定義客戶端認證方式
        public static IEnumerable<Client> Clients => new[]
        {
            // 客戶端認證
            new Client
            {
                ClientId="sample_client", // 客戶端id
                ClientSecrets =
                {
                    new Secret("sample_client_secret".Sha256()) // 客戶端祕鑰

                },
                AllowedGrantTypes=GrantTypes.ClientCredentials, // 授權類型爲客戶端
                AllowedScopes={ "sample_api" } // 設置該客戶端允許訪問的api範圍
            },
            // 資源擁有者認證
            new Client
            {
                ClientId="sample_pass_client", // 客戶端id
                ClientSecrets =
                {
                    new Secret("sample_client_secret".Sha256()) // 客戶端祕鑰

                },
                AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, // 授權類型爲資源擁有者
                AllowedScopes={ "sample_api" } // 設置該客戶端允許訪問的api範圍
            }
        };

 

 二、Client項目中增加模擬請求資源擁有者認證,其他代碼不變

// 資源擁有者認證
            var tokenResponse = await client.RequestPasswordTokenAsync(
                    new PasswordTokenRequest
                    {
                        Address = disco.TokenEndpoint,
                        ClientId = "sample_pass_client",
                        ClientSecret = "sample_client_secret",
                        UserName="admin",
                        Password="123"
                    }
                );

 

 三、項目測試

1、’postman模擬請求 http://localhost:5001/connect/token 獲取token

 

 2、使用token請求api

 

 3、Client項目模擬客戶端請求

 

學習鏈接:https://www.cnblogs.com/stulzq/p/7509648.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章