In this article, we are going to implement Blazor WebAssembly cookie authentication using Google.
Part-4 Blazor WebAssembly Cookie Authentication With Microsoft Account
Install Google Authentication NuGet In API Project:
Let's install the Google Authentication NuGet package into our API Project
.NET CLI Command:
dotnet add package Microsoft.AspNetCore.Authentication.Google --version 6.0.3
dotnet add package Microsoft.AspNetCore.Authentication.Google --version 6.0.3
Package Manager:
Install-Package Microsoft.AspNetCore.Authentication.Google -Version 6.0.3
Install-Package Microsoft.AspNetCore.Authentication.Google -Version 6.0.3
Register API With Google:
We need to register the API project with Google to enable Google authentication. So following are the registration steps with Google.
Step1:
Goto 'Google APIs&Services' at 'https://console.cloud.google.com/projectselector2/apis/dashboard'
Step2:
Step2:
Click the 'Create Project' button.
Stpe3:
Now define the project name and then click on the 'Create' button.
Step4:
On creating a project successfully, we can observe it as a selected project in our dashboard like below.
Step5:
Select 'OAuth Consent Screen' left side menu, next select the 'User Type' let select the 'External' option.
Step6:
Need to configure App under the project.
- Define 'App Name' and 'User support email'.
- Define the 'Developer Contact Information'.
Step7:
In 'Scopes' click on 'Add OR Remove Scopes' and then select 'email', 'profile', 'openid' scopes.
Step8:
Configure test email address which can only authenticate with our app for development.
Step9:
In summary, the tab clicks on the 'Back To Dashboard'.
Step10:
Select 'Credentials' left menu, then click on the 'Create Credentials' button, and then select 'OAuth Client ID'
Step10:
Now configure 'Create OAuthClient ID'
- Select 'Application Type' to 'Web applicaiton'. Define the client's name.
- Add 'Redire URL' which is our API domain with the default path 'singin-google'.
Step11:
Now save the 'Client Secret' and 'Client Id' which we use in our API project.
Add Google Auth Settings In API Project:
Let's add Google 'Client Id' and 'Client Secret' into our 'appsettings.Development.json' file.
API_Project/appsettings.Development.json:
"GoogleSettings":{ "ClientId":"00000000", "ClientSecret":"000000000" }
Register Google Service In API Project:
Let's register our Google authentication service into the 'Program.cs'
API_Project/Program.cs:
// code hidden for display purpose builder.Services.AddAuthentication( CookieAuthenticationDefaults.AuthenticationScheme ) .AddCookie() .AddFacebook() .AddTwitter() .AddMicrosoftAccount(). AddGoogle(g => { g.ClientId = builder.Configuration .GetSection("GoogleSettings").GetValue<string>("ClientId"); g.ClientSecret = builder.Configuration .GetSection("GoogleSettings").GetValue<string>("ClientSecret"); });
Implement Google Authentication Login In API Project:
Let's implement the 'GoogleLogin' action method.
API_Project/Controllers/AuthController.cs:
[HttpGet] [Route("google-login")] public IActionResult GoogleLogin(string returnURL) { return Challenge( new AuthenticationProperties { RedirectUri = Url.Action(nameof(GoogleLoginCallBack), new { returnURL }) }, GoogleDefaults.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 'Google' authentication. Here 'RedirectUri' is configured with the 'GoogleLoginCallBack' action method that gets executed on successful authentication with the Google account.
API_Project/Controllers/AuthController.cs:
[HttpGet] [Route("google-login-callback")] public async Task<IActionResult> GoogleLoginCallBack(string returnURL) { var authenticationResult = await HttpContext .AuthenticateAsync(GoogleDefaults.AuthenticationScheme); if (authenticationResult.Succeeded) { string email = HttpContext .User.Claims.Where(_ => _.Type == ClaimTypes.Email) .Select(_ => _.Value) .FirstOrDefault(); string firstName = HttpContext .User.Claims.Where(_ => _.Type == ClaimTypes.GivenName) .Select(_ => _.Value) .FirstOrDefault(); string lastName = HttpContext .User.Claims.Where(_ => _.Type == ClaimTypes.Surname) .Select(_ => _.Value) .FirstOrDefault(); var user = await ManageExternalLoginUser( email, firstName, lastName, "Google" ); 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 Google account.
- (Line: 9-22) On successful authentication, an initial cookie will be created by our API with Google account claims. Here we fetching claims like 'email', 'givenname', 'surname'.
- (Line: 24-29) The 'ManageExternalLoginUser' is a common method for our external login click here to know more about this method implementation.
- (Line: 31) The 'RefreshExternalSignIn()' is a common method where we remove the default auth cookie and create a new auth cookie with our database user information. Click here to know more about this method of implementation.
- (Line: 32) Redirecting to Blazor WebAssembly application with query parameter 'externalauth=true'.
- (Line: 34) If Google authentication fails then redirect to the Blazor WebAssembly application with the query parameter 'externalauth=false'.
Add Google Login Link In Blazor WebAssembly Project:
In 'Login.razor' add the Google login link.
BlazorWasm_Project/Pages/Login.razor:
<div class="row"> <div class="col-md-6 offset-md-3"> <div> <a href="https://localhost:7235/auth/google-login?returnurl=https://localhost:7218/" class="nav-link btn btn-link"> Google </a> </div> </div> </div>
- Configure the 'Google' login API and added our Blazor WebAssembly URL as a query parameter.
Step1:
Step2:
Step3:
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information about Blazor WebAssembly Cookie Authentication Using Google Account. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Hi, I wonder if it is possible to retrieve google token at client level in your solution. What I would like to achieve is to get google token and send it to API and then release own token with custom claims. Thanks
ReplyDelete