客戶端模式
開始以前請先看下阮一峰大神的OAuth2.0的博客,或者這個系列的前兩篇關于OAuith和openid的介紹煞赢,對這兩個東西有個大概的了解,同時貼出一些參考的博客
授權服務器搭建
第一步安裝identityServer4
Install-Package identityserver4
第二步編寫配置類
我們新建一個叫identityServerContent的webapi的項目
添加一個config類
//config
public class config {
//配置api resource
public static List<ApiResource> GetResources()
{
return new List<ApiResource>
{
new ApiResource('api','My API')
}
}
public static List<Client> GetClients()
{
return new List<Client>()
{
new Client()
{
ClientId="client",
AllowedGrantTypes= GrantTypes.ClientCredentials,//模式:最簡單的模式
ClientSecrets={//私鑰
new Secret("secret".Sha256())
},
AllowedScopes={//可以訪問的Resource
"api"
}
}
}
}
}
第三步注入identityServer4
在Startup.cs中注入ids4
services.AddIdentityServer()
.AddDeveloperSigningCredential()//添加開發(fā)人員簽名憑據
.AddInMemoryApiResources(Config.GetResources())//添加內存apiresource
.AddInMemoryClients(Config.GetClients());//添加內存client
到此我們的授權服務端算是完成了
客戶端集成IdentityServer
安裝包
首先新建一個webapi的項目,同時安裝中間件
dotnet new webapi --name ClientCredentialApi
Install-Package IdentityServer4.AccessTokenValidation
注入Di
services.AddAuthentication("Bearer")//添加授權模式
.AddIdentityServerAuthentication(Options=>{
Options.Authority="http://localhost:5000";//授權服務器地址
Options.RequireHttpsMetadata=false;//是否是https
Options.ApiName="api";
});
同時把所有控制器打上[Authorize]的標記,到此我們客戶端配置已經完成了
使用postman來測試接口
我們分別啟動這兩個項目,5000端口代表授權服務器,5001代表Api服務器
1.使用postman來測試調用
到此我們的客戶端模式編寫完成,下篇我們將開始密碼模式
推薦參考 博客園 曉晨master大佬的identityServer4系列