ASP.NET MVC Forms Authentication with SqlMembershipProvider
The ASP.NET MVC Website Template comes pre-configured to use SqlMembershipProvider which manages storage of membership information for an ASP.NET application in a SQL Server database.
But before you can use this properly you will need to setup your database, which will be very easy because Microsoft shipped .NET 2.0 with a nice utility to do it! You can find this on your computer, at this path C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe
Your database should have these tables:
Now lets tell our ASP.NET MVC Website’s configuration where to find this database. Open the web.config and change the ApplicationServices connection string to point to your SQL Server. You should now rebuild your solution to avoid any problems in the next step!
<connectionStrings> <add name="ApplicationServices" connectionString="Data Source=localhost; Initial Catalog=database; Persist Security Info=True; User ID=user; Password=password" providerName="System.Data.SqlClient" /> </connectionStrings>
It’s all good and nice but now we need Users in this database otherwise it’s completly useless! So open up your ASP.NET MVC Solution in Visual Studio and go to Project » ASP.NET Configuration. This will open the ASP.NET Web Application Administration website. In the Security tab you can Add/Manage Users and Roles. For the moment, add a user so we can try the login. I’ve added user Mike.
You can now run your application and click on [ Log On ] at the top right corner of the page, this will redirect you the the logon form.
If you entered the correct credential you should be redirected to the home page of the site and you will see your name and a Log Off button instead of the Log On button.
Well congraticulations! You now have SqlMembershipProvider working on your website, wasn’t so hard, was it? Not a single line of code required! I’ll be posting again soon to show you how to use Roles in your applications.
This entry was posted on Wednesday, April 22nd, 2009 at 9:16 pm and is filed under ASP.NET, C#.NET, Developement, MVC, SQL Server. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.