Return 403 from webapi2 controller

My API has the following routes

GET: api / department

GET: api / department / {departmentID} / employees

The second route displays the next controller action

public IEnumerable<Employee> Get(int departmentID)
{
  return GetEmployees(departmentID);
}

This route could potentially be called using a department identifier that does not exist or the user does not have access to access. When this happens, what is the right way to handle this? Currently, I have changed the action of my controller to return 403, as shown below.

public HttpResponseMessage Get(int departmentID)
{
  var isDepartmentValid = CheckIfDepartmentIsAccessible(username, departmentID);
  if(!isDepartmentValid)
  {
    return Request.CreateResponse(HttpStatusCode.Forbidden);
  }

   Request.CreateResponse(HttpStatusCode.OK, GetEmployees(departmentID));
}

Is this right to do? It seems that changing the method signature makes it difficult to understand the type of content returned from the controller action. Is there a way for the method signature to remain the same, but return 403 if necessary?

+4
3

, , , :

public IEnumerable<Employee> Get(int departmentID)
{
   try
   {
      return GetEmployees(departmentID);
   }
   catch(Exception ex) //assuming invalid dept or unauthorized throw Argument & Security Exceptions respectively
   {
        if(ex is SecurityException)
            throw new HttpResponseException(HttpStatusCode.Forbidden);
        else if(ex is ArgumentException)
            throw new HttpResponseException(HttpStatusCode.NotFound);
        else
             //handle or throw actual unhandled exception
    }
}

, , , , , , . . WebAPI, , , , .

+5

:

public IEnumerable<Employee> Get(int departmentID)
{
    var isDepartmentValid = CheckIfDepartmentIsAccessible(username, departmentID);
    if (!isDepartmentValid)
    {
        throw new HttpResponseException(HttpStatusCode.Forbidden);
    }

    return Request.CreateResponse(HttpStatusCode.OK, GetEmployees(departmentID));
}
+3

For me, the best place to host all types of authentication / authorization would be either in the OWIN middleware or in some authorization authorization filters; but it depends on your requirements, because if you no longer have routes that require auth, I would leave the solution as it is and check it inside the controller itself.

0
source

Source: https://habr.com/ru/post/1606012/


All Articles