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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NET问答: 如何集中化统一验证 Authorization

發布時間:2023/12/4 编程问答 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NET问答: 如何集中化统一验证 Authorization 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

咨詢區

  • Felipe Deveza

我自己實現了一個 basic 驗證,現在我的做法是在每一個 Action 中都提取 Request.Headers["Authorization"] 進行權限驗證。

[HttpGet] public?IActionResult?Get() {string?token?=?Request.Headers["Authorization"];//?Validate?token. }[HttpPost] public?IActionResult?Post(int?id) {string?token?=?Request.Headers["Authorization"];//?Validate?token. }

請問我是否可以在某一個集中地方做 Request.Headers["Authorization"] 的全局驗證呢?

回答區

  • miechooy

你可以通過自定義中間件的方式對 header 進行統一驗證,然后決定是否傳給后端的的 Controller。

中間件的邏輯大概如下:

public?class?YourMidllewareClass{public?async?Task?Invoke(HttpContext?context){string?token?=?context.Request.Headers["Authorization"];//do?the?checkingif?(token?==?null){context.Response.StatusCode?=?401;await?context.Response.WriteAsync("Access?denied!");return;}//pass?request?further?if?correctawait?_next(context);}}

有了中間件之后,接下來通過 IApplicationBuilder 將其注入到Http請求管道中,參考如下代碼:

public?void?Configure(IApplicationBuilder?app,?IHostingEnvironment?env,?IConnectionManager?conn,?ILoggerFactory?loggerFactory) {app.UseMiddleware<YourMidllewareClass>(); }
  • Matheus Lacerda

在 ASP.NET Core 中,你可以使用內置的 AuthenticationHandler 類,詳細文檔請參考:https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x 。

剛好我的項目中有一個自定義驗證功能。

  • Startup.ConfigureServices:

  • services.AddAuthentication(options?=>{options.DefaultAuthenticateScheme?=?"Custom?Scheme";options.DefaultChallengeScheme?=?"Custom?Scheme";}).AddCustomAuth(o?=>?{?});
  • Startup.Configure:

  • app.UseAuthentication();
  • finally

  • internal?class?CustomAuthenticationHandler?:?AuthenticationHandler<CustomAuthenticationOptions> {public?CustomAuthenticationHandler(IOptionsMonitor<CustomAuthenticationOptions>?options,?ILoggerFactory?logger,?UrlEncoder?encoder,?ISystemClock?clock)?:?base(options,?logger,?encoder,?clock){}protected?override?async?Task<AuthenticateResult>?HandleAuthenticateAsync(){try{//?Your?auth?code?here//?Followed?by?something?like?this:return?AuthenticateResult.Success(new?AuthenticationTicket(new?ClaimsPrincipal(new?ClaimsIdentity(new?List<Claim>()?{?new?Claim(ClaimTypes.Sid,?Id.ToString())?},Scheme.Name)),Scheme.Name));}????????catch{return?AuthenticateResult.Fail("Error?message.");}} }

    這樣配置之后,所有對Controller的請求都會先經過 authentication ,如果某些 Controller 有特殊需求,可以使用 [AllowAnonymous] 忽略它。

    點評區

    說實話在.netcore 時代實現這種統一驗證的需求不要太簡單了,中間件這塊也是大家必須理解的基礎知識。

    總結

    以上是生活随笔為你收集整理的NET问答: 如何集中化统一验证 Authorization的全部內容,希望文章能夠幫你解決所遇到的問題。

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