IdnentiyServer使用客戶端憑據(jù)訪問API的實例代碼
情景如下:一個客戶端要訪問一個api,不需要用戶登錄,但是又不想直接暴露api給外部使用,這時可以使用identityserver添加訪問權(quán)限。
客戶端通過clientid和secrect訪問identitserver的Token Endpoint,獲取accesstoken;
接著客戶端再使用accesstoken作為頭部驗證訪問webapi。(webapi已經(jīng)添加了identityserver的相關(guān)驗證)。
代碼實現(xiàn):其中 "http://localhost:5000"是identityserver地址,"http://localhost:5001"是api地址
identityserver:在identityserver添加api和客戶端,如下所示:定義了一個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的驗證,代碼如下,其中定義了同樣的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(); } }
添加一個需要驗證的控制器:
[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類庫
實際請求如下:
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的各個端點地址 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"); //設置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.這里默認的accesstoken為jwt格式,客戶端訪問api時,api只需要在啟動的時候訪問identity獲取秘鑰即可。若為referencetoken,客戶端訪問api時,api需要授權(quán)訪問的都會再請求一次identityserver,,而且api必須設置秘鑰,client設置AccessTokenType屬性為Reference。
2.可自定義AccessTokenLifetime(token存活時間),默認是3600秒,即一小時
總結(jié)
以上所述是小編給大家介紹的IdnentiyServer-使用客戶端憑據(jù)訪問API,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
ASP.NET Gridview與checkbox全選、全不選實現(xiàn)代碼
ASP.NET Gridview checkbox全選與全不選實現(xiàn)代碼,其實原理就是利用js來實現(xiàn)的,但需要簡單的設置下回傳。2010-04-04ASP.NET中Session和Cache的區(qū)別總結(jié)
這篇文章主要介紹了ASP.NET中Session和Cache的區(qū)別總結(jié),本文結(jié)合使用經(jīng)驗,總結(jié)出了5點Session緩存和Cache緩存的區(qū)別,需要的朋友可以參考下2015-06-06在asp.net(C#)中采用自定義標簽和XML、XSL顯示數(shù)據(jù)
在asp.net(C#)中采用自定義標簽和XML、XSL顯示數(shù)據(jù)的實現(xiàn)代碼。2009-06-06使用FreeHost SQL2000網(wǎng)頁管理器出錯解決辦法
在您登陸FreeHost SQL2000網(wǎng)頁管理器時,如果提示以下信息: 發(fā)生類型為 System.Web.HttpUnhandledException 的異常2012-01-01.NET?Core控制臺應用ConsoleApp讀取appsettings.json配置文件
這篇文章介紹了.NET?Core控制臺應用ConsoleApp讀取appsettings.json配置文件的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07.NET6?ConfigurationManager的實現(xiàn)及使用方式
這篇文章主要介紹了.NET6?ConfigurationManager的實現(xiàn),我們上面展示的這一部分的ConfigurationManager代碼,其實就是替代了原來的ConfigurationBuilder類的功能,需要的朋友可以參考下2021-12-12告別ADO.NET實現(xiàn)應用系統(tǒng)無縫切換的煩惱(總結(jié)篇)
說起ADO.NET,就扯上了數(shù)據(jù)庫訪問類庫了,現(xiàn)在的每個項目的數(shù)據(jù)庫訪問類應該說都很強的了,經(jīng)常就聽到說我的我們的數(shù)據(jù)庫訪問類怎么怎么強大而且支持多數(shù)據(jù)庫,現(xiàn)在的大家做的項目里用的數(shù)據(jù)庫訪問類庫我想也都是支持多數(shù)據(jù)庫吧,支持到什么程度我就不知道了2009-11-11ASP.net Substitution 頁面緩存而部分不緩存的實現(xiàn)方法
在ASP.NET中要實現(xiàn)部分內(nèi)容非緩存,而其它的都需要緩存輸出,可以使用Substitution控件實現(xiàn).2009-03-03