DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Authentication Using Twitter in ASP.NET Core 2.0

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!

Ankit Sharma user avatar by
Ankit Sharma
·
Feb. 19, 18 · Tutorial
Like (4)
Save
Tweet
Share
6.64K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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.

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 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 {  
            get;  
        }  
        // 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 > ();  
            services.AddMvc();  
        }  
        // 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()) {  
                app.UseBrowserLink();  
                app.UseDeveloperExceptionPage();  
                app.UseDatabaseErrorPage();  
            } else {  
                app.UseExceptionHandler("/Home/Error");  
            }  
            app.UseStaticFiles();  
            app.UseAuthentication();  
            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.

Conclusion

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.

twitter ASP.NET ASP.NET Core app authentication Web application .NET

Published at DZone with permission of Ankit Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Concurrency: LockSupport
  • Tackling the Top 5 Kubernetes Debugging Challenges
  • MongoDB Time Series Benchmark and Review
  • Best Practices for Setting up Monitoring Operations for Your AI Team

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: