OAuth
Google, GitHub ve diğer OAuth sağlayıcılarıyla oturum açın.
Not: Bu içerik, yalnızca gösterim amaçlı örnek/yer tutucu içeriktir.
Kullanıcıların Google, GitHub ve diğer sağlayıcılardaki mevcut hesaplarıyla oturum açmasına izin verin.
Desteklenen Sağlayıcılar
Supabase birçok OAuth sağlayıcısını destekler:
- GitHub
- GitLab
- Bitbucket
- Azure
- Discord
- Slack
- Ve daha fazlası...
OAuth Kurulumu
Supabase Dashboard'da Yapılandırma
- Authentication → Providers bölümüne gidin
- İstediğiniz sağlayıcıyı etkinleştirin (ör. Google)
- OAuth kimlik bilgilerinizi ekleyin:
- Client ID
- Client Secret
- Redirect URL:
https://your-project.supabase.co/auth/v1/callback
Google OAuth Kurulumu
- Google Cloud Console adresine gidin
- Yeni bir proje oluşturun veya mevcut bir projeyi seçin
- Google+ API'yi etkinleştirin
- OAuth 2.0 kimlik bilgileri oluşturun
- Yetkili yönlendirme URI'lerini ekleyin:
- Üretim:
https://your-project.supabase.co/auth/v1/callback - Geliştirme:
http://localhost:54321/auth/v1/callback
- Üretim:
GitHub OAuth Kurulumu
- GitHub Settings → Developer Settings → OAuth Apps bölümüne gidin
- "New OAuth App" düğmesine tıklayın
- Bilgileri doldurun:
- Application name: Uygulamanızın adı
- Homepage URL:
https://yourapp.com - Authorization callback URL:
https://your-project.supabase.co/auth/v1/callback
- Client ID ve Client Secret değerlerini Supabase'e kopyalayın
Uygulama
OAuth Oturum Açma Düğmesi
'use client';
import { signInWithOAuthAction } from '../_lib/actions';
export function OAuthButtons() {
const handleGoogleSignIn = async () => {
await signInWithOAuthAction('google');
};
const handleGitHubSignIn = async () => {
await signInWithOAuthAction('github');
};
return (
<div className="space-y-2">
<button
onClick={handleGoogleSignIn}
className="w-full flex items-center justify-center gap-2 border rounded-lg p-2"
>
<GoogleIcon />
Continue with Google
</button>
<button
onClick={handleGitHubSignIn}
className="w-full flex items-center justify-center gap-2 border rounded-lg p-2"
>
<GitHubIcon />
Continue with GitHub
</button>
</div>
);
}
Server Action
'use server';
import { enhanceAction } from '@kit/next/actions';
import { getSupabaseServerClient } from '@kit/supabase/server-client';
import { z } from 'zod';
const OAuthProviderSchema = z.enum([
'google',
'github',
'gitlab',
'azure',
'facebook',
]);
export const signInWithOAuthAction = enhanceAction(
async (provider) => {
const client = getSupabaseServerClient();
const origin = process.env.NEXT_PUBLIC_SITE_URL!;
const { data, error } = await client.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${origin}/auth/callback`,
},
});
if (error) throw error;
// OAuth sağlayıcısına yönlendir
redirect(data.url);
},
{
schema: OAuthProviderSchema,
}
);
OAuth Callback İşleyicisi
// app/auth/callback/route.ts
import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get('code');
if (code) {
const cookieStore = cookies();
const supabase = createRouteHandlerClient({ cookies: () => cookieStore });
await supabase.auth.exchangeCodeForSession(code);
}
// Ana sayfaya yönlendir
return NextResponse.redirect(new URL('/home', request.url));
}
OAuth Akışını Özelleştirme
Kapsamlar
Belirli izinler talep edin:
await client.auth.signInWithOAuth({
provider: 'google',
options: {
scopes: 'email profile https://www.googleapis.com/auth/calendar',
},
});
Sorgu Parametreleri
Özel parametreler iletin:
await client.auth.signInWithOAuth({
provider: 'azure',
options: {
queryParams: {
prompt: 'consent',
access_type: 'offline',
},
},
});
Tarayıcı Yönlendirmesini Atlama
Mobil uygulamalar veya özel akışlar için:
const { data } = await client.auth.signInWithOAuth({
provider: 'google',
options: {
skipBrowserRedirect: true,
},
});
// data.url, OAuth URL'sini içerir
// Yönlendirmeyi manuel olarak yönet
Hesap Bağlama
Ek Sağlayıcıları Bağlama
Kullanıcıların birden fazla OAuth hesabını bağlamasına izin verin:
export const linkOAuthProviderAction = enhanceAction(
async (provider) => {
const client = getSupabaseServerClient();
const user = await requireAuth();
const { data, error } = await client.auth.linkIdentity({
provider,
});
if (error) throw error;
redirect(data.url);
},
{ schema: OAuthProviderSchema, auth: true }
);
Sağlayıcıların Bağlantısını Kaldırma
export const unlinkOAuthProviderAction = enhanceAction(
async ({ provider, identityId }) => {
const client = getSupabaseServerClient();
const { error } = await client.auth.unlinkIdentity({
identity_id: identityId,
});
if (error) throw error;
revalidatePath('/settings/security');
},
{
schema: z.object({
provider: z.string(),
identityId: z.string(),
}),
auth: true,
}
);
Bağlı Kimlikleri Görüntüleme
import { getSupabaseServerClient } from '@kit/supabase/server-client';
export async function getLinkedIdentities() {
const client = getSupabaseServerClient();
const { data: { user } } = await client.auth.getUser();
return user?.identities || [];
}
OAuth'tan Gelen Kullanıcı Verileri
Sağlayıcı Verilerine Erişme
const { data: { user } } = await client.auth.getUser();
// Sağlayıcıdan gelen kullanıcı meta verileri
const {
full_name,
avatar_url,
email,
} = user.user_metadata;
// Sağlayıcıya özgü veriler
const identities = user.identities || [];
const googleIdentity = identities.find(i => i.provider === 'google');
console.log(googleIdentity?.identity_data);
Ek Verileri Saklama
export const completeOAuthProfileAction = enhanceAction(
async (data) => {
const client = getSupabaseServerClient();
const user = await requireAuth();
// Kullanıcı meta verilerini güncelle
await client.auth.updateUser({
data: {
username: data.username,
bio: data.bio,
},
});
// Veritabanındaki profili güncelle
await client.from('profiles').upsert({
id: user.id,
username: data.username,
bio: data.bio,
avatar_url: user.user_metadata.avatar_url,
});
redirect('/home');
},
{ schema: ProfileSchema, auth: true }
);
Yapılandırma
Yapılandırmada OAuth'u Etkinleştirme
// config/auth.config.ts
export const authConfig = {
providers: {
emailPassword: true,
oAuth: ['google', 'github'],
},
};
Koşullu Görüntüleme
import { authConfig } from '~/config/auth.config';
export function AuthProviders() {
return (
<>
{authConfig.providers.emailPassword && <EmailPasswordForm />}
{authConfig.providers.oAuth?.includes('google') && (
<GoogleSignInButton />
)}
{authConfig.providers.oAuth?.includes('github') && (
<GitHubSignInButton />
)}
</>
);
}
Sorun Giderme
Yönlendirme URI'si Uyuşmazlığı
Yönlendirme URI'lerinin birebir eşleştiğinden emin olun:
- Supabase Dashboard → Authentication → URL Configuration bölümünü kontrol edin
- Sağlayıcı konsolundaki OAuth uygulama ayarlarını doğrulayın
- Tam URL'leri kullanın (http/https dahil)
Eksik E-posta
Bazı sağlayıcılar e-posta adresini varsayılan olarak paylaşmaz:
const { data: { user } } = await client.auth.getUser();
if (!user.email) {
// E-postayı ayrıca talep et veya kullanıcıdan iste
redirect('/auth/complete-profile');
}
Hız Sınırlaması
OAuth sağlayıcıları isteklere hız sınırı uygulayabilir:
- OAuth token'larını uygun şekilde önbelleğe alın
- Aşırı sayıda yetkilendirme isteği yapmaktan kaçının
- Hız sınırı hatalarını düzgün bir şekilde ele alın
En İyi Uygulamalar
- Minimum kapsam talep edin - Yalnızca ihtiyacınız olanı isteyin
- Hataları düzgün bir şekilde ele alın - OAuth birçok nedenden dolayı başarısız olabilir
- E-posta adreslerini doğrulayın - Bazı sağlayıcılar e-postaları doğrulamaz
- Hesap bağlamayı destekleyin - Kullanıcıların birden fazla sağlayıcı bağlamasına izin verin
- Yedek seçenek sunun - Her zaman yedek olarak e-posta/şifre seçeneği sunun
- OAuth olaylarını kaydedin - Oturum açmaları ve bağlama denemelerini takip edin
- Kapsamlı test edin - Gerçek sağlayıcı hesaplarıyla test edin