一、客戶端模式介紹
客戶端模式(Client Credentials Grant)是指客戶端直接向認證服務(Authorization Server)發送認證請求,獲取token,進行認證,一般適用於受信任的客戶端。

請求步驟為:
- 客戶端向認證服務器進行認證,並請求一個訪問令牌
token;- 認證服務器進行認證,通過之后,返回客戶端一個訪問令牌。
二、創建認證服務
- 創建一個認證服務
IdentityServerCenter,通過NuGet安裝IdentityServer4;- 添加配置資源與客戶端的文件,引入
using IdentityServer4.Models
public class Config
{
public static IEnumerable<ApiResource> GetResources()
{
return new List<ApiResource> {
new ApiResource {
Name = "ImageResource",
Scopes={ new Scope ("ImageResource")},//Scopes必須配置,否則獲取token時返回 invalid_scope
},
new ApiResource { Name = "FileResourse" },
new ApiResource { Name="Api", Scopes={new Scope ("Api") } }
};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client> {
new Client {
ClientId = "ClientId",
AllowedGrantTypes =GrantTypes.ClientCredentials,//授權模式:客戶端模式
AllowedScopes={ "ImageResource","Api" }, //允許訪問的資源 GetResources()中配置的
ClientSecrets={ new Secret { Value= "ClientSecret".Sha256(), Expiration=DateTime.Now.AddMinutes(5)} }
} };
}
}
- 注入
IdentityServer4,添加IdentityServer4配置
public void ConfigureServices(IServiceCollection services)
{
//注入IdentityServer 添加IdentityServer4配置
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetResources()) //添加配置的資源ApiResource
.AddInMemoryClients(Config.GetClients());//添加配置的客戶端Client
// services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
- 使用
IdentityServer4
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//使用IdentityServer
app.UseIdentityServer();
}
- 啟動項
由於未使用MVC,訪問該api返回404。IdentityServer4提供一個地址可獲取相關配置項。
http://examplehostname.com.well-known/openid-configuration/
訪問 http://localhost:5000/.well-known/openid-configuration 將返回的信息序列化如下

scopes_supported": ["ImageResource", "Api", "offline_access"]即為Config中配置的訪問的資源AllowedScopes。
- 使用
postman獲取token
grant_type為客戶端授權client_credentials,client_id與Client_Secret為Config中配置的ClientId與Secret。接下來創建一個可訪問的資源。
三、創建資源服務
- 創建一個資源服務項目
ImageResourceApi- 注入認證
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(config => {
config.DefaultScheme = "Bearer";
}).AddIdentityServerAuthentication(option=> {
option.ApiName = "ImageResource";
option.Authority = "http://localhost:5000"; //認證服務的url
option.ApiSecret = "ClientSecret".ToSha256();// 訪問的secret
option.RequireHttpsMetadata = false;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
//使用認證
app.UseAuthentication();
app.UseMvc();
}
- 啟動資源服務,返回401未授權;
- 使用
postman帶着token請求資源服務ImageResourceApi,請求成功。



