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