[英]ASP.NET Core: How would I go about binding data from user claims?
我有一個簡單的 ASP.NET Core http API,並且有很多控制器操作都是這樣開始的:
public async Task<ActionResult> Delete()
{
if (!User.Claims.TryGetClaim("merchant_id", out long merchantId))
{
return BadRequest();
}
/* Real code using merchantId */
}
我想減少每次索賠檢查的重復,但我不確定如何去做。 我已經使用擴展方法獲得了盡可能小的代碼,但我想讓它更小,如下所示:
public async Task<ActionResult> Delete([FromClaims] long merchantId)
{
/* Real code using merchantId */
}
但是我一直在閱讀有關 ASP.NET 核心中間件的文檔,但我不知道我必須實現什么才能實現這一點。
內置FromBody
屬性繼承自IBindingSourceMetadata
,它定義了BindingSource
屬性。 但是,我在網上找不到任何關於如何實現自己的綁定源以從用戶聲明中獲取項目的資源。
您可以將策略庫授權與屬性一起使用。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthorization(options =>
{
options.AddPolicy("ShouldHaveMerchantId", policy =>
policy.RequireClaim("merchant_id"));
});
...
}
並在您的操作方法中使用 Authorize 屬性和您的策略名稱。
[Authorize(Policy = "ShouldHaveMerchantId")]
public async Task<IActionResult> YourActionMethod()
{
//Your logic
}
你可以像這樣創建一個中間件
public class MyMiddleware
{
private readonly RequestDelegate next;
public MyMiddleware (RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext ctx)
{
// Your check here, something like
if (!ctx.User.Claims.TryGetClaim("merchant_id", out long merchantId))
{
ctx.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
else
{
await next.Invoke(ctx);
}
}
}
然后像這樣注冊
app.UseMiddleware<MyMiddleware>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.