CSRF

2023. 12. 13. 21:05Node.js Express

const form_get_csrf = (req, res) => {
    return res.status(200).render('form_post_csrf',{"csrfToken":req.csrfToken()});
}

const form_post_csrf = (req, res) => {
    return res.status(200).json({"title":req.body.title, "data":req.body.data});
}
module.exports = {
    form_get_csrf,
    form_post_csrf,
}​
const express = require('express')
const csrf = require('csurf');
const csrfProtection = csrf({ cookie: true });

const {form_get_csrf, form_post_csrf} = require('../controllers/form_controller')
const router = express.Router();

router.route('/csrf').get(csrfProtection, form_get_csrf).post(csrfProtection, form_post_csrf)

module.exports = router;

 

<!doctype html>
<html lang="ko">
<head>
    <meta charset="utf-8">
    <title>csrf test </title>
</head>
<body>
    <form method = "POST">
        <p>csrfToken :<input name= "_csrf" value = <%=csrfToken%> />
        <p>제목 : <input type="text" name = "title" value = "test title"></p>
        <p>내용 : <input type="text" name = "data" value = "test data"> </p>
        <input type="submit">
    </form>
    
    <p>-------------------------------------------</p>    
    
    <a href = "/">back home</a>
</body>
</html>

 

csrf token을 이용한 csrf 방지는 csurf라는 모듈을 이용하면 간단하게 구축 할 수 있다

get 요청이 들어 왔을 때 csrf token도 같이 보내 주는 것 말고는 기존과 같다

'Node.js Express' 카테고리의 다른 글

Session  (0) 2023.12.13
WebSocket  (0) 2023.12.13
MongoDB  (0) 2023.12.13
Form Data  (0) 2023.12.13
Node.js express Studying project  (0) 2023.12.11