一、前言
從上一篇關於客戶端憑證模式中,我們通過創建一個認證授權訪問服務,定義一個API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,並使用它來控制訪問API。其中,我們也注意到了在4.x版本中於之前3.x版本之間存在的差異。
所以在這一篇中,我們將通過多種授權模式中的資源所有者密碼憑證授權模式進行說明,主要針對介紹IdentityServer保護API的資源,資源密碼憑證授權訪問API資源。

二、初識
如果你高度信任某個應用Client,也允許用戶把用戶名和密碼,直接告訴該應用Client。該應用Client就使用你的密碼,申請令牌,這種方式稱為"密碼式"(password)。
這種模式適用於鑒權服務器與資源服務器是高度相互信任的,例如兩個服務都是同個團隊或者同一公司開發的。
2.1 適用范圍
資源所有者密碼憑證授權模式,適用於當資源所有者與客戶端具有良好信任關系的場景,比如客戶端是設備的操作系統或具備高權限的應用。授權服務器在開放此種授權模式時必須格外小心,並且只有在別的模式不可用時才允許這種模式。
這種模式下,應用client可能存了用戶密碼這不安全性問題,所以才需要高可信的應用。
主要適用於用來做遺留項目升級為oauth2的適配授權使用,當然如果client是自家的應用,也是可以的,同時支持refresh token。
例如,A站點 需要添加了 OAuth 2.0 作為對其現有基礎架構的一個授權機制。對於現有的客戶端轉變為這種授權方案,資源所有者密碼憑據授權將是最方便的,因為他們只需使用現有的帳戶詳細信息(比如用戶名和密碼)來獲取訪問令牌。
2.2 密碼授權流程:
+----------+
| Resource |
| Owner |
| |
+----------+
v
| Resource Owner
(A) Password Credentials
|
v
+---------+ +---------------+
| |>--(B)---- Resource Owner ------->| |
| | Password Credentials | Authorization |
| Client | | Server |
| |<--(C)---- Access Token ---------<| |
| | (w/ Optional Refresh Token) | |
+---------+ +---------------+
資源所有者密碼憑證授權流程描述
(A)資源所有者向客戶端提供其用戶名和密碼。
(B)客戶端從授權中請求訪問令牌服務器的令牌端點,以獲取訪問令牌。當發起該請求時,授權服務器需要認證客戶端的身份。
(C) 授權服務器驗證客戶端身份,同時也驗證資源所有者的憑據,如果都通過,則簽發訪問令牌。
2.2.1 過程詳解
訪問令牌請求
參數 | 是否必須 | 含義 |
---|---|---|
grant_type | 必需 | 授權類型,值固定為“password”。 |
username | 必需 | 用戶名 |
password | 必需 | 密碼 |
scope | 可選 | 表示授權范圍。 |
同時將允許其他請求參數client_id和client_secret,或在HTTP Basic auth標頭中接受客戶端ID和密鑰。
驗證用戶名密碼
示例:
客戶端身份驗證兩種方式
1、Authorization: Bearer base64(resourcesServer:123)
2、client_id(客戶端標識),client_secret(客戶端秘鑰),username(用戶名),password(密碼)。
(用戶的操作:輸入賬號和密碼)
A 網站要求用戶提供 B 網站的用戶名和密碼。拿到以后,A 就直接向 B 請求令牌。
POST /oauth/token HTTP/1.1
Host: authorization-server.com
grant_type=password
&username=user@example.com
&password=1234luggage
&client_id=xxxxxxxxxx
&client_secret=xxxxxxxxxx
上面URL中,grant_type參數是授權方式,這里的password是“密碼式”,username和password是B的用戶名和密碼。
2.2.2 訪問令牌響應
第二步,B 網站驗證身份通過后,直接給出令牌。注意,這時不需要跳轉,而是把令牌放在 JSON 數據里面,作為 HTTP 回應,A 因此拿到令牌。
響應給用戶令牌信息(access_token),如下所示
{
"access_token": "訪問令牌",
"token_type": "Bearer",
"expires_in": 4200,
"scope": "server",
"refresh_token": "刷新令牌"
}
用戶使用這個令牌訪問資源服務器,當令牌失效時使用刷新令牌去換取新的令牌。
這種方式需要用戶給出自己的用戶名/密碼,顯然風險很大,因此只適用於其他授權方式都無法采用的情況,而且必須是用戶高度信任的應用。
三、實踐
在示例實踐中,我們將創建一個授權訪問服務,定義一個API和要訪問它的客戶端,客戶端通過IdentityServer上請求訪問令牌,並使用它來訪問API。
3.1 搭建 Authorization Server 服務
搭建認證授權服務
3.1.1 安裝Nuget包
IdentityServer4
程序包
3.1.2 配置內容
建立配置內容文件Config.cs
public static class Config
{
public static IEnumerable<IdentityResource> IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable<ApiScope> ApiScopes =>
new ApiScope[]
{
new ApiScope("password_scope1")
};
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("api1","api1")
{
Scopes={ "password_scope1" },
ApiSecrets={new Secret("apipwd".Sha256())} //api密鑰
}
};
public static IEnumerable<Client> Clients =>
new Client[]
{
new Client
{
ClientId = "password_client",
ClientName = "Resource Owner Password",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = { new Secret("511536EF-F270-4058-80CA-1C89C192F69A".Sha256()) },
AllowedScopes = { "password_scope1" }
},
};
}
因為是資源所有者密碼憑證授權的方式,所以我們通過代碼的方式來創建幾個測試用戶。
新建測試用戶文件TestUsers.cs
public class TestUsers
{
public static List<TestUser> Users
{
get
{
var address = new
{
street_address = "One Hacker Way",
locality = "Heidelberg",
postal_code = 69118,
country = "Germany"
};
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "i3yuan",
Password = "123456",
Claims =
{
new Claim(JwtClaimTypes.Name, "i3yuan Smith"),
new Claim(JwtClaimTypes.GivenName, "i3yuan"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "i3yuan@email.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),
new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json)
}
}
};
}
}
}
返回一個TestUser的集合。
通過以上添加好配置和測試用戶后,我們需要將用戶注冊到IdentityServer4服務中,接下來繼續介紹。
3.1.3 注冊服務
在startup.cs中ConfigureServices方法添加如下代碼:
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddTestUsers(TestUsers.Users); //添加測試用戶
// in-memory, code config
builder.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddInMemoryApiScopes(Config.ApiScopes);
builder.AddInMemoryApiResources(Config.ApiResources);
builder.AddInMemoryClients(Config.Clients);
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
}
3.1.4 配置管道
在startup.cs中Configure方法添加如下代碼:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
以上內容是快速搭建簡易IdentityServer項目服務的方式。
這搭建 Authorization Server 服務跟上一篇客戶端憑證模式有何不同之處呢?
- 在Config中配置客戶端(client)中定義了一個
AllowedGrantTypes
的屬性,這個屬性決定了Client可以被哪種模式被訪問,GrantTypes.ClientCredentials為客戶端憑證模式,GrantTypes.ResourceOwnerPassword為資源所有者密碼憑證授權。所以在本文中我們需要添加一個Client用於支持資源所有者密碼憑證模式(ResourceOwnerPassword)。- 因為資源所有者密碼憑證模式需要用到用戶名和密碼所以要添加用戶,而客戶端憑證模式不需要,這也是兩者的不同之處。
3.2 搭建API資源
實現對API資源進行保護
3.2.1 快速搭建一個API項目
3.2.2 安裝Nuget包
IdentityServer4.AccessTokenValidation 包
3.2.3 注冊服務
在startup.cs中ConfigureServices方法添加如下代碼:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthorization();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5001";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
options.ApiSecret = "apipwd"; //對應ApiResources中的密鑰
});
}
AddAuthentication把Bearer配置成默認模式,將身份認證服務添加到DI中。
AddIdentityServerAuthentication把IdentityServer的access token添加到DI中,供身份認證服務使用。
3.2.4 配置管道
在startup.cs中Configure方法添加如下代碼:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
UseAuthentication將身份驗證中間件添加到管道中;
UseAuthorization 將啟動授權中間件添加到管道中,以便在每次調用主機時執行身份驗證授權功能。
3.2.5 添加API資源接口
[Route("api/[Controller]")]
[ApiController]
public class IdentityController:ControllerBase
{
[HttpGet("getUserClaims")]
[Authorize]
public IActionResult GetUserClaims()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
在IdentityController 控制器中添加 [Authorize] , 在進行請求資源的時候,需進行認證授權通過后,才能進行訪問。
這搭建API資源跟上一篇客戶端憑證模式有何不同之處呢?
我們可以發現這跟上一篇基本相似,但是可能需要注意的地方應該是
ApiName
和ApiSecret
,要跟你配置的API資源名稱和API資源密鑰相同。
3.3 搭建Client客戶端
實現對API資源的訪問和獲取資源
3.3.1 搭建一個窗體程序
3.3.2 安裝Nuget包
IdentityModel 包
3.3.3 獲取令牌
客戶端與授權服務器進行身份驗證並向令牌端點請求訪問令牌。授權服務器對客戶端進行身份驗證,如果有效,頒發訪問令牌。
IdentityModel 包括用於發現 IdentityServer 各個終結點(EndPoint)的客戶端庫。
我們可以使用從 IdentityServer 元數據獲取到的Token終結點請求令牌:
private void getToken_Click(object sender, EventArgs e)
{
var client = new HttpClient();
var disco = client.GetDiscoveryDocumentAsync(this.txtIdentityServer.Text).Result;
if (disco.IsError)
{
this.tokenList.Text = disco.Error;
return;
}
//請求token
tokenResponse = client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId =this.txtClientId.Text,
ClientSecret = this.txtClientSecret.Text,
Scope = this.txtApiScopes.Text,
UserName=this.txtUserName.Text,
Password=this.txtPassword.Text
}).Result;
if (tokenResponse.IsError)
{
this.tokenList.Text = disco.Error;
return;
}
this.tokenList.Text = JsonConvert.SerializeObject(tokenResponse.Json);
this.txtToken.Text = tokenResponse.AccessToken;
}
3.3.4 調用API
要將Token發送到API,通常使用HTTP Authorization標頭。 這是使用
SetBearerToken
擴展方法完成。
private void getApi_Click(object sender, EventArgs e)
{
//調用認證api
if (string.IsNullOrEmpty(txtToken.Text))
{
MessageBox.Show("token值不能為空");
return;
}
var apiClient = new HttpClient();
//apiClient.SetBearerToken(tokenResponse.AccessToken);
apiClient.SetBearerToken(this.txtToken.Text);
var response = apiClient.GetAsync(this.txtApi.Text).Result;
if (!response.IsSuccessStatusCode)
{
this.resourceList.Text = response.StatusCode.ToString();
}
else
{
this.resourceList.Text = response.Content.ReadAsStringAsync().Result;
}
}
這搭建Client客戶端跟上一篇客戶端憑證模式有何不同之處呢?
- 客戶端請求token多了兩個參數,一個用戶名,一個密碼
- 請求Token中使用
IdentityModel
包的方法RequestPasswordTokenAsync
,實現用戶密碼方式獲取令牌。
以上展示的代碼有不明白的,可以看本篇項目源碼,項目地址為 :資源所有者密碼憑證模式
3.4 效果
3.4.1 項目測試
3.4.2 postman測試
四、拓展
從上一篇的客戶端憑證模式到這一篇的資源所有者資源密碼憑證模式,我們都已經初步掌握了大致的授權流程,以及項目搭建獲取訪問受保護的資源,但是我們也可能發現了,如果是僅僅為了訪問保護的API資源的話,加不加用戶和密碼好像也沒什么區別呢。
但是如果仔細對比兩種模式在獲取token,以及訪問api返回的數據可以發現,資源所有者密碼憑證模式返回的Claim的數量信息要多一些,但是客戶端模式返回的明顯少了一些,這是因為客戶端不涉及用戶信息。所以資源密碼憑證模式
可以根據用戶信息做具體的資源權限判斷。
比如,在TestUser有一個Claims屬性,允許自已添加Claim,有一個ClaimTypes枚舉列出了可以直接添加的Claim。所以我們可以為用戶設置角色,來判斷角色的權限功能,做簡單的權限管理。
4.1 添加用戶角色
在之前創建的TestUsers.cs
文件的User
方法中,添加Cliam的角色熟悉,如下:
public class TestUsers
{
public static List<TestUser> Users
{
get
{
var address = new
{
street_address = "One Hacker Way",
locality = "Heidelberg",
postal_code = 69118,
country = "Germany"
};
return new List<TestUser>
{
new TestUser
{
SubjectId = "1",
Username = "i3yuan",
Password = "123456",
Claims =
{
new Claim(JwtClaimTypes.Name, "i3yuan Smith"),
new Claim(JwtClaimTypes.GivenName, "i3yuan"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "i3yuan@email.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://i3yuan.top"),
new Claim(JwtClaimTypes.Address, JsonSerializer.Serialize(address), IdentityServerConstants.ClaimValueTypes.Json),
new Claim(JwtClaimTypes.Role,"admin") //添加角色
},
}
};
}
}
}
4.2 配置API資源需要的Cliam
因為要用到ApiResources
,ApiResources
的構造函數有一個重載支持傳進一個Claim集合,用於允許該Api資源可以攜帶那些Claim, 所以在項目下的Config
類的ApiResources
做出如下修改:
public static IEnumerable<ApiResource> ApiResources =>
new ApiResource[]
{
new ApiResource("api1","api1")
{
Scopes={ "password_scope1" },
UserClaims={JwtClaimTypes.Role}, //添加Cliam 角色類型
ApiSecrets={new Secret("apipwd".Sha256())}
}
};
4.3 添加支持Role驗證
在API資源項目中,修改下被保護Api的,使其支持Role驗證。
[HttpGet("getUserClaims")]
//[Authorize]
[Authorize(Roles ="admin")]
public IActionResult GetUserClaims()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
4.4 效果
可以看到,為我們添加了一個Role Claim,效果如下:
五、總結
- 本篇主要闡述以資源所有者密碼憑證授權,編寫一個客戶端,以及受保護的資源,並通過客戶端請求IdentityServer上請求獲取訪問令牌,從而獲取受保護的資源。
- 這種模式主要使用client_id和client_secret以及用戶名密碼通過應用Client(客戶端)直接獲取秘鑰,但是存在client可能存了用戶密碼這不安全性問題,如果client是自家高可信的應用,也是可以使用的,同時如果遺留項目升級為oauth2的授權機制也是適配適用的。
- 在后續會對其中的其他授權模式,數據庫持久化問題,以及如何應用在API資源服務器中和配置在客戶端中,會進一步說明。
- 如果有不對的或不理解的地方,希望大家可以多多指正,提出問題,一起討論,不斷學習,共同進步。
- 項目地址