Over a million developers have joined DZone.

Authentication Using Twitter in ASP.NET Core 2.0

DZone's Guide to

Authentication Using Twitter in ASP.NET Core 2.0

In this post, we examine how to use Twitter as a means of adding an authentication mechanism to your web application. Let's get started!

· Security Zone ·
Free Resource

Secure and manage your open source software with Flexera.


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


  • 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 the available project types. Put the name of the project as DemoTwitterAuth and press OK.

After clicking on OK, a new dialog will open asking you to select the project template. You will see 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 the "Web application(Model-View-Controller)" template. Click on the "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 the Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.

Press F5 to run the application. You should see the page 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 a 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 the Twitter Apps you have configured. Since I have already configured a Twitter App, it is being displayed. If you are creating a Twitter app for the first time, it will not show anything. Click on the "Create New App" button in the top right corner. It will open a form and ask you to fill out the details to create a new app.

You can fill in the form with the details 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 the same as an email id. Two people cannot have the 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 www.demopage.com, you will get an error “The client application failed validation: Not a valid URL format.” Always use the URL format http://demopage.com
  • Callback URL
    Give the base URL of your application with /signin-twitter appended to it. For this tutorial, the URL will be http://localhost:51763/signin-twitter

Accept the Developer agreement by clicking the checkbox and click on the "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 purposes.

Our Twitter app has been created successfully.

Configure Our Web App to Use Twitter Authentication

We need to store the 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.

    "Authentication:Twitter:ConsumerKey": "Your Consumer Key here",  
    "Authentication:Twitter:ConsumerSecret": "Your Consumer Secret here"  

Now open the Startup.cs file and put the following code into the ConfigureServices method.

services.AddAuthentication().AddTwitter(twitterOptions => {  
    twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
    twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  

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

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Identity;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using DemoTwitterAuth.Data;  
using DemoTwitterAuth.Models;  
using DemoTwitterAuth.Services;  
namespace DemoTwitterAuth {  
    public class Startup {  
        public Startup(IConfiguration configuration) {  
            Configuration = configuration;  
        public IConfiguration Configuration {  
        // This method gets called by the runtime. Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services) {  
            services.AddDbContext < ApplicationDbContext > (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
            services.AddIdentity < ApplicationUser, IdentityRole > ().AddEntityFrameworkStores < ApplicationDbContext > ().AddDefaultTokenProviders();  
            services.AddAuthentication().AddTwitter(twitterOptions => {  
                twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];  
                twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];  
            // Add application services.  
            services.AddTransient < IEmailSender, EmailSender > ();  
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
            if (env.IsDevelopment()) {  
            } else {  
            app.UseMvc(routes => {  
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  

And with this, our application is ready.

Execution Demo

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 the 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 the homepage again, but, this time, you can also see your registered email is in the top right corner.


We have successfully created a Twitter app and used it to authenticate our ASP.NET Core application.

You can get the source code from GitHub.

Please note that in the source code, the secrets.json file contains dummy values. Hence, replace the values with the keys of your Twitter app before executing it.

You can check my other articles on ASP .NET Core here.

Security vulnerabilities put your data and your customer’s data at risk. Find out how FlexNet Code Insight integrates into your SDLC and makes monitoring open source security a breeze, so you can worry less and build more.  Brought to you in partnership with Flexera.

security ,authentication ,web application security

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}