Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#)
This tutorial shows you how to build an ASP.NET MVC 5 web application that enables users to log in using OAuth 2.0 or OpenID with credentials from an external authentication provider, such as Facebook, Twitter, Microsoft, or Google. For simplicity, this tutorial focuses on working with credentials from Facebook and Google.
Enabling these credentials in your web sites provides a significant advantage
because millions of users already have accounts with these external providers.
These users may be more inclined to sign up for your site if they do not have to
create and remember a new set of credentials
Prerequisites
- Visual Studio Express 2013 Preview for Web or Visual Studio 2013 Preview.
- Microsoft ASP.NET Web Frameworks and Tools - Visual Studio 2013 Preview.
Getting Started
Start by installing and running Visual Studio Express 2013 Preview for Web or Visual Studio 2013 Preview. You also need to install the Microsoft ASP.NET Web Frameworks and Tools - Visual Studio 2013 Preview.
Click New Project from the Start page, or you can use the menu and select File, and then New Project.
Creating Your First Application
You can create applications using either Visual Basic or Visual C# as the programming language. Click New Project, then select Visual C# on the left, then Web and then select ASP.NET Web Application. Name your project "MvcAuth" and then click OK.
In the New ASP.NET Project dialog, click MVC and then click Configure Authentication.
In the Configure Authentication dialog, keep the default Individual User Accounts, and then click OK.
Back in the New ASP.NET Project dialog, Click Create Project. Click F5 or Control F5 to run the application. In the image below, the port number is 1234. When you run the application, you'll see a different port number.
Depending on the size of your browser window, you might need to click the navigation icon to see the Home, About, Contact, Register and Log in links.
Enable the Google OpenID provider
Open the App_Start\Startup.Auth.cs file and remove the comment
characters in //app.UseGoogleAuthentication();
to
enable Google authentication.
public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseApplicationSignInCookie(); // Enable the application to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); app.UseGoogleAuthentication(); }
Press Control F5 to build and run the application. Click the Log in link.
Under Use another service to log in, click Google.
You will be redirected to the google site where you will enter your credentials. After you enter your credentials, you will be promoted to give permission to the web application you just created to:
- View basic information about your account.
- View your email address
Click Accept.
You will now be redirected back to the Register page of MvcAuth application where you can register your Google account with the MvcAuth application. Notice the URL in the image above contains openid2. Unlike OAuth2 providers, OpenID providers don't require you to create an application with the authentication provider.
Click Register to add the user name and your Google account information to the MvcAuth application.
Next you are redirected back to the home page where you can see that your name and a Log off link.
That's all you need to add Google as an identity provider.
Setting up SSL in the Project
To connect to Facebook, you will need to set up IIS-Express to use SSL. Even though Google doesn't require you to use SSL to log in, it's a best security practice to require SSL in your application. Your login cookie is just as secret as your username and password, and without using SSL you’re sending it in clear-text across the wire. Besides, you’ve already taken the time to perform the handshake and secure the channel (which is the bulk of what makes HTTPS slower than HTTP) before the MVC pipeline is run, so redirecting back to HTTP after you’re logged in won’t make the current request or future requests much faster.
- In Solution Explorer, click the MvcAuth project.
- Enter the F4 key to show the project properties. Alternatively, from the View menu you can select Properties Window.
- Change SSL Enabled to True.
- Copy the SSL URL.
- In Solution Explorer, right click the MvcAuth and select Properties.
- Select the Web tab, then paste the SSL URL into the Project Url
box. Save the file (Ctl+S). You will need this URL to configure
Facebook.
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.
-
In your browser, navigate to https://developers.facebook.com/apps and log in by entering your Facebook credentials.
-
If you aren’t already registered as a Facebook developer, click Register as a Developer and follow the directions to register.
-
Click Create New App.
-
Enter an App Name and App Namespace, and then click Continue.
These must be unique across Facebook. The App Namespace is the part of the URL that people will use to access your Facebook application (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.
-
On the Basic Settings page for the app, set the Sandbox Mode to Enabled. This ensures that you have exclusive access to the app until it's ready to be made available to everyone.
You’ll use the App ID, App Secret, and Namespace settings in the next step.
-
In Visual Studio, open the application App_Start\Startup.Auth.cs.
-
Copy and paste the AppId and App Secret into the
UseFacebookAuthentication
method. Be sure to remove the comment characters. The AppId and App Secret values below will not work.public void ConfigureAuth(IAppBuilder app) { // 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 app.UseSignInCookies(); // 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(); }
-
Copy the Project URL from the Web tab and paste it into the Canvas URL and Secure Canvas URL fields in the Facebook Basic Settings page.
-
Click Save Changes.
-
Press CTRL+F5 to run the application.
When you run the application in Internet Explorer (IE), Firefox, or Page Inspector, you get a security certificate warning. This is because the certificates used by IIS Express are not trusted by browsers. You can dismiss these warnings on your development machine. When you deploy the application to Windows Azure, the SSL certificates are trusted and you won't get any warnings. In IE, click Continue to this website (not recommended). In Chrome, click Proceed anyway.


Under Use another service to log in. click Facebook.
Enter your Facebook credentials.
You are now logged. You can now register this account with the application.
When you register, an entry is added to the Users table of the membership database.
The Membership Database
In this section you will examine the membership database and add a user role.
If you are using Visual Studio Express 2012 Preview for Web, from the View menu, click Database Explorer.
If you are using Visual Studio 2013 Preview, from the View menu, click Server Explorer.
Right click on the Users table and click Show Table Data.
You can see the newly added users and their id's.
Add a Role
Right click on the Roles table and click Show Table Data.
Enter canEdit in the Id column.
Right click on the UserRoles table and click Show Table Data. Enter canEdit in the RoleId column and copy and paste a users Id (from the UserLogins table) into the UserId column.
The user you added to the canEdit role
Require Authorization
Open the Controllers\HomeController.cs file and add the following
Authorize attribute to the About
method.
[Authorize(Roles = "canEdit")] public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); }
The Authorize attribute will prevent users who are not members of the canEdit role from accessing this method. A user who is not a member of the canEdit role will be redirected to the Login page (where they have a chance to login as a user who is a member of the canEdit role.)
Run the application and navigate to the About
method. The user
you added to the
canEdit role will be able to access the About
page. Login as a user who is not a member of the canEdit role,
that user will be redirected to the Login page.
Note: Log off functionality is not complete in this release. To log into another account with the same provider (for example, to log on using another Google account, you will either need to user another browser or open an incognito window (Chrome) or Start InPrivate Browsing (IE).
Remove Local ASP.NET Membership Registration
The current local ASP.NET membership registration in the project does not provide support for password resets and it does not verify that a human is registering (for example with a CAPTCHA). Once a user is authenticated using one of the third party providers, they can register and the third party provider has support for password rest. In the AccountController, remove the [AllowAnonymous] attribute from the GET and POST Register methods. This will prevent bots and anonymous users from registering.
Next Steps
For an excellent 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.
For more tips on making the application secure, see my tutorial Deploy a Secure ASP.NET MVC app with Membership, OAuth, and SQL Database to a Windows Azure Web Site.
Comments (0) RSS Feed