IdentityServer4在Asp.Net Core中的應用(二)

    繼續上次受權的內容,客戶端模式後咱們再說如下密碼模式,先回顧下密碼模式的流程:數據庫

咱們仍是使用上次的代碼,在那基礎上修改,在IdentityServer4裏面有一個IdentityServer4.Test的引用,它裏面包含了測試用戶的類,咱們先將這個引用添加進來,並配置咱們的用戶信息,修改Config類,添加一個GetTestUsers()方法,固然在實際項目中,咱們須要去從咱們的數據庫中去讀取用戶名及密碼等信息,這裏只作測試,添加內容以下:api

咱們再添加一個客戶端,更改其受權模式爲密碼模式,內容以下:服務器

修改其受權模式爲ResourceOwnerPassword,下面再將咱們的用戶依賴注入到系統中,學習

至此咱們的受權服務器已經修改完成,咱們經過Postman測試是否能夠拿到咱們的access_token測試

OK,測試成功。咱們的Api是不須要改動的,下面咱們再新建立一個第三方應用程序,去請求受權並獲取資源,代碼以下spa

using System;
using System.Net.Http;
using IdentityModel;
using IdentityModel.Client;

namespace ThirdPartyAppByPwd
{
    class Program
    {
        static void Main(string[] args)
        {
            //請求受權服務器
            var diso=DiscoveryClient.GetAsync("http://localhost:5000").Result;
            if(diso.IsError)
            {
                Console.WriteLine(diso.Error);
            }

            //受權服務器根據客戶端發來的請求返回令牌
            var tokenClient=new TokenClient(diso.TokenEndpoint,"pwdClient","pwdSecrect");
            //使用密碼模式
            var tokenResponse =tokenClient.RequestResourceOwnerPasswordAsync("allen","123456","api").Result;
            if(tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
            }
            //若是成功,則打印輸出返回的令牌信息
            else
            {
                Console.WriteLine(tokenResponse.Json);
            }

            //建立HttpClient對象
            var httpClient=new HttpClient();

            //設置Authorization的Value值
            httpClient.SetBearerToken(tokenResponse.AccessToken);

            //根據受權服務器返回的令牌信息請求Api資源
            var response= httpClient.GetAsync("http://localhost:5001/api/values").Result;

            //若是返回結果爲成功,輸出Api資源的結果
            if(response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            }
        }
    }
}

只改動了兩個地方,把ClientID和ClientSecret的值修改了,以及請求受權服務器的方法改成: 對象

RequestResourceOwnerPasswordAsync(username,password,scope),運行結果以下:blog

以上就是完整的密碼模式的受權,下面是對以上的簡化流程:token

掃描二維碼關注個人公衆號,共同窗習,共同進步!資源

相關文章
相關標籤/搜索