ソーシャルログイン(OAuthプロバイダー)
Google、GitHub、Facebookなどの人気OAuthプロバイダーを統合し、ユーザーにスムーズなソーシャルログインを提供します。
「ソーシャルログイン(OAuthプロバイダー)」はCoddyKit上の無料Supabase Backend as a Serviceレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSupabase Backend as a Service学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Supabase Backend as a Serviceコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Simplify Sign-Ups with Social Logins
Tired of users creating new passwords for every app? Social logins, also known as OAuth providers, let users sign in with their existing accounts from services like Google, GitHub, or Facebook.
This makes signing up much faster and more convenient, improving the user experience and potentially increasing user adoption.
Supabase Makes OAuth Easy
Supabase acts as a powerful intermediary, simplifying the complex OAuth flow. Instead of you writing intricate logic for each provider, Supabase handles the redirects, token exchanges, and session management securely.
This means you can integrate multiple social login options with minimal code.
Activate Providers in Your Project
Before writing any code, you need to enable the desired social login providers in your Supabase project dashboard.
- Go to Authentication > Providers.
- Toggle on providers like Google, GitHub, or Facebook.
- You'll need to configure their respective Client ID and Client Secret, obtained from the provider's developer console.
The `signInWithOAuth` Method
The core of initiating a social login in your application is the Supabase JavaScript client's signInWithOAuth() method. This function redirects your user to the chosen provider's login page.
It takes a provider name (e.g., 'google', 'github') and an optional options object, typically including a redirectTo URL.
Initiate Google Login
Here's a practical example of how to start a Google login flow. When this code runs, the user will be sent to Google's authentication page.
Remember to replace window.location.origin + '/auth/callback' with your actual callback URL.
import { createClient } from '@supabase/supabase-js';
// Initialize Supabase client (replace with your actual URL and Anon Key)
const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';
const supabase = createClient(supabaseUrl, supabaseAnonKey);
async function signInWithGoogle() {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: window.location.origin + '/auth/callback'
}
});
if (error) {
console.error('Error initiating Google login:', error.message);
} else {
console.log('Redirecting to Google for authentication...');
// User will be redirected automatically
}
}
// To run this, you'd typically call signInWithGoogle()
// on a button click event in a web application.
// For example: signInWithGoogle();The OAuth Redirect Flow
After the user successfully logs in with the social provider (e.g., Google), the provider redirects them back to your application.
This redirect includes special parameters in the URL that Supabase uses to establish the user's session securely. It's a critical part of the OAuth process.
Handling the Callback Route
Your application needs a designated callback route (e.g., /auth/callback) to receive the redirect from the OAuth provider.
The Supabase client library automatically listens for these URL parameters on page load and processes them to create a user session. You typically don't need to write explicit code for this route beyond initializing the Supabase client.
Accessing User Session Data
Once authenticated via social login, Supabase provides access to the user's session and profile information. You can use methods like supabase.auth.getSession() to retrieve the active session details.
The session object contains the user's ID, email, and other metadata provided by the OAuth provider.
Check the Current Session
This example shows how to check if a user is currently logged in and retrieve their session data. This is often done after the callback redirect or on app startup.
import { createClient } from '@supabase/supabase-js';
// Initialize Supabase client (replace with your actual URL and Anon Key)
const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';
const supabase = createClient(supabaseUrl, supabaseAnonKey);
async function getCurrentUserSession() {
const { data: { session }, error } = await supabase.auth.getSession();
if (error) {
console.error('Error getting session:', error.message);
return null;
}
if (session) {
console.log('User is logged in!');
console.log('User ID:', session.user.id);
console.log('Email:', session.user.email);
console.log('Provider:', session.user.app_metadata.provider);
return session;
} else {
console.log('No active session.');
return null;
}
}
// Call this function to check the session
// getCurrentUserSession();Keep Your App Secure
Security is paramount with authentication:
- Use HTTPS: Always ensure your application is served over HTTPS.
- Valid `redirectTo` URLs: Configure your
redirectToURLs carefully in both Supabase and the OAuth provider's settings to prevent redirect attacks. - Client-Side Keys: Never expose your Supabase Service Role Key on the client-side; only use the Anon Key for client-side operations.
Social Login Check
When using supabase.auth.signInWithOAuth(), what is the primary purpose of the redirectTo option?
Recap & Next Steps
You've successfully learned how to integrate social logins using Supabase! This powerful feature simplifies user authentication, enhances convenience, and leverages existing user accounts from popular OAuth providers like Google and GitHub.
You now understand the role of signInWithOAuth(), the redirect flow, and how to retrieve user session data.
Next, explore how to manage user sessions and profiles, including updating user metadata and handling logout functionalities securely.
AI チューターと学ぶ Supabase Backend as a Service — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 11
- レッスン
- 40
よくある質問
「ソーシャルログイン(OAuthプロバイダー)」レッスンは無料ですか?
はい。「ソーシャルログイン(OAuthプロバイダー)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Supabase Backend as a Serviceコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Supabase Backend as a Serviceコースには全4レッスンが含まれています。
「ソーシャルログイン(OAuthプロバイダー)」で何を学びますか?
Google、GitHub、Facebookなどの人気OAuthプロバイダーを統合し、ユーザーにスムーズなソーシャルログインを提供します。 ブラウザで直接実行するハンズオンコードでSupabase Backend as a Serviceを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Supabase Backend as a Serviceを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSupabase Backend as a Serviceは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「ソーシャルログイン(OAuthプロバイダー)」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSupabase Backend as a Serviceレッスンでコードを書いて実行できますか?
はい。すべてのSupabase Backend as a Serviceレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- メールアドレスとパスワードによるユーザー登録
- ソーシャルログイン(OAuthプロバイダー)
- ユーザーセッションとプロフィールの管理
- パスワードリセットとマジックリンク認証