Saturday, December 29, 2012

How to set up OAuth and SimpleMembership on MVC4 with IIS

If you're new to MVC4, you will notice that a lot has changed with the Membership Provider.  You no longer need to run Aspnet_regsql.exe and you no longer need to run the ASP.NET Web Configuration Tool.

In MVC4, user registration and authentication is done using SimpleMembership.  By default, when you run your web application, users are registered in a lightweight database within your project called LocalDb.  If you want to use a different database such as SQL Server 2008 or 2012 then all you have to do is modify your connection string in your web.config.   What i did was I commented out the LocalDb connection and added a new one that points to my SQL Server 2012 database.


 <!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CoolDB;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CoolDB.mdf" providerName="System.Data.SqlClient" />-->

    <add name="DefaultConnection"
       connectionString="Data Source=gmisa-win;Initial Catalog=CoolDB;Integrated Security=True;MultipleActiveResultSets=True"
       providerName="System.Data.SqlClient"/

Also, add the Role Manager and Membership to your web.config:


 <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
      <providers>
        <clear />
        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
      </providers>
    </roleManager>
    <membership defaultProvider="SimpleMembershipProvider">
      <providers>
        <clear />
        <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
      </providers>
    </membership>



Once this is set, I can run my application and start registering new users.   You will notice that there are new tables created on your SQL Server database.

If you are using IIS, you have to make sure that the Application Pool that you're using runs on an Identity that can access your SQL Server database.

Now another interesting feature in MVC4 is how easy you can let users register using OAuth.  This means that users can register on your site using their Facebook, Twitter, MSN and Google accounts.  This is very simple to set up.  All you have to do is go to AuthConfig.cs which is under the App_Start folder in your project.  Uncomment the client that you want users to be able to use.  Add your app's authentication details to it.  It's usually an App Id and a Secret key.


 OAuthWebSecurity.RegisterFacebookClient(
                appId: "119036189745",
                appSecret: "ef9dj4730fkdj4ae3acc8eab4a117577");

Once this is set, run your application and click Log In.  You will see that there is a Log in using Facebook button.   Isn't that cool!??

No comments:

Post a Comment