gitHub OAuth 로그인 구현
FrontEnd/웹 지식

gitHub OAuth 로그인 구현

728x90

gitHub OAuth 로그인 구현하는법을 정리해 보겠다!

 

 

https://www.oauth.com/oauth2-servers/accessing-data/create-an-application/

 

Create an Application - OAuth 2.0 Simplified

Before we can begin, we'll need to create an application on GitHub in order to get a client ID and client secret. On GitHub.com, from the "Settings" page,

www.oauth.com

 

gitHub의 공식 문서를 참조해서 만들어보았다.

 

https://github.com/settings/applications/new

 

GitHub: Where the world builds software

GitHub is where over 83 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and feat...

github.com

https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps#2-users-are-redirected-back-to-your-site-by-github

 

Identifying and authorizing users for GitHub Apps - GitHub Docs

When your GitHub App acts on behalf of a user, it performs user-to-server requests. These requests must be authorized with a user's access token. User-to-server requests include requesting data for a user, like determining which repositories to display to

docs.github.com

 

 

 

먼저 깃허브에 세팅을 해주어야 한다.

 

 

 

OAuth 메커니즘 같은 경우 인증과정이 끝나면 리디렉션을 통해 내 앱으로 돌아오기 때문에 돌아오는 URL이 필요하다고 한다. 

 

 

이렇게 등록을 하면

 

 

ClientID와 secrets를 볼 수 있다.

 

이때, 해당 값들은 절대 자바스크립트파일이나, GitHub에 올리지 않도록 관리해야한다.

.env파일 에 따로 관리를 해주어야 한다!

 

 

 

이제 로그인을 구현해보자.

 

 

const GITHUB_LOGIN_URL = `https://github.com/login/oauth/authorize?client_id=${process.env.REACT_APP_GITHUB_CLIENT_ID}`;
    window.location.assign(GITHUB_LOGIN_URL);

먼저  로그인 버튼이 눌러지면 다음과 같이  인증 페이지로 이동하게 한다. 

 

 

 

이러면 다음과 같은 페이지가 나오고, 인증에 성공하면 설정해두었던 return 페이지로 이동하게 된다.

 

 

그 후 돌아오는 페이지를 보면 authorization code 가 전달된 것을 확인할 수 있다.

/* 깃허브에서 리다이랙트 되는 페이지 */
import React, { useEffect } from "react";

const LoginReturn = () => {
  useEffect(() => {
    const url = new URL(window.location.href);
    const authorizationCode = url.searchParams.get("code");
    console.log(authorizationCode); //인증 코드
  });

  return (
    <>
      <div></div>
    </>
  );
};

export default LoginReturn;

 

 

이렇게 받은 code를 가지고 서버단에서 AccessToken을 발급받으면 된다. 

 

AccessToken을 프론트단에서 받는것보다 서버단에서 받는것이 보안상 더 좋다고 한다.

 

 

app.post("/login", async (req, res) => {
  axios
    .post(
      "https://github.com/login/oauth/access_token",
      {
        client_id: process.env.GITHUB_CLIENT_ID,
        client_secret: process.env.GITHUB_CLIENT_SECRET,
        code: req.body["authorizationCode"],
      },
      {
        headers: {
          accept: "application/json",
        },
      }
    )
    .then((response) => {
      console.log(response.data);
      res.status(200).json({ accessToken: response.data["access_token"] });
    });
});

 

이 받은 access Token을 가지고 다시 서버에 이번엔 gitHub User 정보를 받을 수 있도록 요청해준다.

 

/* 깃허브에서 리다이랙트 되는 페이지 */
import React, { useEffect } from "react";
import { getUserDataApi, loginApi } from "../api/api";

// type getUserInfoType = {
//   data: {
//     name: string;
//     login: string;
//     html_url: string;
//     public_repos: string;
//   };
// };

const LoginReturn = () => {
  useEffect(() => {
    //useEffect에서 async를 사용하기 위함
    const effect = async () => {
      const url = new URL(window.location.href);
      const authorizationCode = url.searchParams.get("code");
      console.log(authorizationCode); //authorization code

      if (authorizationCode) {
        //코드를 제대로 받으면 AccessToken을 받아옴
        const getAccessToken = await loginApi({ authorizationCode });
        console.log(getAccessToken);
        const userData = await getUserDataApi({ getAccessToken });
        console.log(userData);
      }
    };
    effect();
  });

  return (
    <>
      <div>로그인중...</div>
    </>
  );
};

export default LoginReturn;

 

 

 

이제 받아온 데이터를 활용해서 로그인을 구현하거나, 페이지를 랜더링하는등의 동작을 수행하면 된다!

 

728x90

'FrontEnd > 웹 지식' 카테고리의 다른 글

[GIT] 레포기록을 유지한 채 다른 레포로 옮기기  (1) 2023.11.14
리액트 build파일 경로 설정  (0) 2022.09.26
쿠키  (0) 2022.09.20
HTTP란?  (0) 2022.09.20
Unix와 Windows 파일 시스템  (0) 2022.08.30