In this article, we are going to implement Blazor WebAssembly cookie authentication with Twitter(external login provider).
Click here for Part-2 Blazor WebAssembly Cookie Authentication With Facebook
Step3:
Step4:
Click here for Part-2 Blazor WebAssembly Cookie Authentication With Facebook
Install Twitter NuGet In API Project:
Let's install the Twitter authentication library into the API project.
.NET CLI Command:
dotnet add package Microsoft.AspNetCore.Authentication.Twitter --version 6.0.3
dotnet add package Microsoft.AspNetCore.Authentication.Twitter --version 6.0.3
Package Manager:
Install-Package Microsoft.AspNetCore.Authentication.Twitter -Version 6.0.3
Install-Package Microsoft.AspNetCore.Authentication.Twitter -Version 6.0.3
Register API With Twitter:
To enable twitter authentication to our application we have to register our API with Twitter. So following are steps to register with Twitter.
Step1:
Register with 'Twitter Developers' section and then navigate to the dashboard page https://developer.twitter.com/en/portal/dashboard.
Step2:
Click 'Create Project' on the dashboard page.
Specify Project Name, then click on the 'Next' button.
Select any use case in the dropdown
Step5:
Specify project description.
Step6:
Now we need to 'APP' under the project we just created above.
Step7:
Choose APP environment and then click the 'Next' button.
Choose APP environment and then click the 'Next' button.
Step8:
Specify App Name.
Step9:
In the 'Keys & Tokens' tab copy and store the 'API Key' and 'API Key Secret' we will use them in our API project, then next click on the 'App settings' button.
Step 10:
Now in our 'APP' click on the 'Set up' button in the 'User Authentication Settings' card.
Now in our 'APP' click on the 'Set up' button in the 'User Authentication Settings' card.
Step11:
Now configure the User Authentication Settings. Enable OAuth 1.0 & 2.0
Select 'Type Of App' to 'WebApp'. Enable 'Request email from users'. (This email permission must be enabled if we want to get user email from the authentication).
Now configure 'General Authentication Settings'.
- Add the 'Callback URL/Redirect URL', so here we can add our localhost URL with a mandatory path '/signin-twitter'(eg https://localhsot:12445/signin-twitter).
- Add the 'Website URL', 'Terms of service', 'Privacy policy' here all these three fields will not accept the localhost URL, but we can assign real free domains like either 'blogspot' or 'wordpress'.
Add Twitter Settings To API Project:
In our API project let's configure the Twitter setting into the 'appsettings.Development.json'.
API_Project/appsettings.Development.json:
"TwitterSettings":{ "ApiKey":"0000000000", "ApiKeySecret":"000000000" }
Register Twitter Service To API Project:
Let's register the Twitter service into the API project.
API_Project/Program.cs
builder.Services.AddAuthentication(
CookieAuthenticationDefaults.AuthenticationScheme
)
.AddCookie()
.AddFacebook(fb => {
// code hidden for display purposeImplement Twitter Authentication Logic In API Project:
})
.AddTwitter(tt => {
tt.ConsumerKey = builder.Configuration
.GetSection("TwitterSettings").GetValue<string>("ApiKey");
tt.ConsumerSecret = builder.Configuration
.GetSection("TwitterSettings").GetValue<string>("ApiKeySecret");
tt.RetrieveUserDetails = true;
});
- (Line: 10&13) Configure 'Apikey', 'ApiKeySecret' from the Twitter dashboard.
- (Line: 14) Enable 'RetrieveUserDetails' to fetch the email from the Twitter authentication.
Implement Twitter Authentication Logic In API Project:
Let's implement the 'TwitterLogin' action method.
API_Project/Controllers/AuthController.cs:
[HttpGet] [Route("twitter-login")] public IActionResult TwitterLogin(string returnURL) { return Challenge( new AuthenticationProperties { RedirectUri = Url.Action(nameof(TwitterLoginCallback), new { returnURL }) }, TwitterDefaults.AuthenticationScheme ); }
- (Line: 3) The 'returnURL' is a Blazor Webassembly application URL.
- (Line: 5-11) The 'Challenge' method to invoke the external login providers. Here we configured the 'Twitter' authentication. Here 'RedirectUri' is configured with the 'TwitterLoginCallback' action method.
API_Project/Controllers/AuthController.cs:
[HttpGet] [Route("twitter-login-callback")] public async Task<IActionResult> TwitterLoginCallback(string returnURL) { var authenticationResult = await HttpContext .AuthenticateAsync(TwitterDefaults.AuthenticationScheme); if (authenticationResult.Succeeded) { string email = HttpContext .User.Claims.Where(_ => _.Type == ClaimTypes.Email) .Select(_ => _.Value) .FirstOrDefault(); string firstName = HttpContext .User.Claims.Where(_ => _.Type == ClaimTypes.Name) .Select(_ => _.Value) .FirstOrDefault(); var user = await ManageExternalLoginUser( email, firstName, string.Empty, "Twitter" ); await RefreshExternalSignIn(user); return Redirect($"{returnURL}?externalauth=true"); } return Redirect($"{returnURL}?externalauth=false"); }
- (Line: 3) The 'returnURL' is our Blazor WebAssembly application URL.
- (Line: 5-6) Fetching authentication status of Twitter.
- (Line: 9-17) On successful authentication, an initial cookie will be created by ours.NET6 framework with Facebook claims. Here we fetching claims like 'email', and 'name' from Twitter.
- (Line: 19-24) The 'ManagerExternalLoginUser' is a common method for our external login click here to know more about this method implementation
- (Line: 26) The 'RefreshExternalSign()' is a common method where we remove the default cookie and create a new cookie with our database user information click here to know more about this method implementation.
- (Line: 27) Redirecting to Blazor WebAssembly application with query parameter 'externalauth=true'.
- (Line: 29) If Twitter authentication fails then redirect to Blazor Webassembly application with query parameter 'externalauth=false'.
Add Twitter Login Link In Blazor WebAssembly Application:
In 'Login.razor' let's add the Twitter login link.
Blazor_Wasm/Pages/Login.razor:
<div class="row"> <div class="col-md-6 offset-md-3"> <div> <a href="https://localhost:7235/auth/twitter-login?returnurl=https://localhost:7218/" class="nav-link btn btn-link"> Twitter </a> </div> <!-- code hidden for display purpose --> </div> </div>
- (Line: 4-5) Configured the 'Twitter' login API and add our Blazor WebAssembly URL as a query parameter.
Hopefully, I think this article delivered some useful information about Blazor WebAssembly Cookie Authentication Using Twitter. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Refer:
Part-1 Blazor WebAssembly Cookie Authentication[.NET 6]
Part-2 Blazor WebAssembly Cookie Authentication With Facebook
Part-2 Blazor WebAssembly Cookie Authentication With Facebook
Blazor Server (Not WASM) Examples: How does any of this change if using Blazor Server vice WebAssembly?
ReplyDelete