반응형
React,Express의 기초코드를 설명하진 않는다.
1. 프론트에서 인증코드 요청
/signin 페이지를 다음과 같이 만들었다.
버튼을 클릭하면 카카오 인증코드를 받을 수 있는 페이지로 리다이렉트 된다.
const auth = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const kakaoAuth = `https://kauth.kakao.com/oauth/authorize?client_id=${rest_api_key}&redirect_uri=${redirect_uri}&response_type=code`;
window.location.assign(kakaoAuth);
};
return (
<>
<Form onSubmit={auth}>
<KakaoSignin>Kakao Signin</KakaoSignin>
</Form>
</>
);
2. 인증 코드 전달
위의 kakaoAuth페이지에서 확인을 누르면 /auth 페이지로 이동한다.
/auth 페이지에 url 파라미터로 붙은 code가 인증코드이다.
3. 인증코드 전송
이제 이 인증코드를 서버로 전송한다.
로컬에 만든 `localhost:4000/auth`에 post요청으로 인증코드를 전송하였다.
const Auth = () => {
const navigate = useNavigate();
const authMutation = async (authToken: string) => {
const code = await axios
.post('http://localhost:4000/auth', {
authToken,
})
.then((res) => res.data);
return code;
};
useEffect(() => {
// url parameter의 code를 authToken으로 저장한다.
const authToken = new URL(window.location.href).searchParams.get('code');
try {
if (!authToken) return;
authMutation(authToken);
// 토큰 전송후 '/'페이지로 리다이렉트
navigate('/');
} catch (err) {
alert(err);
}
}, []);
return <>auth loading..</>;
};
export default Auth;
4. 인증코드로 카카오에 토큰 요청
express로 간편하게 서버를 만들었다.
프론트에서 받은 인증코드와 카카오dev페이지에서 등록한 rest_api_key, redirect_uri등을 카카오에 post로 보내준다.
app.post('/auth', auth);
const auth = async (req, res) => {
const { authToken } = req.body;
try {
const kakaoResponse = await axios
.post(
'https://kauth.kakao.com/oauth/token',
{},
{
header: {
'Content-type': 'application/x-www-form-urlencoded;charset=utf-8',
},
params: {
grant_type: 'authorization_code',
client_id: process.env.KAKAO_REST_API_KEY,
code: authToken,
redirect_uri: `http://localhost:3000/auth?social_provider=kakao`,
},
}
)
.then((res) => res.data.access_token);
console.log('카카오응답', kakaoResponse);
res.send(kakaoResponse);
} catch (err) {
console.log('에러', err);
}
};
그러면 응답으로 토큰관련 정보들을 내려준다.
DB도 안만들고 코드부터 써서 여기서 멈춤
DB만들고 그 이후도 작성하겠음
+ mysql 비번초기화하는데 하루 반걸림..
https://wnsdufdl.tistory.com/536
반응형
'개발 > 그 외' 카테고리의 다른 글
webpack에서 vite로 마이그레이션 (1) | 2024.01.07 |
---|---|
Rest 정리 (0) | 2023.11.23 |
라이브러리 버전의 디테일을 관리하는 package-lock.json (0) | 2022.12.22 |
핵클 라이브러리 : A/B 테스트, 기능 플래그, 실시간 데이터 분석, 모니터링 (0) | 2022.04.01 |
react와 next.js를 비교하며 라이브러리와 프레임워크 차이 알아보기 (0) | 2022.01.25 |