IdentityServer4 -OAuth Password模式

1.1 認證授權中心代碼

在內(nèi)部系統(tǒng)調(diào)用,或者高信任客戶端調(diào)用可以采用。

使用之前的IdentityServer4 -ClientCredential模式代碼,在IdentityServer.ServerCenter項目中,修改IdentityConfig.cs配置,新增客戶端配置,加入測試用戶代碼如下:

 public class IdentityConfig
    {
        /// <summary>
        ///   ApiResource 
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ApiResource> GetResource()
        {
            return new List<ApiResource>() {
            new ApiResource("UserAPI","OrderAPI"){
            } };
        }
        /// <summary>
        /// Client
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<Client> GetClients()
        {
            var clientApp = new Client()
            {
                ClientId = "App1",
                ClientName = "App",
                AllowedGrantTypes = new List<string>() {
                    GrantType.ClientCredentials },
                ClientSecrets = new List<Secret>() {
                    new Secret("Secret".Sha256())

                },
                AllowedScopes = { "UserAPI"}
            };
            var clientWebMVC = new Client()
            {
                ClientId = "WebMVC1",
                ClientName = "WebMVC1"
               ,
                AllowedGrantTypes = new List<string>(){
                   GrantType.ResourceOwnerPassword
                },
                ClientSecrets = new List<Secret>() {
                    new Secret("WebMVCSecret".Sha256())

            }
            };
            return new List<Client>() {
                    clientApp,clientWebMVC
            };
        }
        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser>()
            {
                new TestUser(){
                    Username="WebMVC_Main",
                    Password="WeMVC_Pwd",
                    SubjectId="1001"
                }
            };
        }
    }

修改Startup.cs文件,使用內(nèi)存中的測試用戶

 public void ConfigureServices(IServiceCollection services)
       {

           services.AddIdentityServer()//添加服務 
               .AddDeveloperSigningCredential()
               .AddInMemoryApiResources(IdentityConfig.GetResource())//Api 資源
               .AddInMemoryClients(IdentityConfig.GetClients())//Api的客戶端
               .AddTestUsers(IdentityConfig.GetTestUsers());//添加測試用戶
           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        
       }

啟動IdentityServer.ServerCenter項目,使用PostMan來模擬獲取Token。
報文信息參考如下:

POST /connect/token HTTP/1.1
Host: localhost:4000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 63b8ec74-9901-8721-391c-3c8b9f4076df

client_id=WebMVC1&client_secret=WebMVCSecret&grant_type=password&username=WebMVC_Main&password=WeMVC_Pwd&=

返回信息如下:

{
"access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImUyM2FkOWMxZmQwZjJjMDU2YTVlN2I3MzU1OWU5MDY1IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NDQ1MDkyNTAsImV4cCI6MTU0NDUxMjg1MCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo0MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC9yZXNvdXJjZXMiLCJVc2VyQVBJIl0sImNsaWVudF9pZCI6IldlYk1WQzEiLCJzdWIiOiIxMDAxIiwiYXV0aF90aW1lIjoxNTQ0NTA5MjUwLCJpZHAiOiJsb2NhbCIsInNjb3BlIjpbIlVzZXJBUEkiXSwiYW1yIjpbInB3ZCJdfQ.NJPDnBvALBH0fbulqpXmviu1M_FT72fnV6GLaL62lvl6mjksaIshaQj-iher1MthCejnjrV_Se9S4vNaSaolDv1wuv5la1Ex3S9_U9D_2sAq4huvjm6SiEexD-rrr9Q1T0kqceJ-AL7dE0wTcwxSBOSBRSSG6soJuKiPsPzIUJJGgsRkj_kmYmuLse2YetAWSRBUl9KNDaiJ55pSH7wQcE3Vp1hxPI6HwBjCQlUSFACFrzcBPEWpCBI4YugYLhYCfWSO98-KJxkrc-hu7dyqakIP3mo2YCGzYJX6qs5UpA1jL0cCbPS0otDo2zYBuQJJoNfzpTdaBXi3Uo_bOeh-2A",
"expires_in": 3600,
"token_type": "Bearer"
}

1.2 第三方Client 調(diào)用代碼

代碼如下:

using System;
using System.Net.Http;
using IdentityModel;
using IdentityModel.Client;
namespace IdentityServer.UseCmd
{
   class Program
   {
       static void Main(string[] args)
       {
               //1.1 授權服務發(fā)現(xiàn)
            var disco=DiscoveryClient.GetAsync("http://localhost:4000").Result;
           if (disco.IsError)
           {
               Console.WriteLine(disco.Error);
               Console.ReadLine();
               return;
           }
           //1.2 獲取token  
           #region ClientCredential
           //var tokenClient = new TokenClient
           //        (
           //        //授權 獲取token 節(jié)點
           //        disco.TokenEndpoint,
           //        //ClientId
           //        "App1",
           //        //ClientSecret
           //        "Secret");
           //var tokenResponse = tokenClient.RequestClientCredentialsAsync().Result;
           //if (tokenResponse.IsError)
           //{
           //    Console.WriteLine(tokenResponse.Error);
           //    return;
           //} 
           #endregion

           var tokenClient = new TokenClient
                (
                //授權 獲取token 節(jié)點
                disco.TokenEndpoint,
                //ClientId
                "WebMVC1",
                //ClientSecret
                "WebMVCSecret");
           var tokenResponse = tokenClient.RequestResourceOwnerPasswordAsync(
               //測試用戶名
               "WebMVC_Main",
               //測試用戶面膜
               "WeMVC_Pwd")
               .Result;
           if (tokenResponse.IsError)
           {
               Console.WriteLine(tokenResponse.Error);
               return;
           }
           Console.WriteLine(tokenResponse.Json);
           //1.3 調(diào)用API
           HttpClient c = new HttpClient();
           //設置授權信息
           c.SetBearerToken(tokenResponse.AccessToken);
           var jsonRe = c.GetAsync("http://localhost:4001/api/values").Result;
           Console.WriteLine(jsonRe.Content.ReadAsStringAsync().Result);
           Console.ReadLine();
       }
   }
}

參考文檔:https://identityserver4.readthedocs.io/en/latest/quickstarts/2_resource_owner_passwords.html

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

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

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • feisky云計算、虛擬化與Linux技術筆記posts - 1014, comments - 298, trac...
    不排版閱讀 4,354評論 0 5
  • 文/逗逗 圖/逗逗 心靈上得到及時休憩與調(diào)整,會讓你更加充滿能量。 沒有時間休息的人,總要騰出時間來生病,所以,難...
    遇見逗逗閱讀 1,174評論 0 0
  • 思念是一個日記本 我把它放在枕頭下 半夜醒來總會不經(jīng)意的找到它 在不開燈的房間 光線太暗,沒法看清你 夢境里你不約...
    xyhk閱讀 359評論 4 3
  • 影視新星復賽篇 下午五點左右,“美的杯”第二屆影視新星大賽(佛岡賽區(qū))的復賽終于降下了帷幕。臺上共有六十名打扮得花...
    冷珩湄閱讀 104評論 0 0

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