How to Login With Twitter in ASP.NET Core Identity

In this article, we will learn how to login with Twitter in ASP.NET Core Identity

Create a new Twitter App

First Go to apps.twitter.com and click on Sign In. Log in using your personal Twitter credentials.

Twitter

If this is your first time creating an App on Twitter. You will see a button to “Create an app”

Create Twitter App

Now Create ASP.NET Core Identity Project

First you need to install the package called Microsoft.AspNetCore.Authentication.Twitter from NuGet.

Next, go to your Startup.cs file, and inside it’s ConfigureServices() method, set up the Twitter Authentication Service and provide the OAuth credentials you got from the Twitter Project before.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppIdentityDbContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
    services.AddIdentity<AppUser, IdentityRole>().AddEntityFrameworkStores<AppIdentityDbContext>().AddDefaultTokenProviders();
 
    services.AddAuthentication()
    .AddTwitter(twitterOptions => {
                twitterOptions.ConsumerKey = "Your Twitter Consumer Key";
                twitterOptions.ConsumerSecret = "Your Twitter Consumer Secret";
                twitterOptions.RetrieveUserDetails = true;
            });
 
    services.AddControllersWithViews();
}

View Page

<h1 class="bg-info text-white">Login</h1>
<div class="text-danger" asp-validation-summary="All"></div>
 
<form asp-action="Login" method="post">
    <input type="hidden" asp-for="ReturnUrl" />
    <div class="form-group">
        <label asp-for="Email"></label>
        <input asp-for="Email" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Password"></label>
        <input asp-for="Password" class="form-control" />
    </div>
    <button class="btn btn-primary" type="submit">Log In</button>
    <a class="btn btn-info" asp-action="TwitterLogin">Log In With Twitter</a>
</form>

The new link targets the TwitterLogin action on the Account controller. You can see this action along with the changes I made to the Account controller (code is given below). Basically I added 2 method which are TwitterLogin & TwitterResponse.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Identity.Models;
using System.Threading.Tasks;
using System.Security.Claims;
 
namespace Identity.Controllers
{
    public class AccountController : Controller
    {
        private UserManager<AppUser> userManager;
        private SignInManager<AppUser> signInManager;
 
        public AccountController(UserManager<AppUser> userMgr, SignInManager<AppUser> signinMgr)
        {
            userManager = userMgr;
            signInManager = signinMgr;
        }
 
        // other methods
 
        public IActionResult AccessDenied()
        {
            return View();
        }
 
        [AllowAnonymous]
        public IActionResult TwitterLogin()
        {
            string redirectUrl = Url.Action("TwitterResponse", "Account");
            var properties = _signInManager.ConfigureExternalAuthenticationProperties("Twitter", redirectUrl);
            return new ChallengeResult("Twitter", properties);
        }
 
        [AllowAnonymous]
        public async Task<IActionResult> TwitterResponse()
        {
            ExternalLoginInfo info = await signInManager.GetExternalLoginInfoAsync();
            if (info == null)
                return RedirectToAction(nameof(Login));
 
            var result = await signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false);
            string[] userInfo = { info.Principal.FindFirst(ClaimTypes.Name).Value, info.Principal.FindFirst(ClaimTypes.Email).Value };
            if (result.Succeeded)
                return View(userInfo);
            else
            {
                AppUser user = new AppUser
                {
                    Email = info.Principal.FindFirst(ClaimTypes.Email).Value,
                    UserName = info.Principal.FindFirst(ClaimTypes.Email).Value
                };
 
                IdentityResult identResult = await userManager.CreateAsync(user);
                if (identResult.Succeeded)
                {
                    identResult = await userManager.AddLoginAsync(user, info);
                    if (identResult.Succeeded)
                    {
                        await signInManager.SignInAsync(user, false);
                        return View(userInfo);
                    }
                }
                return AccessDenied();
            }
        }
    }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories