日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API

發布時間:2023/12/4 asp.net 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架學習之保護API。

使用IdentityServer4 來實現使用客戶端憑據保護ASP.NET Core Web API 訪問。

IdentityServer4 GitHub: https://github.com/IdentityServer/IdentityServer4

IdentityServer 框架支持以下功能:

身份驗證服務
所有應用程序(Web,本機,移動,服務)的集中登錄邏輯和工作流。

單點登錄/退出
對多種應用程序類型的單點登錄和退出。

API的訪問控制
針對各種類型的客戶發出針對API的訪問令牌,例如服務器到服務器,Web應用程序,SPA和本機/移動應用程序。

聯合登錄
支持外部身份提供程序,如Azure Active Directory,Google,Facebook等。

專注于定制
IdentityServer最重要的部分 - 許多方面可以定制,以滿足你的需要。由于IdentityServer是一個框架,而不是一個封閉產品或SaaS,你可以編寫代碼,使你的系統適應對應的場景。

?

?

IdentityServer實現了以下規范:

OpenID Connect

OpenID Connect Core 1.0
OpenID Connect Discovery 1.0
OpenID Connect Session Management 1.0 - draft 22
OpenID Connect HTTP-based Logout 1.0 - draft 03

OAuth 2.0

OAuth 2.0 (RFC 6749)
OAuth 2.0 Bearer Token Usage (RFC 6750)
OAuth 2.0 Multiple Response Types
OAuth 2.0 Form Post Response Mode
OAuth 2.0 Token Revocation (RFC 7009)
OAuth 2.0 Token Introspection (RFC 7662)
Proof Key for Code Exchange (RFC 7636)

?

主要講解?使用客戶端憑據保護API 。如何保證的你的API 不被其他人擅自訪問?

下面開始正式的實例。

新建ASP.NET Core項目及引用IdentityServer4

首先新建一個ASP.NET Core項目IdentityServer4Demo,然后選擇?空?模板。

?

然后添加引用。

NuGet命令行:

Install-Package IdentityServer4 -Pre

IdentityServer4使用

添加好引用以后我們就可以來使用了。

首先創建一個 Config.cs 類。

定義范圍:

public static IEnumerable<Scope> GetScopes()

? ? ? ? {

? ? ? ? ? ? return new List<Scope>

? ? ? ? ? ? {

? ? ? ? ? ? ? ? new Scope

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? Name = "zeroapi",

? ? ? ? ? ? ? ? ? ? Description = "LineZero ASP.NET Core Web API"

? ? ? ? ? ? ? ? }

? ? ? ? ? ? };

? ? ? ? }

定義客戶端:

public static IEnumerable<Client> GetClients()

? ? ? ? {

? ? ? ? ? ? return new List<Client>

? ? ? ? ? ? {

? ? ? ? ? ? ? ? new Client

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ClientId = "linezeroclient",


? ? ? ? ? ? ? ? ? ? //使用clientid / secret進行身份驗證

? ? ? ? ? ? ? ? ? ? AllowedGrantTypes = GrantTypes.ClientCredentials,


? ? ? ? ? ? ? ? ? ? // 加密驗證

? ? ? ? ? ? ? ? ? ? ClientSecrets = new List<Secret>

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? new Secret("secret".Sha256())

? ? ? ? ? ? ? ? ? ? },


? ? ? ? ? ? ? ? ? ? // client可以訪問的范圍,在上面定義的。

? ? ? ? ? ? ? ? ? ? AllowedScopes = new List<string>

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? "zeroapi"

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }; ?

? ? ? ? }

定義好以后,在Startup.cs 中 配置IdentityServer4

public void ConfigureServices(IServiceCollection services){services.AddDeveloperIdentityServer() ? ? ? ? ? ? ? ?.AddInMemoryScopes(Config.GetScopes()) ? ? ? ? ? ? ? ?.AddInMemoryClients(Config.GetClients());} public void Configure(IApplicationBuilder app, IHostingEnvironment env){ ? ? ? ? ? ?app.UseIdentityServer();}

然后我們啟動IdentityServer4Demo?

訪問:http://localhost:5000/.well-known/openid-configuration

IdentityServer 創建成功。

?

新建WebAPI項目

然后添加引用。

NuGet命令行:

Install-Package IdentityServer4.AccessTokenValidation -Pre

?

首先更改API 的URL地址,不和Server 重復。

這里改為?http://localhost:5001

public static void Main(string[] args)

? ? ? ? {

? ? ? ? ? ? var host = new WebHostBuilder()

? ? ? ? ? ? ? ? .UseKestrel()

? ? ? ? ? ? ? ? .UseUrls("http://localhost:5001")

? ? ? ? ? ? ? ? .UseContentRoot(Directory.GetCurrentDirectory())

? ? ? ? ? ? ? ? .UseIISIntegration()

? ? ? ? ? ? ? ? .UseStartup<Startup>()

? ? ? ? ? ? ? ? .Build();


? ? ? ? ? ? host.Run();

? ? ? ? }

然后在Startup.cs 中 配置相關信息

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

? ? ? ? {

? ? ? ? ? ? loggerFactory.AddConsole(Configuration.GetSection("Logging"));

? ? ? ? ? ? loggerFactory.AddDebug();

? ? ? ? ? ? app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Authority = "http://localhost:5000",

? ? ? ? ? ? ? ? ScopeName = "zeroapi",


? ? ? ? ? ? ? ? RequireHttpsMetadata = false

? ? ? ? ? ? });


? ? ? ? ? ? app.UseMvc();

? ? ? ? }

注意:這里定義的授權地址是 ?http://localhost:5000?

下面我們來定義API,添加一個Web API 控制器 ClientController?

[Route("api/[controller]")]

? ? [Authorize]

? ? public class ClientController : Controller

? ? {

? ? ? ? [HttpGet]

? ? ? ? public IActionResult Get()

? ? ? ? {

? ? ? ? ? ? return new JsonResult(from c in User.Claims select new { c.Type, c.Value });

? ? ? ? }

? ? }

上面添加了?Authorize 特性,直接訪問API 是無法訪問的。

程序啟動以后,訪問http://localhost:5001/api/client 會返回401 。

客戶端調用

創建一個客戶端調用,添加一個控制臺程序 Client。

首先也要添加引用:

NuGet命令行:

Install-Package IdentityModel

客戶端代碼如下:

public static void Main(string[] args)

? ? ? ? {

? ? ? ? ? ? //訪問授權服務器獲取token

? ? ? ? ? ? var disco = DiscoveryClient.GetAsync("http://localhost:5000").Result;

? ? ? ? ? ? var tokenClient = new TokenClient(disco.TokenEndpoint, "linezeroclient", "secret");

? ? ? ? ? ? var tokenResponse = tokenClient.RequestClientCredentialsAsync("zeroapi").Result;

? ? ? ? ? ? if (tokenResponse.IsError)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Console.WriteLine(tokenResponse.Error);

? ? ? ? ? ? ? ? return;

? ? ? ? ? ? }


? ? ? ? ? ? Console.WriteLine(tokenResponse.Json);

? ? ? ? ? ? Console.WriteLine("==============================");

? ? ? ? ? ? //設置token 訪問API

? ? ? ? ? ? var client = new HttpClient();

? ? ? ? ? ? client.SetBearerToken(tokenResponse.AccessToken);


? ? ? ? ? ? var response = client.GetAsync("http://localhost:5001/api/client").Result;

? ? ? ? ? ? if (!response.IsSuccessStatusCode)

? ? ? ? ? ? {

? ? ? ? ? ? ? ? Console.WriteLine(response.StatusCode);

? ? ? ? ? ? }


? ? ? ? ? ? var content = response.Content.ReadAsStringAsync().Result;

? ? ? ? ? ? Console.WriteLine(content);

? ? ? ? ? ? Console.ReadKey();

? ? ? ? }

然后開始一個個運行。

首先啟動?IdentityServer4Demo,然后API 然后Client。

Client 成功訪問 API 。使用客戶端憑據保護API 到這里就基本完成。

更多IdentityServer4信息:https://identityserver4.readthedocs.io/?

相關文章:?

  • Thinktecture IdentityServer:.NET開源OpenID和OAuth解決方案

  • 教你實踐ASP.NET Core Authorization(免看文檔教程)

原文地址:http://www.cnblogs.com/linezero/p/IdentityServer4.html


.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注

總結

以上是生活随笔為你收集整理的IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。