In this article, we are going to learn how to apply google base authentication in .Net 5.0
Let us understand with the help of an example.
We need ClientId and ClientSecret Key so this helps the login provider understand which application is requesting the authenticated user’s profile to provide user security.
First, you need to set up Google Cloud Console.
Next click on Select a project.
Then add New Project.
Next, provide the Project name as per your choices and click on Create button.
Then go to APIs & Services -> Credentials.
To generate Credentials click on Create Credentials and select OAuth client ID.
After clicking on Configure Consent Screen button and following the next steps.
Select User Type External and Click on Create button.
Next, fill out App Information like App name, Email, App logo, also provide your email on Developer contact information, and click on Save And Continue button.
Then again go to Credentials and click on create Credentials -> OAuth client Id and now you can see the following page.
Select your application type and provide your application URL in Authorized JavaScript Origins and provide this URL https://localhost:44344/signin-google in Authorized redirect URLs and then click on create button.
Then you get your Client ID and Client Secret.
Now let us Integrate Google Auth in .NET 5.0
Let us create a new project.
- Open visual studio 2019
- Create a new project.
- Select ASP.NET Core Web Application and Next.
- Provide a Project name and confirm or change the Location. Then click on Create.
- Select the latest version of ASP.NET Core in the drop-down ASP.NET Core 5.0.
- Under Authentication Type, select Change and set the authentication to Individual User Accounts. Then click on Create.
Once the project is created then add the following package.
Microsoft.AspNetCore.Authentication.Google
Then open the Startup.cs and add the following code to it.
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System.Security.Claims; using System.Threading.Tasks; namespace LoginWithGoogleDemo { 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.AddControllersWithViews(); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/account/GoogleResponse"; }); services.AddAuthentication() .AddGoogle(options => { IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google"); options.ClientId = "YourClientId"; options.ClientSecret = "YourClientSecret"; //this function is get user google profile image options.Scope.Add("profile"); options.Events.OnCreatingTicket = (context) => { var picture = context.User.GetProperty("picture").GetString(); context.Identity.AddClaim(new Claim("picture", picture)); return Task.CompletedTask; }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Account}/{action=Login}/{id?}"); }); } } }
Then add AccountController to your controller folder and then add the following code in it.
using LoginWithGoogleDemo.Models; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using System.Threading.Tasks; namespace LoginWithGoogleDemo.Controllers { public class AccountController : Controller { public IActionResult Login() { return View(); } public IActionResult GoogleLogin() { var properties = new AuthenticationProperties { RedirectUri = Url.Action("GoogleResponse") }; return Challenge(properties, GoogleDefaults.AuthenticationScheme); } public async Task<IActionResult> GoogleResponse() { string email = string.Empty; string firstName = string.Empty; string lastName = string.Empty; string profileImage = string.Empty; var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme); //get google login user infromation like that. if (result.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { email = result.Principal.FindFirstValue(ClaimTypes.Email); } if (result.Principal.HasClaim(c => c.Type == ClaimTypes.GivenName)) { firstName = result.Principal.FindFirstValue(ClaimTypes.GivenName); } if (result.Principal.HasClaim(c => c.Type == ClaimTypes.GivenName)) { lastName = result.Principal.FindFirstValue(ClaimTypes.Surname); } if (result.Principal.HasClaim(c => c.Type == "picture")) { profileImage = result.Principal.FindFirstValue("picture"); } UserInfoVM userInfo = new UserInfoVM() { email = email, firstName = firstName, lastName = lastName, profileImage = profileImage }; return Json(userInfo); } } }
With the GoogleResponse method, we collect exactly that – external login info. So the information like provider, given name, last name, email, name identifier, profile image, etc, are going to be provided in the info variable.
Create Login.cshtml and add the following code to it.
@{ ViewData["Title"] = "Login"; Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="row"> <div class="col-sm-12"> <div class="justify-content-center"> <form asp-action="GoogleLogin" asp-controller="Account"> <h4 class="text-center margin-top">Login With Google Account</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <input type="text" hidden="hidden" name="returnUrl" value="/Home/Privacy" class="currenctURL1" id="currentURL1" /> <input type="submit" value="Login With Google" class="btn btn-success" /> </form> </div> </div> </div>
That’s it.
Output
Also check ,Get Hosted Page And Payment Using Authorize.Net