Home > Back-end >  What's the best practice for a similar API called by Client vs User authentication
What's the best practice for a similar API called by Client vs User authentication

Time:02-19

In a situation where you want to get user info from an api, and you may be calling as a User (end-user) token or a Client (owned service) token, is it better to have separate endpoints, or to share an endpoint and handle the authorization within?

For example, between something like this:

        [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);
        }

or this:

        [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();     
        }

What's the best practice?

CodePudding user response:

separate endpoints and share an endpoint can all work fine. But there is a different between them. When you use separate endpoints, If validate fails, request will not get into the action, it just return directly in Policy. When you use share an endpoint, request will get into the action and validate in if(....). So, in my opinion, I will choose separate endpoints. Because I prefer to validate in policy rather than in action

  • Related