[DAY53] react 카카오 소셜 로그인

1nxeo·2023년 3월 30일

항해99

목록 보기
51/63
post-thumbnail

react 카카오 소셜로그인

로그인 페이지 부분 로직

  const REST_API_KEY = "8556f063804f3a560b2aa9a26c924279";
  const REDIRECT_URI =
    "http://localhost:3000/oauth";
  const KAKAO_AUTH_URL = `https://kauth.kakao.com/oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&response_type=code`;

return 부분

  <CacaoBtn
                      type="button"
                      onClick={() => {
                        window.location.href = KAKAO_AUTH_URL;
                      }}
                    >
                      <CacaoImg src="https://m.bunjang.co.kr/pc-static/resource/7bf83f72cf54461af573.png" />
                      카카오로 이용하기
                    </CacaoBtn>

리다이렉트 페이지가 필요합 !! ! ! !! !!

import axios from "axios";
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { isLoginActions } from "../redux/modules/loginSlice";
import { cookies } from "../shared/cookies";

const Redirect = (props) => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 발급된 인가코드를 백엔드로 넘겨주기 위해 꺼내오는 작업이 필요하다.
  // code라는 이름으로 파라미터 코드 값을 꺼내오려면 아래와 같이 선언하면 된다.
  const code = new URL(window.location.href).searchParams.get("code");

  //	프론트에서 토큰 가져오는 법 ?
  //   const getKakaoToken = async () => {
  //     try {
  //       const response = axios.post(
  //         `https://kauth.kakao.com/oauth/token`,
  //         `grant_type=authorization_code&client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&code=${code}`,
  //         {
  //           headers: {
  //             "Content-Type": "application/x-www-form-urlencoded",
  //           },
  //         }
  //       );
  //       const token = response.data.access_token;
  //       cookies.set("token", token);
  //     } catch (e) {
  //     }
  //   };

  const authKakaoCode = async (code) => {
    const response = await axios.get(
      `${process.env.REACT_APP_SERVER_URL}/kakao/callback?code=${code}`
    );
    cookies.set("token", response.headers.authorization, {
      path: "/",
      maxAge: 3540,
    });
    cookies.set("nick", response.data.nick, { path: "/", maxAge: 3540 });
  };

  useEffect(() => {
    authKakaoCode(code);
    dispatch(isLoginActions.login());
    alert("로그인 되었습니다.");
    navigate("/");
  }, []);

  return <div>로그인 중</div>;
};

export default Redirect;

그리고 다시 navigate'/'로 보내주면 됨.

profile
항상 피곤한 인서의 개발블로그

0개의 댓글