Using MVC4 and OAuth with a MVC 4 Mobile Application

Tags: MVC4, Mobile, OAuth, DotNetOpenAuth

In my last blog I wrote about using MVC 4 and OAuth to log in with a Facebook, Google, LinkedIn, Microsoft, Twitter, Yahoo!, or StackExchange account.  The sample application was based on the MVC 4 Internet Application template.  This blog will explain the steps I took to port that functionality over to an application based on the MVC 4 Mobile Application template so I could use OAuth in a standard MVC 4 mobile application.

Please note that all of the same caveats in terms of the secret keys in the App_Start\AuthConfig.cs apply, so if you haven’t read that blog you will need to if you want to support logins from all of these web sites.  The source code for the mobile solution is at the end of this article.

Steps to migrate OAuth features in the OAuthWithMVC4 internet application to a mobile application

  • Created the OAuthWithMVC4 internet application (if you don’t have it you can download the solution)
  • Created a new MVC4 mobile application (in this case named OAuthWithMVC4Mobile)
  • Copied the packages for DotNetOpenAuth.*, Microsoft.AspNet.WebPages.*
  • Update Packages.config with the 9 packages copied over in step 3
  • Add references to the 9 packages copied over in step 3
  • Updated About and Contact view pages
  • Copied AuthConfig.cs from App_Start folder from OAuthWithMVC4 app and changed the namespace name to match the current project
  • Add AuthConfig.RegisterAuth(); to global.asax.cs
  • Added a Filters folder to the root of the web solution
  • Copied InitializeSimpleMembershipAttribute over and updated the namespace references to the current project
  • Copy UsersContext, UserProfile, ExternalLogin and RegisterExternalLogin classes from Models\AccountModels, and renamed ChangePasswordModel to LocalPasswordModel
  • Copied ExternalLoginConfirmation.cshtml and ExternalLoginFailure.cshtml to Views\Account and udpated the namespace reference in ExternalLoginConfirmation.cshtml
  • Copied AccountController.cs file to controllers folder and replaced namespaces with the project name
  • Remove ChangePassword.cshtml and ChangePasswordSuccess.cshtml from Views\Account
  • Copy _ExternalLoginsListPartial.cshtml to the Views\Account Folder
  • Added following to login.cshtml
    <section class="social" id="socialLoginForm">
      @Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
    </section>
  • Added <add key="enableSimpleMembership" value="true" /> to web.config's <appSettings>
  • Changed <membership defaultProvider="DefaultMembershipProvider"> to <membership defaultProvider="SimpleMembershipProvider">
  • Changed the membership provider from

     <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
to
      <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData, Version=2.0.0.0, Culture=neutral,   PublicKeyToken=31bf3856ad364e35" />

Note: The following 5 are from http://stackoverflow.com/questions/12573824/how-to-get-oauth-working-on-mvc4-mobile

  • In root web.config replaced the compilation section in <system.web> 

     <compilation debug="true" targetFramework="4.5"/>

          with the code shown below to add the 2 WebMatrix assemblies to initialize the Role Manager

     <compilation debug="true" targetFramework="4.5">
       <assemblies>
         <add assembly="WebMatrix.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
         <add assembly="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
       </assemblies>
     </compilation>

  • Modified _layout.cshtml so it can render a custom script after loading jQuery, but before loading jQuery mobile:

    @Scripts.Render("~/bundles/jquery","~/scripts/RemoveHashFromWindowLocation")
    @RenderSection("beforeJqueryMobile", required: false);
    @Scripts.Render( "~/bundles/jquerymobile")
    @RenderSection("scripts", required: false)

  • Modified Login.cshtml so it contains the section:

    @section BeforeJqueryMobile {
      @Scripts.Render("~/scripts/disable-ajax.js")
    }

  • Added a script named disable-ajax.js in the scripts folder which contails the following javascript:

    $(document).bind("mobileinit", function () {
      $.mobile.ajaxEnabled = false;
    });

  • Added a script named RemoveHashFromWindowLocation.js to the scripts folder which contains the following javascript (thanks to http://stackoverflow.com/questions/8069704/facebook-oauth-login-with-jquery-mobile):

    if (window.location.hash == "#_=_")
      window.location.hash = "";

  • Added ReadMe.txt and BSD-License.txt files to solution
  • Updated Properties\AssemblyInfo.cs with copyright information

Source Code

Download OAuthWithMVC4Mobile.zip for the source code that accompanies this blog post.

1 Comment

  • Kim Badger said

    Heya i'm for the primary time here. I found this board and I to find It really helpful & it helped me out a lot. I am hoping to offer one thing back and help others like you aided me.

Comments have been disabled for this content.