avatarM. Ramadhan

Summary

The web content provides a comprehensive guide on integrating Twitter authentication into a Blazor Server application, enabling users to sign in using their Twitter accounts.

Abstract

The article "Blazor Server Project #18: How to Configure Twitter Authentication" serves as a practical tutorial for developers looking to implement Twitter sign-in functionality within their Blazor Server web applications. It outlines the necessary steps, starting with creating an application in the Twitter developer portal, installing the Twitter authentication middleware via NuGet, and securely storing the Twitter client ID and secret. The guide also covers configuring Twitter authentication in the Startup.cs file, modifying the login and registration pages to include Twitter as an authentication option, and testing the sign-in process. The article emphasizes the importance of handling different user types, including unregistered users and those with varying roles, and ensures compliance with the application's authorization specifications.

Opinions

  • The author believes that integrating Twitter authentication is straightforward for those with experience in C#, HTML, CSS, and SQL.
  • The article suggests that the process of setting up Twitter authentication is similar to that of Google and Facebook, as seen in previous articles in the series.
  • The author values the security of the application, emphasizing the use of the secrets.json file to store sensitive information like API keys and secrets.
  • The guide is designed to be practical and hands-on, providing step-by-step instructions, screenshots, and code snippets for developers to follow.
  • The author encourages feedback, indicating a willingness to engage with the developer community and improve the guide based on user experience.

Blazor Server Project #18: How to Configure Twitter Authentication

A practical guide to integrating Twitter Sign-In into your web app, allowing users to log in using their Twitter account.

Table of Contents

OverviewCreate the app in TwitterInstall Twitter Authentication MiddlewareStore the Twitter Client ID and SecretConfigure Twitter AuthenticationModify the Login and Register PageSign in with TwitterSummaryReferences

This article is the eighteenth in a series covering the Blazor Server Project: (1) How to create a CRUD operation using Dapper (2) Building a dropdown list involves a 1:N relationship (3) How to implement a checkbox list involving an M:N relationships (4) Understanding URL routing and navigation (5) Creating and using page layout (6) How to create a reusable modal dialog component (7) Practical guide to making a master-detail page (8) Master-detail page using dynamic query (9) How to avoid SQL injection attacks (10) Hiding/showing HTML elements (11) Migrate to ASP.NET Core 6.0 (12) Installing ASP.NET Core Identity (13) Integrating Identity tables into the existing project database (14) Authentication and authorization (15) Role-based authorization (16) How to implement Google Authentication (17) Facebook Authentication and Authorization (18) How to configure Twitter Authentication (19) How to Customize Password Policy (20) Account Lockout Policy

These articles are for anyone who wants to learn how to build Blazor Server applications in a practical approach through some sample projects. It will be straightforward if you have some experience with C#, HTML, CSS, and SQL.

Overview

In the previous article, Blazor Server Project #16, we implemented authentication using Google OAuth 2.0; in Blazor Server Project #17, we discussed enabling users to sign in with their Facebook account. For now, we cover how to apply authentication by integrating Twitter Sign-In into your web app so users can log in using their Twitter accounts. The steps are: ▸ Create the app in Twitter ▸ Install Twitter Authentication Middleware ▸ Store the Twitter consumer API key and secret ▸ Configure Twitter Authentication ▸ Sign in with Twitter

Create the app in Twitter

Figure 1 Signing in to Twitter
  • You can sign in with your Google or Apple account, phone, email, or username.
Figure 2 Entering the password
  • Enter your password and log in.
Figure 3 Filling out the required fields
  • Fill out the required fields and click the Let's do this button.
Figure 4 Developer agreement
  • Check the Accept Terms & Conditions checkbox and click the Submit button.
Figure 5 Sending email verification
  • Twitter will send an email verification.
  • Open your email to verify.
Figure 6 Email verification
  • Click the Confirm your email button.
Figure 7 Naming the app
  • Enter the app name. Take it easy; you can always change it later.
  • Click the Get keys button.
Figure 8 API key, API key secret, and bearer token
  • Save the keys. Your keys should differ from mine in Figure 8 above.
  • Click the Dashboard button
Figure 9 Saving the keys
  • If you have not saved the keys, save them now.
  • Click the Yes, I saved them button.
Figure 10 Dashboard
  • Click the gear ⛭ (App settings) button.
Figure 11 App details
  • You may click the Edit button to: - rename the app - upload the app icon - enter the description
  • Click the Set up button to set the user authentication.
Figure 12 App permission and type
  • Select Read and enable Request email from users in the App permissions section.
  • Select WebApp, Automated App or Bot as the type of app.
  • Scroll down.
Figure 13 App info
  • Type https://localhost:44333/signin-twitter as Callback URI during development.
  • Enter your Website URL.
  • Enter links to your terms of service and privacy policy.
  • Click the Save button.
Figure 14 Client ID and secret
  • Save the Client ID and secret. Your Client ID and secret should differ from mine in Figure 14 above.
  • Click Done.

Install Twitter Authentication Middleware

You have to install Microsoft.AspNetCore.Authentication.Twitter NuGet package in the project.

This project is a continuation of the Blazor Server Project #17. If you don't have the project, you can download it via the link below.

  • Open the project in Visual Studio 2022.
  • Select Tools > NuGet Package Manager > Manage NuGet Packages Solution… from the menu, and the NuGet Solution dialog appears.
Figure 15 NuGet package manager dialog
  • Select Browse.
  • Type twitter in the Search box
  • Click Microsoft.AspNetCore.Authentication.Twitter from the package list, check checkboxes, and select Install.
  • In the Preview Changes window, click OK to proceed with the installation and click I Accept to accept the license.

Store the Twitter Client ID and Secret

  • Right-click the BookApp project in the Solution Explorer pane.
  • From the context menu, click Manage User Secrets to open the secrets.json file.
  • Please copy the following code and paste it into the file.

Listing 1 The contents of the secrets.json file

{
   "Authentication:Google:ClientId": "Your Google ClientId",
   "Authentication:Google:ClientSecret": "Your Google ClientSecret",
   "Authentication:Facebook:AppId": "Your Facebook AppId",
   "Authentication:Facebook:AppSecret": "Your Facebook AppSecret",
   "Authentication:Twitter:ConsumerAPIKey": "<API-key>",
   "Authentication:Twitter:ConsumerSecret": "<API-key-secret>"
}
  • Replace <API-key> and <API-key-secret> with yours.
  • Save the file. Visual Studio saves it in the file system path: %APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

Configure Twitter Authentication

Add the following code into Startup.cs file to configure Twitter Authentication.

Listing 2 The contents of the modified Startup.cs file

...
   //Google Authentication service         
   ...
   //Facebook Authentication service
   ...
   //Twitter Authentication service
   services.AddAuthentication().AddTwitter(twitterOptions =>
   {
      twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerAPIKey"];
      twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
   });
...

The application uses the AddTwitter() method to read the ConsumerAPIKey and ConsumerSecret from the secrets.json file.

Modify the Login and Register Page

Modify the Login.cshtml file to make the Login button more readable, as shown in Figure 16.

Figure 16 Modified Login page

Listing 3 The contents of the modified Login.cshtml file

...
   @foreach (var provider in Model.ExternalLogins)
   {
      <button type="submit"
         ...
         Log in with @provider.DisplayName
      </button>
      <br /><br />
   }
...

And so do Register.cshtml file.

Figure 17 Modified Register page

Listing 4 The contents of the modified Register.cshtml file

...
   @foreach (var provider in Model.ExternalLogins)
   {
      <button type="submit"
         ...
         Register with @provider.DisplayName
      </button>
      <br /><br />
   }
...

Sign in with Twitter

For now, the app allows the following: ⦁ unregistered users ⦁ registered users with no role ⦁ registered users with one role or more to sign in using their Twitter account.

You can test authentication and authorization, like in the previous articles, Blazor Server Project #16 and Blazor Server Project #17.

The following page appears when users try registering or logging in using their Twitter account.

Figure 18 Permission to access the user account
  • The user can click Authorize app to allow or Cancel to deny.

Summary

Like on Google and Facebook Authentication, by integrating Twitter Sign-In into your web app, any user — unregistered users, registered users with no role, one or more — can sign in using their Twitter accounts. Their authorization is compliant with the specifications in the app.

Hopefully beneficial. Your feedback will be precious.

References

Blazor
Authentication
Authorization
Twitter
Sign In
Recommended from ReadMedium