IdnentiyServer使用客戶端憑據(jù)訪問API的實(shí)例代碼
情景如下:一個(gè)客戶端要訪問一個(gè)api,不需要用戶登錄,但是又不想直接暴露api給外部使用,這時(shí)可以使用identityserver添加訪問權(quán)限。
客戶端通過clientid和secrect訪問identitserver的Token Endpoint,獲取accesstoken;
接著客戶端再使用accesstoken作為頭部驗(yàn)證訪問webapi。(webapi已經(jīng)添加了identityserver的相關(guān)驗(yàn)證)。

代碼實(shí)現(xiàn):其中 "http://localhost:5000"是identityserver地址,"http://localhost:5001"是api地址
identityserver:在identityserver添加api和客戶端,如下所示:定義了一個(gè)api1資源,client客戶端。client客戶端指定為ClientCredentials(客戶端憑據(jù))模式,并允許其訪問api1。
public class Config
{
// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
// clients want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
// client credentials client
return new List<Client>
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api1" }
}
};
}
}
在startup配置identityserver如下:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// configure identity server with in-memory stores, keys, clients and scopes
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
}
}
WebApi:在api添加identityserver的驗(yàn)證,代碼如下,其中定義了同樣的api名稱,"http://localhost:5000"是identityserver的地址。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore()
.AddAuthorization()
.AddJsonFormatters();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvc();
}
}
添加一個(gè)需要驗(yàn)證的控制器:
[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
客戶端:
這里使用里IdentityModel類庫
實(shí)際請求如下:
1.獲取accesstoken:http://localhost:5000/connect/token?client_id=client&client_secret=secret&grant_type=client_credentials&scope=api1
2.請求api1
http://localhost:5001/identity
Headers
Authorization:accesstoken
public class Program
{
public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult();
private static async Task MainAsync()
{
//獲取identitserver的各個(gè)端點(diǎn)地址
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
//獲取具有api1訪問權(quán)限的accesstoken
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
//設(shè)置accesstoken為http請求頭,并訪問api1
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
}
}
ps:
1.這里默認(rèn)的accesstoken為jwt格式,客戶端訪問api時(shí),api只需要在啟動(dòng)的時(shí)候訪問identity獲取秘鑰即可。若為referencetoken,客戶端訪問api時(shí),api需要授權(quán)訪問的都會再請求一次identityserver,,而且api必須設(shè)置秘鑰,client設(shè)置AccessTokenType屬性為Reference。
2.可自定義AccessTokenLifetime(token存活時(shí)間),默認(rèn)是3600秒,即一小時(shí)
總結(jié)
以上所述是小編給大家介紹的IdnentiyServer-使用客戶端憑據(jù)訪問API,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
VS2010中呈現(xiàn)控件時(shí)出錯(cuò)的解決方法
如何解決“呈現(xiàn)控件時(shí)出錯(cuò)”的問題,這篇文章主要介紹了VS2010中出現(xiàn)"呈現(xiàn)控件時(shí)出錯(cuò)"問題的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
.NET 6開發(fā)TodoList應(yīng)用之實(shí)現(xiàn)接口請求驗(yàn)證
在響應(yīng)請求處理的過程中,我們經(jīng)常需要對請求參數(shù)的合法性進(jìn)行校驗(yàn),如果參數(shù)不合法,將不繼續(xù)進(jìn)行業(yè)務(wù)邏輯的處理。本文將介紹如何使用FluentValidation和MediatR實(shí)現(xiàn)接口請求驗(yàn)證,需要的可以參考一下2021-12-12
彈出窗口,點(diǎn)擊確定在刪除數(shù)據(jù)的實(shí)現(xiàn)方法
彈出窗口,點(diǎn)擊確定在刪除數(shù)據(jù)的實(shí)現(xiàn)方法,需要的朋友可以參考一下2013-04-04
基于.NET的FluentValidation數(shù)據(jù)驗(yàn)證實(shí)現(xiàn)
這篇文章主要介紹了基于.NET的FluentValidation數(shù)據(jù)驗(yàn)證實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
在ASP.NET中讀寫XML數(shù)據(jù)的多種方法
在ASP.NET日常開發(fā)中,XML(可擴(kuò)展標(biāo)記語言)是一種常用的數(shù)據(jù)交換格式,它被廣泛用于配置文件、數(shù)據(jù)傳輸和Web服務(wù)等場景,在.NET框架中,提供了多種類和方法來讀寫XML數(shù)據(jù),以下是對ASP.NET中讀寫XML的詳解,需要的朋友可以參考下2025-01-01
gridview checkbox從服務(wù)器端和客戶端兩個(gè)方面實(shí)現(xiàn)全選和反選
GridView中的checkbox的全選和反選在很多的地方都是要求實(shí)現(xiàn)的,所以下面就從服務(wù)器端和客戶端兩個(gè)方面實(shí)現(xiàn)了checkbox的選擇,感興趣的朋友可以了解下,希望本文對你有所幫助2013-01-01
一個(gè)事半功倍的c#方法 動(dòng)態(tài)注冊按鈕事件
前幾天在網(wǎng)上看見一個(gè)制作計(jì)算器的c#程序,其中有一個(gè)動(dòng)態(tài)注冊按鈕事件,覺的很有用。于是實(shí)際操作了一哈, 確實(shí)比較好。2010-04-04

