Asp.Net Core External Login Providers Google Complete Guide
Understanding the Core Concepts of ASP.NET Core External Login Providers Google
Explanation and Important Information on ASP.NET Core External Login Providers: Google
Setting Up Google as an External Login Provider in ASP.NET Core
Google Developer Console:
Create a New Project:
- Go to the Google Developer Console.
- Click on "Create Project" and name it accordingly.
- Wait for the project to be created and proceed to the next step.
Enable Google+ API:
- Navigate to the Dashboard and find the ‘Library’ section.
- Click on "Enable APIs and Services."
- Search for "Google+ API," click on it, and then click "Enable."
Note: Google is phasing out the Google+ API, so you might need to use OAuth 2.0 directly for Google Sign-In.
Create OAuth 2.0 Credentials:
- In the Developer Console, go to the ‘Credentials’ section.
- Click on "Create Credentials" and select "OAuth client ID."
- Set the application type to "Web application."
- In the "Authorized redirect URIs," add a URL like
https://yourappdomain.com/signin-google
andhttp://localhost:port/signin-google
for local testing.
Install Required NuGet Packages:
- Open the NuGet Package Manager and install
Microsoft.AspNetCore.Authentication.Google
by running the command:Install-Package Microsoft.AspNetCore.Authentication.Google
- Open the NuGet Package Manager and install
Configure Google Authentication in ASP.NET Core:
- Open the
appsettings.json
file and add the Google OAuth configuration:"Authentication": { "Google": { "ClientId": "YOUR_CLIENT_ID_FROM_GOOGLE", "ClientSecret": "YOUR_CLIENT_SECRET_FROM_GOOGLE" } }
- In the
Startup.cs
file, add Google authentication to theConfigureServices
method:services.AddAuthentication() .AddGoogle(options => { IConfigurationSection googleAuthNSection = Configuration.GetSection("Authentication:Google"); options.ClientId = googleAuthNSection["ClientId"]; options.ClientSecret = googleAuthNSection["ClientSecret"]; options.SaveTokens = true; // Optionally save tokens in user cookies for subsequent requests });
- Open the
Register and Login with Google:
- Modify the account management views in your application to allow users to log in with their Google accounts.
- Use the provided authentication middleware to handle the sign-in and sign-out processes seamlessly.
Important Configuration Details
- Scopes: You can specify additional data to request from Google during the authentication process by adding scopes, such as user profile and email.
- Callback Path: Ensure that the callback path in your code matches the ones you configured in the Google Developer Console.
- Consent Screen: Configure the consent screen in the Google Developer Console to describe the application’s use of Google account details.
Handling Sign-In and Sign-Out
- Sign-In: When a user clicks the Google sign-in button, redirect them to Google’s authorization server.
- Callback: After Google authenticates the user, they will be redirected back to your application’s callback endpoint.
- Token Exchange: Exchange the authorization code for tokens to retrieve the user’s profile information.
- Sign-Out: Implement a sign-out method that logs the user out of both your application and optionally from Google.
Security Best Practices
- HTTPS: Always use HTTPS to protect user data during the sign-in process.
- Token Validation: Validate all tokens received from Google to prevent security vulnerabilities.
- User Consent: Ensure that users explicitly consent to sharing their data with your application during the OAuth flow.
Online Code run
Step-by-Step Guide: How to Implement ASP.NET Core External Login Providers Google
Step 1: Create a New ASP.NET Core Project
- Open Visual Studio.
- Create a new project:
- Select ASP.NET Core Web App (Model-View-Controller)
- Click Next.
- Configure your project:
- Name your project, for example:
GoogleAuthExample
. - Choose a location if needed.
- Click Create.
- Name your project, for example:
- Configure your new project:
- Ensure .NET 6.0 (Long Term Support) or a later version is selected.
- Check Enable Docker Support if you want.
- Uncheck Enable HTTPS for simplicity or keep it if you prefer.
- Click Create.
Step 2: Register Your Application in Google Developer Console
- Go to the Google Developer Console.
- Create a new project:
- Click Select a project at the top.
- Click NEW PROJECT.
- Enter a name for your project.
- Click Create.
- Configure the OAuth consent screen:
- On the left sidebar, click OAuth consent screen.
- Select External if you're building it for external users.
- Click Create.
- Fill in the required fields (App name, etc.).
- Click Save and continue.
- Create Credentials:
- On the left sidebar, click Credentials.
- Click Create Credentials > OAuth client ID.
- Under Application type, select Web application.
- Enter a name for your application.
- Under Authorized redirect URIs, add:
https://localhost:5001/signin-google
(usehttp://localhost:5000/signin-google
if you didn't enable HTTPS). - Click Create.
- Note down the Client ID and Client Secret.
Step 3: Configure Google Authentication in ASP.NET Core
Install the necessary NuGet package:
- Open the Package Manager Console.
- Run:
Install-Package Microsoft.AspNetCore.Authentication.Google
.
Configure the Google Authentication middleware:
- Open
appsettings.json
and add the Google Client ID and Client Secret:{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-GoogleAuthExample-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX;Trusted_Connection=True;MultipleActiveResultSets=true" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Authentication": { "Google": { "ClientId": "YOUR_GOOGLE_CLIENT_ID", "ClientSecret": "YOUR_GOOGLE_CLIENT_SECRET" } } }
- Open
Configure services and middleware in
Program.cs
:- Open
Program.cs
. - Add Google Authentication before
app.UseAuthorization()
:var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.ConfigureApplicationCookie(options => { options.LoginPath = "/Account/Login"; }); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme; }) .AddCookie() .AddGoogle(options => { builder.Configuration.Bind("Authentication:Google", options); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run();
- Open
Step 4: Create Controllers and Views for Account Management
Add an
AccountController
:- Right-click on the
Controllers
folder and select Add > Controller. - Select MVC Controller - Empty and name it
AccountController
. - Add the following code to
AccountController.cs
:using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.Google; using Microsoft.AspNetCore.Mvc; namespace GoogleAuthExample.Controllers { public class AccountController : Controller { public IActionResult Login() { return View(); } public IActionResult Logout() { return SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } public IActionResult AccessDenied() { return View(); } } }
- Right-click on the
Create Views for Login, Logout, and AccessDenied:
- Right-click on
Account
underViews
and select Add > New Folder and name itAccount
. - Right-click on the
Account
folder, select Add > Razor View.- Create three views:
Login.cshtml
,Logout.cshtml
,AccessDenied.cshtml
(you can leave them empty for simplicity).
- Create three views:
- Right-click on
Modify the
Login
view to include a button for Google Login:- Open
Login.cshtml
and add the following code:@{ ViewData["Title"] = "Login"; } <h1>@ViewData["Title"]</h1> <p>Use a google account to log in</p> <form asp-controller="Account" asp-action="ExternalLogin" asp-route-provider="Google" method="post"> <button type="submit" style="margin-top: 1em;" class="btn btn-default">Log in with Google</button> </form>
- Open
Modify
AccountController
to handle the external login:- Open
AccountController.cs
and add the following methods:public IActionResult ExternalLogin(string provider, string returnUrl = null) { var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true); if (result.Succeeded) { return LocalRedirect(returnUrl); } else { return RedirectToAction(nameof(Login)); } }
- Open
Step 5: Test the Application
- Run the application:
- Press F5 or click the run button in Visual Studio.
- Navigate to
/Account/Login
:- You should see a page with a button to log in with Google.
- Click the button:
- You will be redirected to the Google login page.
- After logging in, you should be redirected back to your application.
Summary
In this guide, you've learned how to set up external authentication with Google in an ASP.NET Core application. You created an ASP.NET Core MVC application, registered your application in the Google Developer Console, and configured Google authentication in your ASP.NET Core application. This setup allows users to log in using their Google accounts.
Login to post a comment.