투케이2K

80. (NodeJs) [Mac Os] [OAuth] : 구글 계정 사용해 OAuth 인증 및 Response 응답 데이터 확인 본문

NodeJs

80. (NodeJs) [Mac Os] [OAuth] : 구글 계정 사용해 OAuth 인증 및 Response 응답 데이터 확인

투케이2K 2024. 1. 16. 21:27

[개발 환경 설정]

개발 툴 : VS CODE

개발 언어 :NodeJs

 
 

[app.js : 소스코드]

 

// ----------------------------------------------------------------------------------------------

const express = require('express')
const app = express()

// ---------------------------------------

app.set('view engine', 'ejs') // [Page] : [Render]
app.set('views', './views') // [Page] : [Render]

// ---------------------------------------

var bodyParser = require('body-parser'); // [body-parser 사용]

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// ----------------------------------------------------------------------------------------------

// [Get] : Path = [/login] : http://localhost:3000/login
app.get('/login', function (req, res) {
    console.log("")
    console.log("==============================================================================")
    console.log("[Server] :: [App] :: [Path = /login] :: [Start]")
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Headers] :: " + JSON.stringify(req.headers))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Cookies] :: " + JSON.stringify(req.cookies))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Query] :: " + JSON.stringify(req.query))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Body] :: " + JSON.stringify(req.body))
    console.log("==============================================================================")
    console.log("")


    try {

        // [url 생성]
        let url = 'https://accounts.google.com/o/oauth2/v2/auth/userinfo.email';


        // [파라미터 추가]
        //*
        url += "?client_id=393 ...... htrjr.apps.googleusercontent.com"; // [구글 클라이언트 아이디]
        url += "&redirect_uri=http://localhost:3000/getRender"; // [리다이렉트 주소]
        url += "&response_type=code"; // [response_type]
        url += "&scope=email profile"; // [구글에 등록된 유저 정보 email, profile을 가져온다]
        // */


        // [리다이렉트 수행]
        res.redirect(url);

    }
    catch (err) {
        res.status(500).send(JSON.stringify({"error" : err})); // [http 반환]
    }
    
})

// ----------------------------------------------------------------------------------------------

// [Get] : Path = [/getRender] : http://localhost:3000/getRender
app.get('/getRender', function (req, res) {
    console.log("")
    console.log("==============================================================================")
    console.log("[Server] :: [Get] :: [Path = /getRender] :: [Start]")
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Headers] :: " + JSON.stringify(req.headers))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Cookies] :: " + JSON.stringify(req.cookies))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Params] :: " + JSON.stringify(req.query))
    console.log("--------------------------------------------------------------------------")
    console.log("[INPUT] :: [Body] :: " + JSON.stringify(req.body))
    console.log("==============================================================================")
    console.log("")

    // [파라미터값 체크]
    if (req.query != undefined && req.query != ""){

        const { code } = req.query; // [파라미터 값 확인]

        res.render("index", {"code" : code}); // [http 반환]
    }
    else {
        res.status(403).json({ "result" : "error" }); // [http 반환]
    }

})

// ----------------------------------------------------------------------------------------------

// [Server] : [Start]
//*
app.listen(3000, function () {
    console.log("")
    console.log("==============================================================================")
    console.log("[Server] :: [Port = 3000] :: [Start]")
    console.log("==============================================================================")
    console.log("")
})
// */

// ----------------------------------------------------------------------------------------------
 

[index.ejs : 소스코드]

 

<!DOCTYPE HTML>
<html lang="ko">
<head>
    <title>WebTest</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    




    <!-- ================================================================================== -->
    <!-- [반응형 구조 만들기] -->
    <!-- ================================================================================== -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
    




    <!-- ================================================================================== -->
    <!-- [자바 스크립트 및 j쿼리 파일] -->
    <!-- ================================================================================== -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script> 




    <!-- ================================================================================== -->
    <!-- [내부 CSS 스타일 지정] -->
    <!-- ================================================================================== -->
    <style>


        /* [전체 설정 실시] */
    	* {
            font-family : 'Noto Sans KR' , sans-serif;           
            margin : 0;
            padding : 0;
    	}
    	




        /* [html , body 설정] */
        html, body{			
            width : 100%;          
            height : 100%;
            margin : 0 auto;
            padding : 0;
            border : none;         

            /* [모바일 스크롤 시 부드럽게 처리] */
            overflow:scroll-y; 
            -webkit-overflow-scrolling:touch;
        }
        /* [body 스크롤바 메인 스타일 지정] */
        body::-webkit-scrollbar {           
            width: 20px;                 
            background-color: #c1c1c1;
        }
        /* [body 스크롤바 thumb 스타일 지정] */
        body::-webkit-scrollbar-thumb {                 
            background-color: #444444;
        }
                     
    </style>
    




    <!-- ================================================================================== -->
    <!-- [내부 자바스크립트 J쿼리 이벤트 지정] -->    
    <!-- ================================================================================== -->
    <script>

        /* [dom 생성 및 이벤트 상시 대기 실시] */
        document.addEventListener("DOMContentLoaded", ready);
        function ready(){
            console.log("");
            console.log("=====================================================");
            console.log("[window ready] : [start]"); 
            console.log("=====================================================");           
            console.log("");
        }





        /* [html 최초 로드 및 이벤트 상시 대기 실시] */
        window.onload = function() {
            console.log("");
            console.log("=====================================================");
            console.log("[window onload] : [start]");
            console.log("=====================================================");
            console.log(""); 

        };

    </script>
    
</head>





<!-- ================================================================================== -->
<!-- [body 콘텐츠 작성] -->
<!-- ================================================================================== -->
<body>

    <h1> <%= code %> </h1>

</body>


</html>
 

[결과 출력]


반응형
Comments