Authentication in MVC

Home > Search
  by

By default, an MVC application will include options Register and Log In in the top navigation bar. Selecting Register directs to www.example.com/Account/Register, and selecting Log In directs to www.example.com/Account/Login. When you register a user for the first time, the framework checks whether the membership database exists. In this example, the membership database does not exist in SQL Server. There is only one database (freekb) and one table (dbo.content).

 

Ensure your web.config file has a DefaultConnection:

  • Replace x.x.x.x with the IP address of your SQL Server
  • Replace database_name with the name of your database
  • Integrated Security=true is not included, as that would cause the Windows account to be used instead of the account specified
<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=x.x.x.x; Initial Catalog=database_name; User ID=username; Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>

 

Also add a User Account in SQL Server named IIS APPPOOL\server_name. Replace server_name with the name of your ASP.NET project. In this example, IIS APPPOOL\wima2.freekb.net is the db_owner of the freekb database.

 

After registering, 6 new tables are created. You can now sign in and sign out of your web application.

 

Let's say there is a specifc page you want to only allow autenticates users to be able to access, such as www.example.com/Home/About. In this example, to restrict access to the About page, you will add the [Authorize] attribute to the About class in the Home Controller.

[Authorize]
public ActionResult About()
{
  return View();
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments