Thursday, February 13, 2014

ASP.NET MVC5 (Novice) Protecting your site with a login wrapper

The default MVC framework includes login and registration pages. They are functional, but by default the main pages in the site are not configured as login-protected.

 

As with much of MVC, the login wrapper has been abstracted to a configuration component – a filter in this case.

 

In the solution explorer under ~/App_Start, double, double-click “FilterConfig.cs”

 

Add the following lines to RegisterGlobalFilters:

 

filters.Add(new System.Web.Mvc.AuthorizeAttribute());

filters.Add(new RequireHttpsAttribute());

 

I disabled RequireHttpsAttribute during development.

 

The entire site is now protected by the login wrapper with the exception of the account related pages. The account pages are excluded from the login wrapper because of the [AllowAnonymous] attribute.

 

 

For a much more comprehensive treatment, see “Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to a Windows Azure Web Site” by Rick Anderson.

 

This is a beginning-to-end explanation of how to create and deploy a site. To skip to the security section, scroll to the middle of the page and look for “Protect the Application with SSL and Authorize Attribute”. He even explains how to create security levels!

 

 

 

 

ASP.NET MVC5 (Novice) Creating different layouts for different views

I’m creating a simple login-protected site. I want to have a main layout for the core site and a separate layout for the login and other account-related pages.

 

It took me a while to stumble on the most ‘elegant’ answer for ASP.NET MVC 5. The easiest/best solution (also restated here) is to copy _ViewStart.cshtml from the View folder root to the view folder that you want to style differently.

 

Create a new layout in ~/Views/Shared … (_Layout-Account.cshtml in my case)

 

and edit ~/Views/Account/_ViewStart.cshtml to point to the new Layout.

 

This will override the main _ViewStart.cshtml in the Views folder. There are many other approaches, like adding conditional logic to the main _ViewStart.cshtml page, but creating a _ViewStart.cshtml page for each view you

 

Shailendra Chauhan made an excellent blog post exploring many different ways of rendering layouts in ASP.NET MVC.