Authentication Using Twitter In ASP.NET Core 2.0

 
Introduction
Sometimes, we want the users to log in using their existing credentials of third-party applications such as Facebook, Twitter, Google etc. into our application. In this article, we are going to look into authentication of ASP.NET Core app using Twitter.

Prerequisites
  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Create MVC Web Application

Open Visual Studio and select File >> New >> Project. After selecting the project, a "New Project" dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as DemoTwitterAuth and press OK. 



After clicking on OK, a new dialog will open asking to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Web application(Model-View-Controller)” template. Click on "Change Authentication" button; a Change Authentication dialog box will open. Select “Individual User Account” and click OK. Now, click OK again to create your web app.

 

Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.

It will open the Package Manager Console. Put in Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations



Press F5 to run the application. You can see a home page as shown below.

 

Note the URL from the browser address bar. In this case, the URL is http://localhost:51763/. We need this URL to configure our Twitter App which we will be doing in the next section.

Create Twitter App

Before we start building our ASP.NET Core 2.0 application we need to create and configure the Twitter app so that we can use it to authenticate our application.

Navigate to https://apps.twitter.com/ and sign in using your existing Twitter account. If you do not have a Twitter account, you need to create one. You cannot proceed without a Twitter account. Once you have logged in, you will be redirected to Application Management page similar to the one shown below.

 

It will show all your Twitter Apps configured. Since I have already configured a Twitter App, so it is being displayed. If you are creating for the first time, it will not show anything. Click on “Create New App” button in the top right corner. It will open a form and ask to fill out the details to create a new app.

 

You can fill the form with the details as mentioned below.

  • Name
    Give any name of your choice. But it should be universally unique. This means no one should have used this name earlier for creating a Twitter app. This works same as Email id. Two people cannot have same Email id; similarly, two Twitter apps cannot have the same name. I am using the name “DemoTwitterAuth” for this tutorial. If you use an already existing name then you will get an error “The client application failed validation: <your entered name> is already taken for Name.”

  • Description
    Give an appropriate description.

  • Website
    Give your public website URL. But for this demo purpose, we will use a dummy URL http://demopage.com.

    Important Note
    If you use the URL format as www.demopage.com, you will get an error “The client application failed validation: Not a valid URL format.” Always use URL format as http://demopage.com

Accept the Developer agreement by clicking the checkbox and click on “Create your Twitter application” button. You will be redirected to your newly created Twitter app page and you can also see a success message as shown in the image below.

 

Navigate to “Keys and Access Tokens” tab and make a note of Consumer Key (API Key) and Consumer Secret (API Secret) field values. These values we will be using ASP.NET Core app.

The fields are masked in this image for security purpose. 

 
Our Twitter app has been created successfully.

Configure Web App to use Twitter authentication

We need to store Consumer Key (API Key) and Consumer Secret (API Secret) field values in our application. We will use Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key etc. for a .NET Core project during the development process. With the Secret Manager tool, we can associate app secrets with a specific project and can share them across multiple projects.

Open our web application once again and Right-click the project in Solution Explorer, and select Manage User Secrets from the context menu.

 

A secrets.json file will open. Put the following code in it.
  1. {  
  2.     "Authentication:Twitter:ConsumerKey""Your Consumer Key here",  
  3.     "Authentication:Twitter:ConsumerSecret""Your Consumer Secret here"  
  4. }  
Now open Startup.cs file and put the following code into ConfigureServices method.
  1. services.AddAuthentication().AddTwitter(twitterOptions => {  
  2.     twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
  3.     twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  
  4. });  

In this code section, we are reading ConsumerKey and ConsumerSecret for the authentication purpose. So finally, Startup.cs will look like this.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Identity;  
  7. using Microsoft.EntityFrameworkCore;  
  8. using Microsoft.AspNetCore.Hosting;  
  9. using Microsoft.Extensions.Configuration;  
  10. using Microsoft.Extensions.DependencyInjection;  
  11. using DemoTwitterAuth.Data;  
  12. using DemoTwitterAuth.Models;  
  13. using DemoTwitterAuth.Services;  
  14. namespace DemoTwitterAuth {  
  15.     public class Startup {  
  16.         public Startup(IConfiguration configuration) {  
  17.             Configuration = configuration;  
  18.         }  
  19.         public IConfiguration Configuration {  
  20.             get;  
  21.         }  
  22.         // This method gets called by the runtime. Use this method to add services to the container.  
  23.         public void ConfigureServices(IServiceCollection services) {  
  24.             services.AddDbContext < ApplicationDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  25.             services.AddIdentity < ApplicationUser, IdentityRole > ().AddEntityFrameworkStores < ApplicationDbContext > ().AddDefaultTokenProviders();  
  26.             services.AddAuthentication().AddTwitter(twitterOptions => {  
  27.                 twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
  28.                 twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  
  29.             });  
  30.             // Add application services.  
  31.             services.AddTransient < IEmailSender, EmailSender > ();  
  32.             services.AddMvc();  
  33.         }  
  34.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  35.         public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  36.             if (env.IsDevelopment()) {  
  37.                 app.UseBrowserLink();  
  38.                 app.UseDeveloperExceptionPage();  
  39.                 app.UseDatabaseErrorPage();  
  40.             } else {  
  41.                 app.UseExceptionHandler("/Home/Error");  
  42.             }  
  43.             app.UseStaticFiles();  
  44.             app.UseAuthentication();  
  45.             app.UseMvc(routes => {  
  46.                 routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
  47.             });  
  48.         }  
  49.     }  
  50. }  

And with this, our application is ready.

Launch the application and click "Login" in the top right corner of the homepage. You will be redirected to http://localhost:51763/Account/Login page, where you can see the option to login using Twitter on the right side of the page.

Clicking on the Twitter button will take you to Twitter authorization page where you will be asked to fill in your Twitter credentials and authorize the Twitter app to use your Twitter account.



Once you click on Authorize app, the application will take a few moments to authenticate your Twitter account and upon successful authentication, you will be redirected to a registration page inside your application where you need to fill in an email id to tag with your account.

 

Give an email id and click "Register". You will be redirected to homepage again but this time, you can also see your registered email is in the top right corner.

 
 
See Also

Conclusion

We have successfully created a Twitter app and used it to authenticate our ASP.NET Core application. I have attached the source code for your reference. Please note that secrets.json file contains dummy values. Hence, replace the values with the keys of your Twitter app before executing it.

Please let me know of your valuable feedbacks in the comment section below.