Google OAuth Login in ASP.NET Core: A Step-by-Step Guide
Implementing Google OAuth authentication into ASP.NET Core application allows user to log in using their Google accounts, eliminating the need for manual registration. This improves user experience and security. in this blog, i will guide you how it's works and how to set up without skip any step.
How it works?
Google OAuth authentication allows users to log in to your application using their Google account. Here's how the process works:
-
User Clicks Login: The user clicks the "Login with Google" button on your app.
-
Redirect to Google: The app redirects the user to Google's authentication page.
-
User Grants Permission: The user signs in with their Google credentials and grants permissions.
-
Google Sends Authorization Code: If the login is successful, Google redirects the user back to your app with an authorization code.
-
Exchange for Access Token: Your app exchanges this code for an access token and retrieves user information.
-
Authenticate the User: The app uses the retrieved user info (email, name, etc.) to log the user in and create a session.
With this flow, your app never handles user passwords, improving security and reducing authentication complexity.
Requirements
- ASP.NET Core 6 or later
- Google Developer Account
- Google OAuth Credentials
Step 1: Register Your App On Google Cloud Console
-
Go to Google Cloud Console.
-
Create a new project.
-
Navigate to APIs & Services → Credentials.
-
Click Create Credentials → OAuth 2.0 Client ID.
-
Set the Application Type to Web Application.
-
Under "Authorized Redirect URIs," add:
https://localhost:5001/signin-google
-
Click "Create" and save the Client ID and Client Secret.
Step 2: Install Required NuGet Package
In your ASP.NET Core project, install the authentication package:
dotnet add package Microsoft.AspNetCore.Authentication.Google
Step 3: Configure ClientId and ClientSecret
Modify appsettings.json for secure placement
"Authentication": {
"Google": {
"ClientId": "Your_ClientId",
"ClientSecret": "Your_ClientSecret"
}
}
Step 4: Configure Google Authentication in Program.cs
Modify Program.cs to configure authentication:
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.SlidingExpiration = true;
})
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
options.CallbackPath = "/Home/Index"; // Replaced with your callback path
});
Step 5: Create a Login Controller
Create a Controller to handle authentication:
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;
[Route("Auth")]
public class AuthController : Controller
{
[HttpGet("login")]
public IActionResult Login()
{
var redirectUrl = Url.Action("GoogleResponse", "Auth");
var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[HttpGet("google-response")]
public async Task<IActionResult> GoogleResponse()
{
var authenticateResult = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (!authenticateResult.Succeeded)
return BadRequest();
var claims = authenticateResult.Principal.Identities.FirstOrDefault()?.Claims;
if (claims == null)
return BadRequest("No claims found");
var email = claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
var name = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
if (string.IsNullOrEmpty(email))
return BadRequest("Google authentication failed");
// Check if the user already exists in the database
var existingUser = await _context.Users.FirstOrDefaultAsync(u => u.Email == email);
if (existingUser == null)
{
// Create a new user
var newUser = new User
{
Name = name,
Email = email,
CreatedAt = DateTime.UtcNow
};
_context.Users.Add(newUser);
await _context.SaveChangesAsync();
}
// Sign in the user
var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, name));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, email));
var authProperties = new AuthenticationProperties();
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties
);
return Redirect("/dashboard"); // Redirect to a protected page after login
}
[HttpGet("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
}
Step 6: Protect Routes With Authentication
To restrict access to authenticated users, use [Authorize]
in your controllers:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc;
[Authorize] public class DashboardController : Controller { public IActionResult Index() { return View(); } }
Step 7: Run and Test
-
Start your ASP.NET Core app.
-
Navigate to
/Auth/login
. -
Sign in with your Google account.
-
After login, you should automatically redirect to dashboard ( from you rediction )
Comments (0)