박주니 개발 정리

naver login 구현 방법 본문

react

naver login 구현 방법

박주니 2023. 2. 1. 13:21
728x90
반응형

1. https://developers.naver.com/main/ 에 접속하셔서 Products>네이버 로그인>네이버 로그인 API를 접속합니다. 네이버 로그인에 오픈 API이용 신청을 클릭합니다.

 

NAVER Developers

네이버 오픈 API들을 활용해 개발자들이 다양한 애플리케이션을 개발할 수 있도록 API 가이드와 SDK를 제공합니다. 제공중인 오픈 API에는 네이버 로그인, 검색, 단축URL, 캡차를 비롯 기계번역, 음

developers.naver.com

2. 애플리케이션 등록 (API 이용신청) 진행합니다.

  • 추가 설명) 등록시 주의해야할 부분은 로그인 오픈 API 서비스 환경입니다. 환경 추가 select를 누르시면 적용할 부분을 선택을 하는데 저는 웹에 적용을 했기 때문에 PC 웹으로 선택을 했습니다. 앱으로 하시는 경우에는 적용하고자하는 android 또는 ios에 맞게 선택하시면 됩니다.
  • 서비스 url 및 네이버 로그인 callback url 설정 방법) 네이버 로그인을 적용하는 url을 넣으시면 됩니다. 저는 http://localhost:3001/nomalAdmin에 넣었기 때문에 서비스 url 및 네이버 로그인 callback url 동일하게 넣었습니다.

3. 내 애플리케이션에서 연결하고자하는 애플리케이션을 선택하고 개요를 클릭합니다. 그 다음 애플리케이션 정보에서 Client ID를 확인합니다. 네이버 로그인 연결할 때 필요한 clientId 입니다.

  • 추가 설명) Client ID는 해당 애플리케이션 정보에 고유 id입니다. 

4. index.html 에 naver login sdk script를 설정합니다.

    <script
      src="https://static.nid.naver.com/js/naveridlogin_js_sdk_2.0.2.js"
      charset="utf-8"
    ></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <script
      src="https://static.nid.naver.com/js/naveridlogin_js_sdk_2.0.2.js"
      charset="utf-8"
    ></script>
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>Test</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root" class="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>
  • 참고 사항) 위치는 public>index.html 입니다. 
  • 주의 사항) 제가 nextjs에 naver login을 설정했을 때 sdk_2.0.0으로 해도 문제가 없었는데 react로 동일한 버젼으로 할려고 하니깐 접속 에러가 나는 것을 볼 수 있었습니다. react로 하시는 경우 sdk_2.0.2로 설정하시는 것을 추천합니다.

5. 해당 page js에 naver login 기본 폼을 설정합니다. 저는 NomalConnect.js에 naver login을 설정할 것이기 때문에 여기에 넣었습니다.

  • 추가 설명)
    • clientId ▶ clientId는 제가 설명한 3번에서 애플리케이션 정보를 보시면 확인하실 수 있습니다. 
    • callbackUrl ▶callbackUrl는 내 애플리케이션에서 api 설정을 보시면 등록시 callbackUrl 설정하신 것을 보실 수 있습니다. 제가 설명한 2번을 참고하시면 이해하기 쉬우실 것입니다.
    • loginButton▶naver button style을 변경 가능합니다.
    • naver sdk에 id naverIdLogin 넣으면 기본적인 네이버 버튼을 제공합니다. 
  useEffect(() => {
    let naverLogin = new window.naver.LoginWithNaverId({
      clientId: `${process.env.REACT_APP_NAVER_CLIENT_ID}`,
      callbackUrl: `http://localhost:3001/nomalAdmin`,
      loginButton: { color: "green", type: 3, height: "50" },
    });
    naverLogin.init();
    naverLogin.logout();
    try {
      naverLogin.getLoginStatus((status) => {
        if (status) {
          console.log(naverLogin.user);
        }
      });
    } catch (err) {
      console.log(err);
    }
  }, []);

  return (
    <div className="connect">
		<div id="naverIdLogin" />
    </div>
  );

6. 네이버 로그인 후 naverLogin.user에 대한 데이터가 정상적으로 나오는 지 확인합니다.

  • 추가 설명) console.log에 나오는 데이터는 등록시 사용 API에서 제공 정소 선택에 필수로 선택한 값만 가지고 올 수 있습니다. 내 애플리케이션에서 API설정을 보시면 확인하실 수 있습니다. 그럼 여기서 데이터 받아서 서버 요청하는 것은 쉬우니 따로 설명은 하지 않겠습니다.

알아두면 좋을 것

네이버 로그인 설정할 때 nextjs로도 설정해봤고 reactjs로도 설정해봤는데 다른 부분이 있다면 sdk_2.0.0으로 하느냐 아니면 sdk_2.0.1이였습니다. 구글에는 sdk_2.0.0으로 하는 것을 많이 보여주는데 그것은 nextjs로 할 때 잘적용되었지만 react로 여러번 시도해봤지만 안돼서 sdk_2.0.1로 변경하니 되는 것을 보고 그 부분 참고해서 진행해주시면 됩니다.

 

 

728x90
반응형
Comments