Skip to main content

Overview

RealtimeChat supports Google OAuth 2.0 for social authentication, allowing users to sign in with their Google accounts. This guide walks you through setting up Google OAuth credentials and integrating them into your application.
Google OAuth provides a secure way for users to authenticate without creating a separate password, improving user experience and security.

Prerequisites

Before you begin, ensure you have:
  • A Google account
  • Access to Google Cloud Console
  • RealtimeChat source code cloned locally
  • Basic understanding of OAuth 2.0 flow

Step-by-Step Setup

1

Create Google Cloud Project

Navigate to Google Cloud Console and create a new project:
  1. Click “Select a project” dropdown in the top navigation
  2. Click “NEW PROJECT”
  3. Enter project name (e.g., “RealtimeChat”)
  4. Click “CREATE”
2

Enable Google+ API

Enable the Google+ API for your project:
  1. In the left sidebar, go to APIs & Services > Library
  2. Search for “Google+ API”
  3. Click on it and click ENABLE
The Google+ API is required for retrieving user profile information during OAuth authentication.
3

Configure OAuth Consent Screen

Set up the OAuth consent screen:
  1. Go to APIs & Services > OAuth consent screen
  2. Select External user type (unless you have Google Workspace)
  3. Click CREATE
  4. Fill in required fields:
    • App name: RealtimeChat
    • User support email: Your email
    • Developer contact information: Your email
  5. Click SAVE AND CONTINUE
  6. Skip “Scopes” section (default scopes are sufficient)
  7. Add test users if needed for development
  8. Click SAVE AND CONTINUE
4

Create OAuth 2.0 Credentials

Create OAuth 2.0 Client ID credentials:
  1. Go to APIs & Services > Credentials
  2. Click CREATE CREDENTIALS > OAuth client ID
  3. Select Web application as application type
  4. Enter a name (e.g., “RealtimeChat Web Client”)
  5. Configure redirect URIs (see next step)
5

Configure Redirect URIs

Add the following authorized redirect URIs:Development:
http://localhost:5000/signin-google
http://localhost:5173/signin-google
Production:
https://yourdomain.com/signin-google
The callback path /signin-google is configured in the application code and must match exactly. See AuthExtensions.cs:25.
Click CREATE to generate your credentials.
6

Save Client ID and Secret

After creating credentials, you’ll see:
  • Client ID - A long string ending in .apps.googleusercontent.com
  • Client Secret - A secret key for server-side authentication
Copy these values. You’ll need them in the next step.
Keep your Client Secret secure! Never commit it to source control or expose it in client-side code.
7

Add Credentials to Configuration

Add your Google OAuth credentials to your application configuration.

Development (appsettings.Development.json)

Create or edit appsettings.Development.json:
Applications/RealtimeChat.API/appsettings.Development.json
{
  "Authentication": {
    "Google": {
      "ClientId": "your-client-id.apps.googleusercontent.com",
      "ClientSecret": "your-client-secret"
    }
  }
}

Production (Environment Variables)

For production, use environment variables or Azure Key Vault:
export Authentication__Google__ClientId="your-client-id.apps.googleusercontent.com"
export Authentication__Google__ClientSecret="your-client-secret"
Or in Docker:
docker-compose.yml
environment:
  - Authentication__Google__ClientId=your-client-id.apps.googleusercontent.com
  - Authentication__Google__ClientSecret=your-client-secret
ASP.NET Core uses __ (double underscore) to represent nested configuration in environment variables.
8

Verify Configuration

Ensure your authentication configuration is loaded correctly:
Applications/RealtimeChat.API/Extensions/AuthExtensions.cs
.AddGoogle(googleOptions =>
{
    googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"]!;
    googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"]!;
    googleOptions.CallbackPath = "/signin-google";
})
The application reads configuration from:
  1. appsettings.json (base configuration)
  2. appsettings.{Environment}.json (environment-specific)
  3. Environment variables (highest priority)

Testing OAuth Flow

Start the Application

cd Applications/RealtimeChat.API
dotnet run
The application will start on http://localhost:5000 (or your configured port).

Test Login Flow

1

Navigate to Login Endpoint

Open your browser and navigate to:
http://localhost:5000/auth/external-login/Google
This initiates the OAuth flow.
2

Authenticate with Google

You’ll be redirected to Google’s authentication page. Sign in with your Google account and grant permissions.
3

Callback Processing

After successful authentication, Google redirects back to:
http://localhost:5000/auth/external-callback
The ExternalAuthService processes the callback:
Applications/RealtimeChat.API/Services/ExternalAuthService.cs
public async Task<ApplicationUser?> HandleExternalLoginAsync(ClaimsPrincipal principal, string provider)
{
    var email = principal.FindFirst(ClaimTypes.Email)?.Value;
    var providerKey = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
    var fullName = principal.FindFirst(ClaimTypes.Name)?.Value;
    
    // Find existing user or create new one
    var user = await userManager.FindByLoginAsync(provider, providerKey);
    user ??= await userManager.FindByEmailAsync(email);
    
    if (user == null)
    {
        user = new ApplicationUser
        {
            UserName = email,
            Email = email,
            FirstName = firstName,
            LastName = lastName
        };
        
        await userManager.CreateAsync(user);
    }
    
    // Link external login to user
    await userManager.AddLoginAsync(user, loginInfo);
    await signInManager.SignInAsync(user, isPersistent: false);
    
    return user;
}
4

Verify Authentication

Test that authentication is working by accessing a protected endpoint:
curl http://localhost:5000/auth-ping -H "Cookie: .AspNetCore.Identity.Application=your-cookie"
Or navigate to it in your browser after logging in. You should see “PING” response.

OAuth Flow Details

Authentication Flow

The OAuth authentication flow in RealtimeChat works as follows:
┌──────────┐         ┌──────────────┐         ┌───────────┐
│  Client  │         │  RealtimeChat │         │  Google   │
└─────┬────┘         └──────┬───────┘         └─────┬─────┘
      │                     │                        │
      │  1. Click "Login"   │                        │
      ├────────────────────>│                        │
      │                     │                        │
      │  2. Redirect to     │                        │
      │     Google OAuth    │                        │
      │<────────────────────┤                        │
      │                     │                        │
      │  3. User authenticates                       │
      ├────────────────────────────────────────────>│
      │                     │                        │
      │  4. Callback with   │                        │
      │     auth code       │                        │
      │<────────────────────────────────────────────┤
      │                     │                        │
      │  5. Process callback                         │
      ├────────────────────>│                        │
      │                     │                        │
      │                     │  6. Exchange code      │
      │                     ├───────────────────────>│
      │                     │                        │
      │                     │  7. User info          │
      │                     │<───────────────────────┤
      │                     │                        │
      │  8. Create/update   │                        │
      │     user & sign in  │                        │
      │                     │                        │
      │  9. Set cookie &    │                        │
      │     redirect        │                        │
      │<────────────────────┤                        │

User Claims Extracted

During OAuth authentication, the following claims are extracted from Google:
ClaimTypes.Email
string
required
User’s email address (used as username)
ClaimTypes.NameIdentifier
string
required
Unique Google user identifier (provider key)
ClaimTypes.Name
string
User’s full name (split into FirstName and LastName)

Troubleshooting

Redirect URI Mismatch

Error: redirect_uri_mismatch Solution: Ensure the redirect URI in Google Cloud Console exactly matches the one configured in your application:
  • Code: /signin-google (see AuthExtensions.cs:25)
  • Console: Must include full URL with port for development

Missing Configuration

Error: Value cannot be null. (Parameter 'ClientId') Solution: Verify your configuration is loaded:
# Check configuration is present
dotnet user-secrets list

# Or verify environment variables
echo $Authentication__Google__ClientId

User Creation Fails

Error: User creation fails during OAuth callback Solution: Check database connection and ensure migrations are applied:
dotnet ef database update

Security Considerations

Never commit credentials to source control!

Development

  • Use appsettings.Development.json (add to .gitignore)
  • Or use .NET user secrets: dotnet user-secrets set "Authentication:Google:ClientId" "your-client-id"

Production

  • Use environment variables
  • Use Azure Key Vault or AWS Secrets Manager
  • Use managed identities where possible
  • Rotate secrets regularly

OAuth Security

  • Validate state parameter - Prevents CSRF attacks (handled by ASP.NET automatically)
  • Use HTTPS in production - Required for secure cookie transmission
  • Restrict redirect URIs - Only whitelist your application domains
  • Non-persistent cookies - Sessions expire when browser closes (isPersistent: false)

Next Steps

Authentication Overview

Learn about the overall authentication system

Identity Configuration

Explore ASP.NET Identity database configuration

Build docs developers (and LLMs) love