目的:創建IdentityServer 並通過PostMan驗證獲取token
第一次配置如下
public class Config
{
public static IEnumerable<ApiResource> GetResource()
{
return new List<ApiResource>
{ new ApiResource("api","My Api") };
}
public static IEnumerable<Client> GetClients()
{
return new List<Client> { new Client()
{
ClientId="client",
AllowedGrantTypes=GrantTypes.ClientCredentials,
ClientSecrets={ new Secret("secret".Sha256())},
AllowedScopes={"api"}
} };
}
}
PostMan的請求如圖
結果顯示 請求無效 參照教程 >https://www.cnblogs.com/monster17/p/13261647.html 得知是因為傳參格式的問題
- 1.我們將Body改為
格式
- 2.加參數<AllowedScopes: api> 【指定的api為配置Config中apiresource的名稱】 再次請求
如圖
結果又顯示scope無效 【這里懵逼了很久 明明Config中apiResource的name 和client中AllowedScopes的接口是一致的】
但是參照報錯 一定是scop的問題 於是去找了一下官方文檔關於API Resources 的使用
參照原文
這里也便可以理解 問題所在了。 apiResource並不等同於scope 它相當於是scopes集合的統稱 實現了scope的分組【但具體的scope還是要進行設置的 我們先前的Config 缺少具體scope =。= 真是令人頭大】
先參照例子理解一下
//創建多個scope
{
return new List<ApiScope>
{
// invoice API specific scopes
new ApiScope(name: "invoice.read", displayName: "Reads your invoices."),
new ApiScope(name: "invoice.pay", displayName: "Pays your invoices."),
// customer API specific scopes
new ApiScope(name: "customer.read", displayName: "Reads you customers information."),
new ApiScope(name: "customer.contact", displayName: "Allows contacting one of your customers."),
// shared scope
new ApiScope(name: "manage", displayName: "Provides administrative access to invoice and customer data.")
};
}
//調取時 將多個scope的Name加參時 可能會很長很長 為了方便 我們將scope 進行分組 后期可直接調用**統稱** 這里分成兩組
public static readonly IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("invoice", "Invoice API")//設置每組scopes的統稱
{
Scopes = { "invoice.read", "invoice.pay", "manage" }//設置每組scope具體名稱
},
new ApiResource("customer", "Customer API")
{
Scopes = { "customer.read", "customer.contact", "manage" }
}
};
}
再來回頭看看我們的Config 修改如下
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>() {
new ApiResource("api", "My api") { Scopes={"api1","api2"} //將具體的scopes 歸為一組 統稱為api
} };
}
//創建具體的scope
public static IEnumerable<ApiScope> GetApiScopes()
{
return new List<ApiScope> {
new ApiScope("api1","My first api"),
new ApiScope("api2","My second api")};
}
public static IEnumerable<Client> GetClients()
{
return new List<Client>() { new Client {
ClientId="client",
AllowedGrantTypes=GrantTypes.ClientCredentials,
ClientSecrets={new Secret("secret".Sha256()) },
AllowedScopes={ "api1","api2"}//此處一定要配置具體的scope名稱 外部調用可直接配置為 api【統稱】
} };
}
用PostMan驗證一下
成功了 emmmm 又是美好的一天【還是要多讀源文檔e =.=】
補充 獲取Refresh_token
GetClients配置修改如下
結果