External authentication provider integration documentation.
Overview#
Aphrodite supports multiple OAuth providers for social login.
| Provider | Protocol | Features |
|---|---|---|
| OAuth 2.0 | Email, profile | |
| OAuth 1.0a | Username, profile |
Google OAuth#
Documentation: https://developers.google.com/identity
Configuration#
typescript
interface GoogleOAuthConfig {
clientId: string;
clientSecret: string;
redirectUri: string;
scopes: string[];
}
Authorization URL#
typescript
function getGoogleAuthUrl(state: string): string {
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: 'code',
scope: config.scopes.join(' '),
state,
access_type: 'offline',
prompt: 'consent',
});
return `https://accounts.google.com/o/oauth2/v2/auth?${params}`;
}
Exchange Code for Tokens#
typescript
async function exchangeGoogleCode(code: string): Promise<GoogleTokens> {
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: config.clientId,
client_secret: config.clientSecret,
code,
grant_type: 'authorization_code',
redirect_uri: config.redirectUri,
}),
});
return response.json();
}
Get User Profile#
typescript
async function getGoogleProfile(accessToken: string): Promise<GoogleProfile> {
const response = await fetch(
'https://www.googleapis.com/oauth2/v2/userinfo',
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
return response.json();
}
Callback Handler#
typescript
app.get('/oauth/google/callback', async (req, res) => {
const { code, state } = req.query;
// Verify state to prevent CSRF
if (!verifyState(state)) {
return res.status(400).send('Invalid state');
}
// Exchange code for tokens
const tokens = await exchangeGoogleCode(code);
// Get user profile
const profile = await getGoogleProfile(tokens.access_token);
// Find or create user
let user = await findUserByEmail(profile.email);
if (!user) {
user = await createUser({
email: profile.email,
displayName: profile.name,
avatarUrl: profile.picture,
emailVerified: profile.verified_email,
provider: 'google',
providerId: profile.id,
});
} else {
await linkGoogleAccount(user.id, profile.id);
}
// Generate session tokens
const sessionTokens = await generateSessionTokens(user);
// Redirect with tokens
res.redirect(`/auth/callback?tokens=${encodeTokens(sessionTokens)}`);
});
Twitter OAuth 1.0a#
Documentation: https://developer.twitter.com/en/docs/authentication
Configuration#
typescript
interface TwitterOAuthConfig {
consumerKey: string;
consumerSecret: string;
callbackUrl: string;
}
Request Token#
typescript
import OAuth from 'oauth-1.0a';
import crypto from 'crypto';
const oauth = new OAuth({
consumer: {
key: config.consumerKey,
secret: config.consumerSecret,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return crypto.createHmac('sha1', key).update(base_string).digest('base64');
},
});
async function getRequestToken(): Promise<RequestToken> {
const request_data = {
url: 'https://api.twitter.com/oauth/request_token',
method: 'POST',
data: { oauth_callback: config.callbackUrl },
};
const response = await fetch(request_data.url, {
method: request_data.method,
headers: oauth.toHeader(oauth.authorize(request_data)),
});
const text = await response.text();
return parseOAuthResponse(text);
}
Authorization URL#
typescript
function getTwitterAuthUrl(oauthToken: string): string {
return `https://api.twitter.com/oauth/authorize?oauth_token=${oauthToken}`;
}
Access Token#
typescript
async function getAccessToken(
oauthToken: string,
oauthVerifier: string,
tokenSecret: string
): Promise<AccessToken> {
const request_data = {
url: 'https://api.twitter.com/oauth/access_token',
method: 'POST',
data: { oauth_verifier: oauthVerifier },
};
const token = { key: oauthToken, secret: tokenSecret };
const response = await fetch(request_data.url, {
method: request_data.method,
headers: oauth.toHeader(oauth.authorize(request_data, token)),
});
const text = await response.text();
return parseOAuthResponse(text);
}
Callback Handler#
typescript
app.get('/oauth/twitter/callback', async (req, res) => {
const { oauth_token, oauth_verifier } = req.query;
// Get stored token secret
const tokenSecret = await getStoredTokenSecret(oauth_token);
// Exchange for access token
const accessToken = await getAccessToken(
oauth_token,
oauth_verifier,
tokenSecret
);
// Get user profile
const profile = await getTwitterProfile(accessToken);
// Find or create user
let user = await findUserByTwitterId(profile.id);
if (!user) {
user = await createUser({
username: profile.screen_name,
displayName: profile.name,
avatarUrl: profile.profile_image_url_https,
provider: 'twitter',
providerId: profile.id,
});
}
// Generate session tokens
const sessionTokens = await generateSessionTokens(user);
res.redirect(`/auth/callback?tokens=${encodeTokens(sessionTokens)}`);
});
Session Management#
JWT Token Generation#
typescript
import jwt from 'jsonwebtoken';
interface TokenPayload {
userId: string;
email: string;
roles: string[];
}
function generateAccessToken(payload: TokenPayload): string {
return jwt.sign(payload, config.accessTokenSecret, {
expiresIn: '15m',
algorithm: 'RS256',
});
}
function generateRefreshToken(payload: TokenPayload): string {
return jwt.sign({ userId: payload.userId }, config.refreshTokenSecret, {
expiresIn: '7d',
algorithm: 'RS256',
});
}
Token Refresh#
typescript
async function refreshTokens(refreshToken: string): Promise<SessionTokens> {
// Verify refresh token
const payload = jwt.verify(refreshToken, config.refreshTokenSecret);
// Check if refresh token is revoked
if (await isTokenRevoked(refreshToken)) {
throw new Error('Token revoked');
}
// Get user
const user = await getUserById(payload.userId);
// Revoke old refresh token
await revokeToken(refreshToken);
// Generate new tokens
return {
accessToken: generateAccessToken(user),
refreshToken: generateRefreshToken(user),
expiresIn: 900,
};
}
Account Linking#
typescript
async function linkSocialAccount(
userId: string,
provider: string,
providerId: string
): Promise<void> {
// Check if already linked
const existing = await findLinkedAccount(provider, providerId);
if (existing && existing.userId !== userId) {
throw new Error('Account already linked to another user');
}
await createLinkedAccount({
userId,
provider,
providerId,
linkedAt: new Date(),
});
}
Security Best Practices#
- State Parameter: Always use and verify state parameter for CSRF protection
- Token Storage: Store tokens securely (httpOnly cookies, secure flag)
- Token Rotation: Rotate refresh tokens on use
- Scope Minimization: Request only necessary OAuth scopes
- Rate Limiting: Rate limit OAuth endpoints
- Logging: Log all authentication events
Document History#
| Date | Version | Changes |
|---|---|---|
| 2026-01-18 | 1.0.0 | Initial Auth Integrations docs |