@fastify/oauth2 라이브러리를 사용합니다
일단, oauth2 라이브러리를 yarn으로 설치합니다. fastify-oauth2 라이브러리는 간단하게 oauth 로그인 기능을 구현 할 수 있도록 보조합니다.
yarn add @fastify/oauth2
@Type 추가
@fastify/oauth2 라이브러리를 커스텀해서 사용 할 때, 타입 스크립트에서 인식하지 못하는 경우가 있어 타입을 미리 선언 해줍니다.
루트 디렉터리에 @types/index.ts에 정의하였습니다
import {OAuth2Namespace} from "@fastify/oauth2";
declare module "fastify" {
interface FastifyInstance {
kakaoOAuth2: OAuth2Namespace;
}
}
마지막으로, tsconfig.json에 “types”: [“./@types”]를 추가합니다
라이브러리 커스텀 하기
기본적으로 제공하는 구글, 스포티파이 등의 플랫폼도 있지만, 카카오는 없기 때문에 직접 custom 해야 합니다. 이 또한 틀을 제공하고 있습니다
fastify.register(oauthPlugin, {
name: 'customOauth2',
credentials: {
client: {
id: '<CLIENT_ID>',
secret: '<CLIENT_SECRET>'
},
auth: {
authorizeHost: 'https://my-site.com',
authorizePath: '/authorize',
tokenHost: 'https://token.my-site.com',
tokenPath: '/api/token'
}
},
startRedirectPath: '/login',
callbackUri: 'http://localhost:3000/login/callback',
callbackUriParams: {
exampleParam: 'example param value'
}
})
저는 아래와 같이 채웠습니다. Kakao 개발 홈페이지에 들어가서 id와 secret을 발급 받고, redirectURI만 설정하면 됩니다.
token을 받아서 로그인을 처리 할 것이기에, callback 파라미터로 responese_type : "code"로 설정합니다
민감한 정보들은 따로 빼두고, 불러오는 식으로 사용하였습니다.
const kakaoAuth = {
name: "kakaoOAuth2",
scope: ["account_email", "profile_nickname", "gender"],
credentials: {
client: {id: _kakao.clientId, secret: _kakao.clientSecret},
auth: {
authorizeHost: "https://kauth.kakao.com",
authorizePath: "/oauth/authorize",
tokenHost: "https://kauth.kakao.com",
tokenPath: "/oauth/token",
},
},
startRedirectPath: "/auth/kakao",
callbackUri: "/auth/kakao/callback",
callbackUriParams: {
response_type: "code",
},
};
선언한 kakaoAuth는 fastify.register(oauth2,kakaoAuth)로 미들웨어 등록을 합니다
URI 설정
export default async function (fastify: any) {
fastify.get("/callback", async (req: FastifyRequest, reply: FastifyReply) => {
console.log("req.query >>", req.query);
const {token} = await fastify.kakaoOAuth2.getAccessTokenFromAuthorizationCodeFlow(req);
const {data} = await axios.get("https://kapi.kakao.com/v2/user/me", {headers: {Authorization: `Bearer ${token.access_token}`}});
const {kakao_account} = data
const ssoid = data?.id;
const email = kakao_account?.email;
const {nickname} = kakao_account?.profile;
const login = await checkSSO(LOGIN_TYPE.KAKAO, ssoid, {nickname, email});
reply.send(login);
});
}
로그인 처리를 백엔드에서 하고, api를 트리 구조로 계층을 나누었기에 GET URI는 "/callback"만 적었습니다
실제 접근 할 때는 /auth/kakao
에서 로그인하면 카카오 서버는 /auth/kakao/callback
로 제가 요청한 데이터를 던집니다
callback으로 날라온 데이터를 저희는 처리해야 합니다. 사전에 선언한 kakao oauth 클라이언트에 받은 code를 넣어 토큰을 발급 받습니다
마치며
![](https://i.imgur.com/muRa2qt.png)
이제 버튼 리스너에 만들어진 api를 추가하면, 카카오 로그인 창이 뜨고, 데이터 제공 동의하겠느냔 이미지가 뜹니다.
타입이 인식이 잘 되지 않아 애를 먹었는데, 좀 더 많은 삽질을 경험 할 필요를 느낍니다
'DEV > Backend' 카테고리의 다른 글
ICE - WebRTC Peer 연결 프로토콜 (0) | 2023.02.24 |
---|---|
Error - TypeORM DataSource is not set for this entity (0) | 2023.02.14 |
AWS에 올린 MySQL 외부 접속 안됨 (0) | 2023.02.01 |
It is required that your private key files are NOT accessible by others. This private key will be ignored. (0) | 2023.02.01 |
ERROR 1698 (28000) Access denied for user 'root'@'localhost' (0) | 2023.02.01 |