//

SECURING YOUR ASP.NET MVC 4 APPLICATION

Out of the Box when you create an MVC web site, anyone can post anything to your web site. So we need to control the user access.

Microsoft provides a pre-made code for securing your ASP.NET MVC 4 application: [Authorize] attribute Properties of the [Authorize] attribute

  • users
  • roles
 [HttpPost]
 [Authorize]
 public ActionResult Create([Bind(Exclude="CurrentPrice")]Models.Auction auction)
 {
    if (ModelState.IsValid)
    {
        // Save to the database
        var db = new AuctionsDataContext();
        db.Auctions.Add(auction);
        db.SaveChanges();
        return RedirectToAction("Index");
    } 

        return Create();
 }

You could add AllowAnonymous attribute to the controllers that can be accessed by anyone.

 [AllowAnonymous]
 public class HomeController : Controller
 {
    public ActionResult Index()
    {
        return View();
    }
 }

Now even though unauthorized users can see and fill the posts page, when they attempt to post, it will redirect to the log in page. We can specify who could access the page by assigning a user to the Authorize attribute. (User)

[Authorize(Users="John")]

Also we could allow a group to access the create function. (Role)

[Authorize(Roles="Admin")]

Values as such are called a  Whitelist and opposite being Blacklist.

Creating User Accounts

Any user can create an account with your default ASP.NET MVC site by registering a user name and a password.

<section class="social" id="socialLoginForm">
     ## Use another service to log <span class="Statement">in</span>.
     @Html.Action("ExternalLoginsList", 
         new { ReturnUrl = ViewBag.ReturnUrl })
</section>

Also you could use external authentication services by uncommenting the fields of AuthConfig.cs file in App_Start folder.