Creating the app in Facebook and connecting the app to the project

For Facebook OAuth2 authentication, you need to copy to your project some settings from an application that you create in Facebook.
  1. In your browser, navigate to https://developers.facebook.com/apps and log in by entering your Facebook credentials.
  2. If you aren't already registered as a Facebook developer, click Register as a Developer and follow the directions to register.
  3. On the Apps tab, click Create New App.
    Create new app
  4. Enter an App Name and Category, then click Create App.
    This must be unique across Facebook. The App Namespace is the part of the URL that your App will use to access the Facebook application for authentication (for example, https://apps.facebook.com/{App Namespace}). If you don't specify an App Namespace, the App ID will be used for the URL. The App ID is a long system-generated number that you will see in the next step.
    Create New App dialog
  5. Submit the standard security check.
    Security Check
  6. Select Settings for the left menu bar.Facebook Developer's menu bar
  7. On the Basic settings section of the page select Add Platform to specify that you are adding a website application. Basic Settings
  8. Select Website from the platform choices.
    Platform choices
  9. Make a note of your App ID and your App Secret so that you can add both into your MVC application later in this tutorial. Also, Add your Site URL (https://localhost:44300/) to test your MVC application. Also, add a Contact Email. Then, select Save Changes.
    Basic application details page
    Note
    Note that you will only be able to authenticate using the email alias you have registered. Other users and test accounts will not be able to register. You can grant other Facebook accounts access to the application on the Facebook Developer Roles tab.
  10. In Visual Studio, open App_Start\Startup.Auth.cs.
  11. Copy and paste the AppId and App Secret into the UseFacebookAuthentication method. The AppId and App Secret values shown below are samples and will not work.
    C#
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    
        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");
    
        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");
    
        app.UseFacebookAuthentication(
           appId: "000000000000000",
           appSecret: "000000000000000");
    
        app.UseGoogleAuthentication(
             clientId: "000000000000000.apps.googleusercontent.com",
             clientSecret: "000000000000000");
    }
    
  12. Click Save Changes.
  13. Press CTRL+F5 to run the application.
Select Log in to display the Login page. Click Facebook under Use another service to log in.
Enter your Facebook credentials.
You will be prompted to grant permission for the application to access your public profile and friend list.
Facebook app details
You are now logged in. You can now register this account with the application.
When you register, an entry is added to the Users table of the membership database.

Examine the Membership Data

In the View menu, click Server Explorer.
Expand DefaultConnection (MvcAuth), expand Tables, right click AspNetUsers and click Show Table Data.
aspnetusers table data

Adding Profile Data to the User Class

In this section you'll add birth date and home town to the user data during registration, as shown in the following image.
reg with home town and Bday
Open the Models\IdentityModels.cs file and add birth date and home town properties:
C#
public class ApplicationUser : IdentityUser
{
    public string HomeTown { get; set; }
    public System.DateTime? BirthDate { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}
Open the Models\AccountViewModels.cs file and the set birth date and home town properties in ExternalLoginConfirmationViewModel.
C#
public class ExternalLoginConfirmationViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    public string HomeTown { get; set; }
    public System.DateTime? BirthDate { get; set; }
}
Open the Controllers\AccountController.cs file and add code for birth date and home town in the ExternalLoginConfirmation action method as shown:
C#
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Manage");
    }

    if (ModelState.IsValid)
    {
        // Get the information about the user from the external login provider
        var info = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (info == null)
        {
            return View("ExternalLoginFailure");
        }
        var user = new ApplicationUser() 
        {
            UserName = model.Email, Email = model.Email,
            BirthDate = model.BirthDate,
            HomeTown  = model.HomeTown
        
        };
        IdentityResult result = await UserManager.CreateAsync(user);
        if (result.Succeeded)
        {
            result = await UserManager.AddLoginAsync(user.Id, info.Login);
            if (result.Succeeded)
            {
                await SignInAsync(user, isPersistent: false);
                
                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // SendEmail(user.Email, callbackUrl, "Confirm your account", "Please confirm your account by clicking this link");
                
                return RedirectToLocal(returnUrl);
            }
        }
        AddErrors(result);
    }

    ViewBag.ReturnUrl = returnUrl;
    return View(model);
}
Add birth date and home town to the Views\Account\ExternalLoginConfirmation.cshtml file:
cshtml
@model MvcAuth.Models.ExternalLoginConfirmationViewModel
@{
    ViewBag.Title = "Register";
}
<h2>@ViewBag.Title.</h2>
<h3>Associate your @ViewBag.LoginProvider account.</h3>

@using (Html.BeginForm("ExternalLoginConfirmation", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

    <h4>Association Form</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <p class="text-info">
        You've successfully authenticated with <strong>@ViewBag.LoginProvider</strong>.
            Please enter a user name for this site below and click the Register button to finish
            logging in.
    </p>
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.HomeTown, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.HomeTown, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.HomeTown)
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.BirthDate, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.BirthDate, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.BirthDate)
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Delete the membership database so you can again register your Facebook account with your application and verify you can add the new birth date and home town profile information.
From Solution Explorer, click the Show All Files icon, then right click Add_Data\aspnet-MvcAuth-<dateStamp>.mdf and click Delete.
From the Tools menu, click NuGet Package Manger, then click Package Manager Console(PMC). Enter the following commands in the PMC.
  1. Enable-Migrations
  2. Add-Migration Init
  3. Update-Database
Run the application and use FaceBook and Google to log in and register some users.

Examine the Membership Data

In the View menu, click Server Explorer.
Right click AspNetUsers and click Show Table Data.
The HomeTown and BirthDate fields are shown below.

Logging off your App and Logging in With Another Account

If you log on to your app with Facebook,, and then log out and try to log in again with a different Facebook account (using the same browser), you will be immediately logged in to the previous Facebook account you used. In order to use another account, you need to navigate to Facebook and log out at Facebook. The same rule applies to any other 3rd party authentication provider. Alternatively, you can log in with another account by using a different browser.

Next Steps

See Introducing the Yahoo and LinkedIn OAuth security providers for OWIN by Jerrie Pelser for Yahoo and LinkedIn instructions. See Jerrie's Pretty social login buttons for ASP.NET MVC 5 to get enable social login buttons.
Follow my tutorial Create an ASP.NET MVC app with auth and SQL DB and deploy to Azure App Service, which continues this tutorial and shows the following:
  1. How to deploy your app to Azure.
  2. How to secure you app with roles.
  3. How to secure your app with the RequireHttps and Authorize filters.
  4. How to use the membership API to add users and roles.
Please leave feedback on how you liked this tutorial and what we could improve. You can also request new topics at Show Me How With Code. You can even ask for and vote on new features to be added to ASP.NET. For example, you can vote for a tool to create and manage users and roles.
For an good explanation of how ASP.NET External Authentication Services work, see Robert McMurray's External Authentication Services. Robert's article also goes into detail in enabling Microsoft and Twitter authentication. Tom Dykstra's excellent EF/MVC tutorial shows how to work with the Entity Framework.