Supabase Auth

JSK·2024년 8월 14일

로펀님의 Supabase 강의를 듣고 작성한 글입니다.

서두

Supabase Auth는 Supabase의 핵심 기능 중 하나로 어플리케이션 개발 시 인증과 인가 기능을 쉽게 구현할 수 있도록 도와준다. Email / Password 인증 방식부터 패스워드 없이 인증할 수 있는 OTP, Magic link 방식 그리고 써드 파티 프로바이더와 연동한 OAuth 방식까지 다양한 인증 방식을 제공한다. 아래는 Supabase Auth와 연동가능한 프로바이더 목록이다.

Supabase Auth를 이용한 인증 구현 (Password-base Auth)

다음은 Confirmation URL 방식을 이용한 Email / Password 인증 예시를 소개한다. 아래와 같은 순서로 회원 가입과 로그인이 진행된다.

  • 먼저, Client는 Supabase로 회원가입 요청을 한다. 아래 코드와 같이 signUp 함수를 Email, Password, redirect_to 인자와 함께 호출한다. 이 후 회원 가입 완료한 뒤에는 signInWithPassword 함수를 호출해 로그인을 시도할 수 있다.
const { data, error } = await supabase.auth.signUp({
	email,
	password,
	options: {
		emailRedirectTo: "http://localhost:3000/signup/confirm",
	},
});

async function signInWithEmail() {
  const { data, error } = await supabase.auth.signInWithPassword({
    email: 'example@email.com',
    password: 'example-password',
  })
}
  • Supabase는 회원가입 처리와 인증 링크가 담긴 이메일을 전송한다. Auth에서 제공하는 Email Template{{ .ConfirmationURL }} 라는 Message varible을 이용해 아래처럼 이메일을 작성할 수 있다. Supabase 공식 홈페이지 > Dashboard > Auth > Configuration > Email Template 에서 이메일 양식을 커스터마이징 할 수 있다.
<h2>Confirm your signup</h2>

<p>Follow this link to confirm your user:</p>
<p>
	<a href="{{.ConfirmationURL}}">Confirm your email</a>
</p>

import { NextResponse } from "next/server";
import { createServerSupabaseClient } from "utils/supabase/server";

// localhost:3000/signup/confirm/?code=...
export async function GET(request: Request) {
  const requestUrl = new URL(request.url);
  const code = requestUrl.searchParams.get("code");

  if (code) {
    const supabase = await createServerSupabaseClient();
    await supabase.auth.exchangeCodeForSession(code);
  }

  // localhost:3000/
  return NextResponse.redirect(requestUrl.origin);
}

결론

Supabase Auth가 제공하는 signup, signin 함수를 호출함으로써 쉽게 인증 기능을 구현할 수 있다.

참조

profile
fullstack developer & maker

0개의 댓글