HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
Github Login 만들기

Github Login 만들기

날짜
Jan 13, 2025 09:49 AM
  1. https://github.com/application/new 에서 앱 등록
      • Homepage URL : 대상 사이트 url
      • Authorization callbaclk URL : 사용자의 권한 동의 버튼을 누르고 이동할 url
       
  1. 1 완료 시 생성된 하단 변수를 .env에 저장하기
      • client id
      • client secrets (generate a new client secret 클릭 후 얻기)
       
( 3~5 : GitHub DocsGitHub DocsOAuth 앱 권한 부여 - GitHub Docs
OAuth 앱 권한 부여 - GitHub Docs

OAuth 앱 권한 부여 - GitHub Docs

다른 사용자가 OAuth app에 권한을 부여하도록 설정할 수 있습니다.

GitHub DocsGitHub Docs
)
  1. 1. 사용자의 GitHub ID 요청
      • 소셜 로그인 이동 링크 route 파일 만들기
        • ⇒ ex. 이동 링크가 /github/start이면, 파일 위치가 app/github/start/route.ts
      • client_id(필수), scope 등을 searchParams로 등록해주고
        • scope(사용하고 싶은 유저의 권한 범위) 목록 ⇒ https://docs.github.com/ko/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
      • https://github.com/login/oauth/authorize?SEARCH_PARAMS 로 redirect
      • (+ 미들웨어 처리 필요하다면 해주기)
      import { redirect } from "next/navigation"; export function GET() { const idRequestUrl = "https://github.com/login/oauth/authorize"; const params = { client_id: process.env.GITHUB_CLIENT_ID!, scope: "read:user,user:email", }; const idRequestParams = new URLSearchParams(params).toString(); return redirect(`${idRequestUrl}?${idRequestParams}`); }
      app/github/start/route.js
       
  1. 이 페이지에서 code를 accessToken으로 교환
      • 사용자가 요청을 수락 시, 임시 code와 함께 Authorization callbaclk URL 으로 리디렉션 됨.
        • 임시 코드는 10분 후에 만료.
      • 해당 콜백에도 해당하는 route 파일 만들기
      • code → accessToken 으로 교환 요청하기
        • https://github.com/login/oauth/access_token에 POST 요청
        • client_id, client_secret, code를 searchParams로 넣어주기
        • Accept: "application/json" 를 해더에 넣으면, 응답이 json 객체 형태로 access_token 등이 담겨옴
      import { NextRequest } from "next/server"; //사용자 인증 수락 시, 이 페이지로 이동 됨 export async function GET(request: NextRequest) { //url의 searchParams로 같이 달고 옴 const code = request.nextUrl.searchParams.get("code"); if (!code) { return new Response(null, { status: 400, }); } //요청 필수 매개변수 const params = { client_id: process.env.GITHUB_CLIENT_ID!, client_secret: process.env.GITHUB_CLIENT_SECRETS!, code, }; const searchParams = new URLSearchParams(params).toString(); //access 토큰 발급하는 요청 const response = await fetch( `https://github.com/login/oauth/access_token?${searchParams}`, { method: "POST", headers: { Accept: "application/json", }, }, ); // code 만료 등 실패 시, 응답 객체에 error 등이 있고 // 성공 시, 응답 객체 access_token등이 담겨 있음 const { error, access_token } = await response.json(); if (error) { return new Response(null, { status: 400, }); } //토큰 값이 담긴 json객체를 응답으로 한다는 뜻 //return Response.json(result.access_token); }
      app/github/complete/route.js
3. accessToken으로 여러 api 요청 작업 실행하기
  1. github에 사용자 프사, username, id를 가져오기
  1. 가져온 내용을 바탕으로 유저 로그인 or 회원가입
    1. ⇒ db 작업 & 세션 작업
... // user의 정보를 가져오는 get요청 // username(키login), id, 프사(키avatar_url) 등이 있음 const userResponse = await fetch("https://api.github.com/user", { headers: { Authorization: `Bearer ${access_token}`, }, }); //응답의 body를 json 객체로 반환 const user = await userResponse.json(); const session = await getSession(); //사용자 찾기. 있다면 id 얻어온 후 session에 저장 const alreadyUser = await prisma.user.findUnique({ where: { github_id: user.id + "", //github id가 number로 되어 있어 string으로 변환 }, select: { id: true, }, }); if (alreadyUser) { session.id = alreadyUser.id; await session.save(); console.log(session.id); return redirect("/home"); } //없다면, db에 user 생성 후 id를 session에 저장 const newUser = await prisma.user.create({ data: { username: user.login, github_id: user.id + "", avatar: user.avatar_url, }, select: { id: true, }, }); session.id = newUser.id; session.save(); return redirect("/home");
app/github/complete/route.js