Google OAuth Implementation for ASP.
NET Core
1. Create a Project on Google Cloud Platform
1. Go to the Google Cloud Console (https://console.cloud.google.com/).
2. Create a new project or select an existing one.
3. Navigate to APIs & Services > Credentials.
4. Click Create Credentials and choose OAuth 2.0 Client IDs.
- Set the application type to Web application.
- Add the following:
- Authorized redirect URIs: https://localhost:5001/signin-google
- Authorized JavaScript origins: https://localhost:5001
5. Note the Client ID and Client Secret.
2. Add ASP.NET Core Authentication Middleware
Add the necessary NuGet package:
dotnet add package Microsoft.AspNetCore.Authentication.Google
3. Configure Google Authentication
In the appsettings.json file, store the Client ID and Secret securely:
"Authentication": {
"Google": {
"ClientId": "YOUR_CLIENT_ID",
"ClientSecret": "YOUR_CLIENT_SECRET"
}
Google OAuth Implementation for ASP.NET Core
Alternatively, use environment variables for sensitive data.
4. Configure Authentication in Startup
In Program.cs (or Startup.cs for older versions), configure authentication:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(options =>
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
});
Google OAuth Implementation for ASP.NET Core
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
5. Protect Routes with Authentication
For routes requiring authentication, decorate controllers or actions with [Authorize]:
[Authorize]
public IActionResult SecurePage()
return View();
6. Add Login and Logout
In your Razor pages or controllers, use authentication endpoints for login and logout:
Login:
public IActionResult Login()
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, GoogleDefaults.AuthenticationScheme);
}
Google OAuth Implementation for ASP.NET Core
Logout:
public IActionResult Logout()
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
CookieAuthenticationDefaults.AuthenticationScheme);
7. Run and Test the Application
1. Start the application.
2. Access the login endpoint, e.g., https://localhost:5001/login.
3. Google will prompt for authentication and redirect back to the application.