在您想從 api 獲取用戶資訊的情況下,并且您可能作為用戶(最終用戶)令牌或客戶端(擁有的服務)令牌進行呼叫,最好有單獨的端點,還是共享一個端點并在內部處理授權?
例如,在這樣的事情之間:
[HttpGet]
[Authorize(Policy ="ClientAllowedToGetUserInfo")]
[Route("userinfo/{userId}")]
public ActionResult<UserInfo> GetUserInfo(Guid userId)
{
return GetTheUserInfo(userId);
}
[HttpGet]
[Authorize(Policy ="UserCheckingOwnUserInfo")]
[Route("userinfo")]
public ActionResult<UserInfo> GetUserInfo2(Guid userId)
{
return GetTheUserInfo(User.Identity.Name);
}
或這個:
[HttpGet]
[Authorize(Policy ="ClientOrUser")]
[Route("userinfo/{userId}")]
public ActionResult<UserInfo> GetUserInfo(Guid userId)
{
if User.Claims.HasClaim("MyClientClaim") || (userId == User.Identity.Name)
{
return GetTheUserInfo(userId);
}
return Forbidden();
}
最佳做法是什么?
uj5u.com熱心網友回復:
separate endpoints并且share an endpoint都可以正常作業。但他們之間有不同。使用時separate endpoints,如果驗證失敗,請求不會進入動作,直接在Policy中回傳。當您使用時share an endpoint,請求將進入操作并在if(....). 所以,在我看來,我會選擇separate endpoints。因為我更喜歡在政策中而不是在行動中驗證
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/428786.html
標籤:网 asp.net 核心 asp.net-web-api api设计
上一篇:由于ASP.NETCore中的SelectList,ModelState.IsValid一直為false
下一篇:合并2列相等的日期串列
