아래 방식으로 요청시
axios.get('http://localhost:3000/users/login/kakao')
이런 에러가 뜬다. 나는 임시적으로 nestjs에서 Cors전부 오픈 해놓은 상태이다.
app.enableCors();
Access to XMLHttpRequest at 'https://accounts.kakao.com/login?continue=https%3A%2F%2Fkauth.kakao.com%2Foauth%2Fauthorize%3Fresponse_type%3Dcode%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A3000%252Fusers%252Fkakao%252Fcallback%26through_account%3Dtrue%26client_id%3D51f39f3e4994f41f3dd78b0a4d174a86' (redirected from 'http://localhost:3000/users/login/kakao') from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
withCredentials true 등등 여러 방식을 도전해봤지만, axios로 /users/login/kakao를 실행 시 로그인 페이지롤 가는 것에서 에러가 생긴다.
@Public()
@Get('/login/kakao') // /:socialLogin으로 병합할수잇을까?
@UseGuards(AuthGuard('kakao')) //AuthGuard만 dynamic하게 바꿔주면된다.흠.
async kakaoLogin() {}
@Public()
@Get('/kakao/callback')
@UseGuards(AuthGuard('kakao'))
// @Redirect('http://localhost:3001/member', 302)
async kakaoLoginCallback(
@Req() req: any,
@Res({ passthrough: true }) res: Response,
): Promise<void> {
const { email, fullName, kakaoToken } = req.user;
console.log(email);
const { tokens, userId } = await this.usersService.socialLogin(
fullName,
email,
);
await this.postsService.insertStories(kakaoToken, userId);
return tokens
}
콘솔에서 찍다가 network를 확인해본 결과
location:
https://kauth.kakao.com/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fusers%2Fkakao%2Fcallback&client_id=51f39f3e4994f41f3dd78b0a4d174a86
은 잘 뜨는데 여기로 이동을 못하는 중이다.
thunderclient/postman 을 사용했을때는 잘 됬는데 여기서 안되는 것을 보니 3곳의 (localhost 3000, 3001, 그리고 카카오) 통신에서 문제가 생기는것 같다. 3000-(카카오로그인 페이지+콜백)-3001
다양한 방식으로 새로 시도를 했을 때,
1. React 에서 세팅해서 아에 kauth전체 링크 걸기.
clientID: process.env.KAKAO_ID,
clientSecret: '',
callbackURL: "http://localhost:3000/users/kakao/callback",
windows.location? 인가 했을때
3000으로 토큰이 잘 리턴된다.
문제: 문제라고 할건 아니지만, 개인적으로 프론트에 .env라도 , clientId같은 민감한 정보를 저장하기 싫었다.
<a href="http://localhost:3000/users/login/kakao"
성공적으로 페이지를 이동하고 로그인이 되면서, 토큰을 반환했다.
이제 새로운 문제에 부딛혔다.
바로 3000으로 토큰값이 반환되면서, url이 3000/....으로 뜨면서 string일 보이는 것이였다.
res.redirect를 사용하려는데 redirected(boolean)밖에 안보여서 당황했지만 express기반의 import { Response } from 'express';
을 사용하면 정상 작동했다.
맨처음에서는 URL or header 에 넣어서 보낼까 싶었는데, 다시 한번 민감한 내용은 없지만 보안에 신경쓰고 싶어서
뭔가 쿠키가 좀 더 좋을것 같았다. express에서 사용했었던
import * as cookieParser from 'cookie-parser';
app.use(cookieParser());
똑같이 세팅하고
@Public()
@Get('/kakao/callback')
@UseGuards(AuthGuard('kakao'))
// @Redirect('http://localhost:3001/member', 302)
async kakaoLoginCallback(
@Req() req: any,
@Res({ passthrough: true }) res: Response,
): Promise<void> {
const { email, fullName, kakaoToken } = req.user;
console.log(email);
const { tokens, userId } = await this.usersService.socialLogin(
fullName,
email,
);
await this.postsService.insertStories(kakaoToken, userId);
res.cookie('tokens', tokens);
res.redirect('http://localhost:3001/socialLogin');
}
카카오로그인을 눌렀을때, 로그인 성공 시 strategy에서 가져온 정보들로, 유저를 저장하면서 (유저의 스토리도 내 db에 같이 저장했다).
redirect 을 했을때 리액트에 잘 세팅을 했다
<Route path="/socialLogin" element={<SocialLogin/>}/>
여기 페이지에서 쿠기를 가지고 localstorage에 토큰을 넣고, navigate으로 메인 페이지로 이동했다.
10.28() 로컬 호스트에서는 잘 됬는데 vercel을 사용시 쿠키가 전달되지 않았다.
https://velog.io/@saro3/카카오톡-실패-기록-ㅠ-vercel-문제일까?-다른-방식으로-변경