Search code examples
c#.netasp.net-mvcbusiness-logic

Should authorization validation be in the controller or business logic


I have an internal CRM system with the ability for customers to see their invoices.

The 5th line in the function checks if the invoice belongs to the logged in customer (if (invoice.CustomerId != loggerInCustomerId)).

I am not sure if this is where this check should be done.

public ActionResult ViewInvoice(Guid invnum)
    {
        int loggerInCustomerId = GetTheLoggedInCustomerId();
        Invoice invoice = _invoiceLogic.GetInvoice(invnum);

        if (invoice.CustomerId != loggerInCustomerId)
        {
            //Invalid Action
            return RedirectToAction("Index", "MyInvoices");
        }
        //do other stuff as normal
    }

Should this check be moved into the business logic? GetInvoice would take in the invoice number parameter and a parameter for the logged in user. GetInvoice would then do this check and throw an exception, I would have a Try Catch in my action method.

Or is there a better way to do this?


Solution

  • Should this check be moved into the business logic?

    Yes you can and in which case you will have pass the logged in user identity to BL method call. But I don't see anything wrong keeping this check in your controller itself.

    You are anyways, getting the invoice from your BL by calling GetInvoice() and then making a check to see which action to be taken and thus to me it makes much sense keeping this check in your controller Action rather having it in business layer.

    But yes, it's kind of argumentative question though.