Shai Cohen
Shai Cohen

Reputation: 6249

Is there a way to perform conditional authentication?

We are creating a MVC4 document retrieval site where some documents require authentication, while other documents allow anonymous access.

The URL includes a folder id that is used to retrieve a list of documents. Sometimes none of the documents require authentication, sometimes all the documents do, and sometimes it is a mix.

How would I approach this? Thanks in advance.

Upvotes: 0

Views: 562

Answers (2)

smartcaveman
smartcaveman

Reputation: 42246

You can create a custom Authorization Filter on the action that gets the potentially restricted document.

It will first check if the document requires authorization, by comparing it to a statically cached list of IDs for restricted documents.

Then, if the document is restricted, the filter will check if the current user is authorized. If the user is authorized, the action will be rendered as normal. Otherwise, the action result should be placed with a 401/403 (whichever is appropriate) or a redirect to a default "Unauthorized" page.

Upvotes: 1

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

I would add a bool RequiresAuthentication item to your database table that contains the documents. This would be false if the document is free (no auth needed) and true if not.

Then you could do something like this in the controller that serves the documents.

public Details(int Id)
{
    Document doc = databaseContext.Document.Find(Id);
    if(doc.RequiresAuthentication)
    {
        if(User.Identity.IsAuthenticated)
        {
            return View(doc);
        }
        // If the user is not authenticated, redirect them to log on
        return RedirectToAction("LogOn", "Account");
    }
    else
    {
        return View(doc);
    }
}

You could even pass a returnUrl to the log on so once the user logs on they are redirected back to the document they wanted.

Upvotes: 0

Related Questions