Oauth
- 웹 및 애플리케이션 인증 및 권한 부여를 위한 개방형 표준 프로토콜
- third-party 애플리케이션이 사용자의 리소스에 접근하기 위한 절차를 정의하고 서비스 제공자의 API를 사용할 수 있는 권한을 부여
Google Client ID
- 아래 사이트에서 프로젝트 생성 후 클라이언트 ID 및 시크릿키 발급
Google 클라우드 플랫폼
로그인 Google 클라우드 플랫폼으로 이동
accounts.google.com
install
- axios : 비동기 HTTP통신 라이브러리
- googleapis : Google API를 호출 및 인증 처리
- cookie-session : 세션 관리
npm install axios googleapis cookie-session
App.js
- 세션설정 추가 (라우터 설정보다 위쪽에 셋팅)
- 인증 라우터 추가
- 인증체크 미들웨어 추가
// 세션 설정
app.use(cookieSession({
name: 'google-auth-session',
keys: [process.env.GOOGLE_SECRET_KEY],
maxAge: 24 * 60 * 60 * 1000 // 세션 만료 시간 24시간
}));
// auth.js 추가
app.use('/auth', require('./routes/auth'));
// 인증을 체크하는 미들웨어
const authInterceptor = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ message: 'Authentication required' });
}
// 토큰 검증 로직 추가
if (token !== 'valid-token') {
return res.status(403).json({ message: 'Forbidden' });
}
next();
};
app.use(authInterceptor);
Auth.js
var express = require('express');
var router = express.Router();
const { StatusCodes } = require('http-status-codes');
const { google } = require('googleapis');
const CLIENT_ID = process.env.GOOGLE_CLIENT_ID;
const CLIENT_SECRET = process.env.GOOGLE_SECRET_KEY;
const REDIRECT_URI = process.env.GOOGLE_REDIRECT_URI;
function getOauth2Client(){
return new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
}
// Google 인증 시작
router.get('/google', (req, res) => {
try{
const oauth2Client = getOauth2Client();
// 사용자에게 Google 로그인 페이지로 리디렉션
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['<https://www.googleapis.com/auth/plus.login>', '<https://www.googleapis.com/auth/userinfo.profile>'],
});
res.redirect(url);
} catch(err){
res.status(StatusCodes.INTERNAL_SERVER_ERROR);
}
});
// Google 인증 후 콜백 처리
router.get('/google/callback', async (req, res) => {
const code = req.query.code;
if (!code) {
return res.redirect('/');
}
const oauth2Client = getOauth2Client();
try {
// 토큰 교환: code를 사용하여 access token과 refresh token을 얻음
const { tokens } = await oauth2Client.getToken(code);
oauth2Client.setCredentials(tokens);
// Google API를 호출하여 사용자 정보를 얻음
const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client });
const userInfo = await oauth2.userinfo.get();
// 사용자 정보를 세션에 저장
req.session.user = userInfo.data;
// 프로필 페이지로 리디렉션
res.redirect('/auth/profile');
} catch (error) {
console.error('Error during authentication:', error);
res.redirect('/');
}
});
// 사용자 프로필 정보
router.get('/profile', (req, res) => {
try{
const user = req.session.user;
res.status(StatusCodes.OK).json(user);
}catch(err){
res.status(StatusCodes.INTERNAL_SERVER_ERROR);
}
});
// 로그아웃
router.get('/logout', (req, res) => {
req.session = null; // 세션 삭제
res.redirect('/');
});
module.exports = router;
'Script > Node.js' 카테고리의 다른 글
[Node.js] Node.js Restful API Example (0) | 2025.01.13 |
---|---|
[Node.js] Node.js 유용한 패키지들 (0) | 2025.01.13 |
[Node.js] Node.js EJS 템플릿 적용 (0) | 2025.01.06 |
[Node.js] Node.js로 간단한 Todo리스트 API 만들기 (0) | 2025.01.03 |
[Node.js] 간단한 Node.js API Server 셋팅하기 (0) | 2025.01.03 |