Skip to content

TechHoldingLLC/SAP-CDC-Proxy-Handled-Flow

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Proxy-Handled Social Login with SAP CDC

A production-ready implementation of social login using SAP Customer Data Cloud (CDC) with the proxy-handled flow pattern and Ory Hydra for OAuth2.

Overview

This implementation demonstrates the CDC Proxy-Handled Flow where:

  1. Client-side: User authenticates with a social provider (Google) using their JavaScript SDK
  2. Client → Server: The ID token is sent to your proxy server
  3. Server → CDC: Your server searches for the user in CDC using accounts.search
  4. Server → Hydra: User is authenticated via Ory Hydra OAuth2 flow
  5. Client: Receives OAuth2 access and refresh tokens

Key Features

  • ✅ Modern client-side social login experience
  • ✅ SAP CDC integration for user management
  • ✅ Ory Hydra for OAuth2/OIDC token issuance
  • ✅ Docker-based infrastructure setup
  • ✅ Production-ready error handling
  • ✅ Comprehensive logging

Quick Start

Prerequisites

  • Node.js 16+ installed
  • Docker and Docker Compose installed
  • A Google OAuth Client ID (Get one here)
  • SAP CDC credentials (API Key and Secret Key)

1. Clone and Setup

git clone <repository-url>
cd approach-2-proxy-handled
npm install

2. Configure Environment

cp env.example .env

Edit .env and add your credentials:

# SAP CDC Configuration
CDC_API_KEY=your_cdc_api_key
CDC_SECRET_KEY=your_cdc_secret_key
CDC_BASE_URL=https://accounts.us1.gigya.com  # or eu1, au1, etc.

# Google OAuth
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com

# Application URLs
APP_URL=http://localhost:3000
PORT=3000

# Ory Hydra URLs (default for Docker Compose setup)
HYDRA_ADMIN_URL=http://localhost:4445
HYDRA_PUBLIC_URL=http://localhost:4444

# OAuth Client (created automatically by start.sh)
CLIENT_ID=demo-client-id
CLIENT_SECRET=demo-client-secret

3. Configure Google OAuth

  1. Go to Google Cloud Console
  2. Select or create a project
  3. Create OAuth 2.0 Client ID (Web application)
  4. Under Authorized JavaScript origins, add:
    • http://localhost:3000
  5. Copy the Client ID to your .env file

Note: No redirect URI is needed for the JavaScript SDK.

4. Start Everything

./start.sh

This script will:

  • Start Ory Hydra OAuth2 server (Docker)
  • Wait for Hydra to be ready
  • Create the OAuth2 client automatically
  • Start the Node.js application server

5. Test the Flow

Open in your browser: http://localhost:3000/test

Click "Start OAuth2 Flow" → Sign in with Google → Complete authentication

6. Stop Everything

./stop.sh

Architecture

┌──────────┐   1. Click   ┌──────────┐   2. Auth    ┌────────┐
│ Browser  │─────────────▶│  Google  │─────────────▶│ Google │
│          │              │   SDK    │              │  Auth  │
└──────────┘              └──────────┘              └────────┘
     │                          │                        │
     │                          │◀─── 3. ID Token ───────┘
     │                          │
     │    4. POST Token         │
     │─────────────────────────▶│
     │                      ┌───▼────┐
     │                      │  Your  │  5. Search
     │                      │ Server │────────────▶┌─────┐
     │                      └────────┘             │ CDC │
     │                          │   6. User Info   └─────┘
     │                          │◀─────────────────┘
     │                          │
     │                          │  7. Accept Login
     │                          │─────────────────▶┌───────┐
     │  8. Redirect             │                  │ Hydra │
     │◀─────────────────────────┤                  │       │
     │                          │  9. OAuth Tokens │       │
     │◀─────────────────────────────────────────────┴───────┘

File Structure

approach-2-proxy-handled/
├── src/
│   ├── server.js                  # Main Express application
│   ├── routes/
│   │   ├── auth.js               # Login page with Google Sign-In button
│   │   ├── social-login.js       # Receives token, searches CDC
│   │   ├── consent.js            # Hydra consent handler
│   │   ├── hydra-callback.js     # OAuth callback
│   │   └── test.js               # Test interface
│   └── services/
│       └── cdcClient.js          # CDC API client
├── docker-compose.yml            # Hydra infrastructure
├── start.sh                      # Startup script
├── stop.sh                       # Shutdown script
├── package.json                  # Node.js dependencies
├── .env                          # Configuration (create from env.example)
└── env.example                   # Configuration template

How It Works

1. Client-Side Google Sign-In

The login page (src/routes/auth.js) loads the Google Sign-In SDK and renders the authentication button:

google.accounts.id.initialize({
  client_id: 'YOUR_GOOGLE_CLIENT_ID',
  callback: handleGoogleSignIn
});

google.accounts.id.renderButton(
  document.getElementById('google-signin-btn'),
  { theme: 'outline', size: 'large' }
);

2. Token Sent to Server

When the user authenticates, the client sends the ID token to your server:

async function handleGoogleSignIn(response) {
  const result = await fetch('/auth/social-login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      provider: 'google',
      accessToken: response.credential,  // Google ID token
      login_challenge: login_challenge
    })
  });
  
  const data = await result.json();
  window.location.href = data.redirectTo;
}

3. Server Searches CDC

The server (src/routes/social-login.js) decodes the token and searches for the user:

// Decode Google ID token to get email
const decoded = jwt.decode(providerToken);

// Search CDC for existing user
const searchResult = await cdcClient.searchUser(decoded.email);

4. Accept Hydra Login

Once the user is found/created, accept the Hydra login challenge:

await axios.put(
  `${HYDRA_ADMIN_URL}/admin/oauth2/auth/requests/login/accept`,
  {
    subject: cdcResponse.UID,
    context: {
      email: cdcResponse.profile.email,
      provider: 'google'
    }
  },
  { params: { login_challenge } }
);

API Reference

Health Check

GET http://localhost:3000/health

Returns server status and available endpoints.

Test Page

GET http://localhost:3000/test

Interactive page to test the complete OAuth2 flow.

Login Endpoint

GET http://localhost:3000/login?login_challenge={challenge}

Displays Google Sign-In button. Called by Hydra with a login challenge.

Social Login Handler

POST http://localhost:3000/auth/social-login
Content-Type: application/json

{
  "provider": "google",
  "accessToken": "google-id-token",
  "login_challenge": "hydra-login-challenge"
}

Processes social login, searches CDC, and accepts Hydra login.


Environment Variables

Variable Description Example
CDC_API_KEY Your SAP CDC API key 3_abc...
CDC_SECRET_KEY Your SAP CDC secret key xyz...
CDC_BASE_URL CDC API base URL https://accounts.us1.gigya.com
GOOGLE_CLIENT_ID Google OAuth Client ID xxx.apps.googleusercontent.com
APP_URL Your application URL http://localhost:3000
PORT Server port 3000
HYDRA_ADMIN_URL Hydra admin API URL http://localhost:4445
HYDRA_PUBLIC_URL Hydra public API URL http://localhost:4444
CLIENT_ID OAuth client ID demo-client-id
CLIENT_SECRET OAuth client secret demo-client-secret

Troubleshooting

Google Sign-In Button Not Showing

Problem: The Google Sign-In button doesn't appear on the login page.

Solutions:

  1. Verify GOOGLE_CLIENT_ID is correctly set in .env
  2. Check that http://localhost:3000 is added to "Authorized JavaScript origins" in Google Console
  3. Open browser console and look for Google SDK errors
  4. Ensure the SDK script is loading: https://accounts.google.com/gsi/client

Origin Not Allowed Error

Problem: Browser shows: The given origin is not allowed for the given client ID

Solution:

  1. Go to Google Cloud Console
  2. Edit your OAuth 2.0 Client ID
  3. Add http://localhost:3000 to Authorized JavaScript origins
  4. Save and wait a few minutes for changes to propagate

CDC Search Returns No Results

Problem: User authenticates but CDC can't find their account.

Solutions:

  1. This is normal for first-time users - they need to be registered in CDC first
  2. Check CDC console to see if the user exists
  3. Verify the email in the Google token matches the email in CDC
  4. Consider implementing user registration flow for new users

Hydra Connection Errors

Problem: Server can't connect to Hydra.

Solutions:

  1. Ensure Hydra is running: docker ps
  2. Verify Hydra URLs in .env are correct
  3. Check Hydra health: curl http://localhost:4445/health/ready
  4. Restart Hydra: docker-compose restart hydra

Production Deployment

1. Update Environment Variables

# Use production URLs
APP_URL=https://auth.yourdomain.com
HYDRA_ADMIN_URL=https://hydra-admin.yourdomain.com
HYDRA_PUBLIC_URL=https://hydra.yourdomain.com

# Use production CDC datacenter
CDC_BASE_URL=https://accounts.eu1.gigya.com

2. Update Google Console

  1. Add production domain to Authorized JavaScript origins
  2. Remove or restrict localhost origins
  3. Generate new OAuth credentials for production (recommended)

3. Security Considerations

  • ✅ Always use HTTPS in production
  • ✅ Store secrets in a secure vault (AWS Secrets Manager, etc.)
  • ✅ Rotate API keys regularly
  • ✅ Enable rate limiting
  • ✅ Set up monitoring and alerting
  • ✅ Review CORS configuration for production domains

4. Deploy

# Install production dependencies only
npm install --production

# Start with PM2 or similar process manager
pm2 start src/server.js --name "cdc-social-login"

Testing

Manual Testing

  1. Start the application
  2. Visit http://localhost:3000/test
  3. Click "Start OAuth2 Flow"
  4. Sign in with Google
  5. Verify successful authentication
  6. Check CDC console for user account

Verify Endpoints

# Health check
curl http://localhost:3000/health

# Hydra health
curl http://localhost:4445/health/ready

Resources


Support

For issues or questions:

  1. Check the troubleshooting section above
  2. Review server logs for detailed error messages
  3. Verify all environment variables are set correctly
  4. Check CDC error codes in API responses

License

ISC


Status: ✅ Production-Ready

This implementation follows CDC best practices and is ready for production deployment with proper configuration.

SAP-CDC-Proxy-Handled-Flow

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published