Complete reference for Single Sign-On integration with OAuth providers.
OAuth Methods
loginWithGoogle()
Authenticate users with Google OAuth 2.0.
loginWithGoogle(options?: SSOOptions): Promise<void>
OAuth configuration options
Examples:
try {
await gately.loginWithGoogle()
console.log('Google login successful')
} catch (error) {
console.error('Google login failed:', error.message)
}
Returns: Promise<void>
loginWithGithubSSO()
Authenticate users with GitHub OAuth.
loginWithGithubSSO(options?: SSOOptions): Promise<void>
OAuth configuration options
Examples:
try {
await gately.loginWithGithubSSO({
mode: 'popup',
popupOptions: {
width: 500,
height: 600
}
})
console.log('GitHub login successful')
} catch (error) {
console.error('GitHub login failed:', error.message)
}
Returns: Promise<void>
SSO Configuration
SSOOptions
interface SSOOptions {
mode?: 'popup' | 'redirect'
redirectUrl?: string
popupOptions?: PopupOptions
}
mode
'popup' | 'redirect'
default:"'popup'"
Authentication mode - popup opens a new window, redirect navigates the current page
redirectUrl
string
default:"window.location.href"
URL to redirect to after successful authentication (redirect mode only)
Configuration for popup window (popup mode only)
interface PopupOptions {
width?: number
height?: number
scrollbars?: boolean
resizable?: boolean
left?: number
top?: number
}
Popup window width in pixels
Popup window height in pixels
Show scrollbars in popup window
Allow popup window resizing
Popup window left position (auto-centered if not specified)
Popup window top position (auto-centered if not specified)
OAuth Redirect Handling
When using redirect mode, handle the OAuth callback on page load:
function handleOAuthRedirect() {
const url = new URL(window.location.href)
const authSuccess = url.searchParams.get('gately_auth_success')
const sessionParam = url.searchParams.get('gately_session')
const userParam = url.searchParams.get('gately_user')
if (authSuccess === 'true' && sessionParam && userParam) {
try {
// The SDK automatically handles session restoration
console.log('OAuth authentication successful')
// Clean up URL parameters
url.searchParams.delete('gately_auth_success')
url.searchParams.delete('gately_session')
url.searchParams.delete('gately_user')
// Update URL without parameters
window.history.replaceState({}, '', url.toString())
// Show success message or redirect
showSuccessMessage('Successfully logged in!')
} catch (error) {
console.error('Failed to handle OAuth redirect:', error)
showErrorMessage('Authentication failed. Please try again.')
}
}
}
// Call on page load
document.addEventListener('DOMContentLoaded', handleOAuthRedirect)
// Or in React
useEffect(() => {
handleOAuthRedirect()
}, [])
React SSO Integration
Complete React component with SSO support:
import React, { useState, useEffect } from 'react'
import { useGately } from 'https://cdn.usegately.com/gately-sdk.esm.min.js'
function SSOLogin() {
const {
loginWithGoogle,
loginWithGithubSSO,
user,
logout,
loading,
error
} = useGately('your-project-id')
const [ssoLoading, setSsoLoading] = useState(false)
// Handle OAuth redirect on component mount
useEffect(() => {
const handleOAuthRedirect = () => {
const url = new URL(window.location.href)
const authSuccess = url.searchParams.get('gately_auth_success')
if (authSuccess === 'true') {
// Clean up URL
url.searchParams.delete('gately_auth_success')
url.searchParams.delete('gately_session')
url.searchParams.delete('gately_user')
window.history.replaceState({}, '', url.toString())
}
}
handleOAuthRedirect()
}, [])
const handleGoogleLogin = async () => {
setSsoLoading(true)
try {
await loginWithGoogle({
mode: 'popup',
popupOptions: { width: 500, height: 600 }
})
} catch (error) {
console.error('Google login failed:', error)
} finally {
setSsoLoading(false)
}
}
const handleGithubLogin = async () => {
setSsoLoading(true)
try {
await loginWithGithubSSO({
mode: 'redirect',
redirectUrl: window.location.href
})
} catch (error) {
console.error('GitHub login failed:', error)
setSsoLoading(false)
}
}
if (user) {
return (
<div className="user-info">
<h3>Welcome, {user.email}!</h3>
<p>You are logged in via SSO</p>
<button onClick={logout}>Logout</button>
</div>
)
}
return (
<div className="sso-login">
<h2>Sign in with SSO</h2>
<button
onClick={handleGoogleLogin}
disabled={ssoLoading || loading}
className="google-btn"
>
{ssoLoading ? 'Signing in...' : 'Sign in with Google'}
</button>
<button
onClick={handleGithubLogin}
disabled={ssoLoading || loading}
className="github-btn"
>
{ssoLoading ? 'Signing in...' : 'Sign in with GitHub'}
</button>
{error && <p className="error">{error}</p>}
</div>
)
}
export default SSOLogin
Provider Configuration
Google OAuth Setup
To use Google OAuth, configure your OAuth application:
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the Google+ API
- Create OAuth 2.0 credentials
- Add authorized redirect URIs:
https://sdk.usegately.com/api/sdk/auth/google
- Copy the Client ID and Client Secret to your Gately dashboard
GitHub OAuth Setup
To use GitHub OAuth, configure your OAuth application:
- Go to GitHub Settings → Developer settings → OAuth Apps
- Create a new OAuth App
- Set the Authorization callback URL to:
https://sdk.usegately.com/api/sdk/auth/github
- Copy the Client ID and Client Secret to your Gately dashboard
SSO Modes Comparison
Advantages
- User stays on your page
- No page reload required
- Better user experience
- Can handle authentication errors gracefully
Disadvantages
- May be blocked by popup blockers
- Limited screen space on mobile devices
- Requires JavaScript enabled
Redirect Mode
Advantages
- Works on all devices and browsers
- Not blocked by popup blockers
- Better for mobile applications
- Works without JavaScript
Disadvantages
- Page reload required
- User leaves your application temporarily
- Need to handle redirect parameters
- Loses application state
Error Handling
SSO methods can throw specific errors:
OAuth Errors
User cancelled the OAuth flow
OAuth provider returned an error
Popup was blocked by browser
OAuth provider not configured in dashboard
Redirect URL not whitelisted
Example Error Handling:
try {
await gately.loginWithGoogle()
} catch (error) {
switch (error.code) {
case 'OAUTH_CANCELLED':
console.log('User cancelled Google login')
break
case 'POPUP_BLOCKED':
console.log('Popup was blocked. Please allow popups and try again.')
// Fallback to redirect mode
await gately.loginWithGoogle({ mode: 'redirect' })
break
case 'PROVIDER_NOT_CONFIGURED':
console.error('Google OAuth not configured. Please contact support.')
break
default:
console.error('Google login failed:', error.message)
}
}
Best Practices
- Use popup mode for desktop applications
- Use redirect mode for mobile applications
- Provide fallback from popup to redirect if blocked
- Consider user experience and device capabilities
- Always handle authentication errors gracefully
- Provide fallback authentication methods
- Show appropriate error messages to users
- Log errors for debugging and monitoring
- Validate redirect URLs to prevent open redirects
- Use HTTPS in production environments
- Implement proper session management
- Keep OAuth credentials secure
- Show loading states during authentication
- Provide clear instructions for users
- Handle edge cases like popup blockers
- Test on multiple browsers and devices
Next Steps