liner server api제작 - 환경설정(2)

unow30·2021년 3월 9일
0

liner

목록 보기
3/8
"dependencies": {
    "express": "^4.17.1",
    "axios": "^0.21.1",
    "body-parser":"^1.19.0",
    "cookie-parser": "^1.4.5",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "eslint": "^7.16.0",
    "helmet": "^4.4.1",
    "jsonwebtoken": "^8.5.1",
    "morgan": "^1.10.0",
    "winston": "^3.3.3",
    "mysql2": "^2.2.5",
    "sequelize": "^6.3.5",
  },
  "devDependencies": {
    "nodemon": "^2.0.7",
    "sequelize-cli": "^6.2.0"
  }

7. helmet

공식문서
x-powerd-by 헤더 제거 이유

secure Express apps by setting various HTTP headers.

const express = require("express");
const helmet = require("helmet");

const app = express();

//this...
app.use(helmet());

//is equivalent to this
app.use(helmet.contentSecurityPolicy());
// set Content-Security-Policy header witch helps mitigate cross-site scription attacks

app.use(helmet.dnsPrefetchControl());
//sets the X-DNS-Prefetch-Control header to help control DNS prefetching, which can improve user privacy at the expense of performance.(성능을 희생하면서 사용자 개인정보 보안을 향상시킨다.)

app.use(helmet.expectCt());
// set Expect-CT header witch helps mitigate misissued SSL certificates.(잘못 발급된 인증서)

app.use(helmet.frameguard());
//sets the X-Frame-Options header to help you mitigate clickjacking attacks.(사용자 인터페이스 교정 공격, ul교정 공격, ul 교정으로 분류됨) 사용자가 인식하는 것돠 다른 것을 클릭하도록 사용자를 속이는 기술

app.use(helmet.hidePoweredBy());
//removes the x-powered-by header, which is set by default in some frameworks (like express) header 제거로 제한적인 보안 이점을 얻으며, 대역폭 절약을 위해 대부분 제거한다.

app.use(helmet.hsts());
// sets the Strict-Transport-Security header which tells browsers to prefer HTTPS over insecure HTTP.

app.use(helmet.ieNoOpen());
//sets the X-Download-Options header, which is specific to Internet Explorer 8. It forces potentially-unsafe downloads to be saved, mitigating execution of HTML in your site's context. 안전하지 않은 다운로드 저장 강제 강제

app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());

app.use(helmet.referrerPolicy());
//The Referer HTTP request header contains an absolute or partial address of the page making the request. 현제 요청 페이지 이전 페이지 표시

app.use(helmet.xssFilter());

// set custom options like this
app.use(
	helmet({
    	referrerPolicy:{policy:"no-referrer"},
   	})
)


//이전에 사용해본 helmet 설정
app.use(helmet({
  frameguard: false,
}))
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'", "'unsafe-inline'",  `${process.env.BASE_URL}`],
      scriptSrc: ["'self'", "'unsafe-inline'", "https://code.jquery.com/", "https://ajax.aspnetcdn.com/", `${process.env.BASE_URL}`],
      imgSrc: ["'self'", "'unsafe-inline'", "https://cdn.channel.io/plugin/images/", 'data:'],
      objectSrc: ["'none'"]
    }
  })
)

helmet은 express같은 프레임워크와 호환되는 connect-style 미들웨어이다.
koa 프레임워크 전용인 koa-helmet도 있다.

8. jsonWebToken

공식문서

전자서명된 URL-safe(URL로 이용할 수 있는 문자만 구성된)의 JSON이다.
과거의 일반 토큰은 의미없는 문자열을 사용하여 정보를 담거나 할 수 없었다.
토큰 만료 수단도 없고, 토큰 검사시 db에 접근해야 했으며, 로그아웃 등으로 인한 토큰 관리가 어려웠다.

jsonwebtoken은 클레임 기반(토큰 안에 여러 정보를 담고 있다.)토큰의 대표격이다.

//old token 
{
    "code": 0,
    "msg": null,
    "response":{
        "token": "a9ace025c90c0da2161075da6ddd3492a2fca776", //=> no means str, can't controll
        "now": 1512446940,
        "expired_at": 1512448740
    }
}

//jwt token
var jwt = require('jsonwebtoken');
jwt.sign({ foo: 'bar' }, 'shhhhh');
//토큰 생성
//payload, secretKey, otions객체,callback추가가능

var verify = jwt.verify(token, secretKey)
///토큰 payload 해독 token은 아래 그림의 왼쪽 토큰값을 해독하여 payload값만 가져온다.

"mysql2": "^2.2.5",
"sequelize": "^6.3.5",
"nodemon": "^2.0.7",
"sequelize-cli": "^6.2.0"

9. mysql2

MySQL client for Node.js with focus on performance.

10. sequelize

공식문서

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.

11. sequelize-cli

공식문서

The Sequelize Command Line Interface (CLI)

12. nodemon

공식문서

nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.
server 파일의 변경이 감지되면 애플리케이션을 자동으로 다시 시작하게 하는 개발 보조 툴

13. body-parser

공식문서

HTTP request, response시 전송되는 데이터를 자동으로 toString(), json()으로 파싱하는 미들웨어
express에는 body-parser가 내장되있어 따로 require하지 않아도 된다.

req.body는 기본으로 undefined가 설정되어있다. 그래서 bodyParser같은 미들웨어를 사용하여 요청 데이터 값에 접근해야 한다.

const express = require('express')
const app = express()
//bodyparser가 내장되어있어 따로 설치하지 않아도 아래처럼 사용한다.
app.use(express.json())// for parsing application/json
app.usee(express.urlencoded({extended: false}))//for parsing application/x-www-form-urlencoded
  1. bodyParser.json()은 'application/json' 방식의 Content-Type 데이터를 받아준다.

  2. bodyParser.text()는 'text/xml' 방식의 Content-Type 데이터를 받아준다.

  3. bodyParser.urlencoded({...})는 'application/x-www-form-urlencoded'(url 인코딩) 방식의 Content-Type 데이터를 받아준다. (jQuery.ajax의 기본 타입)
    요약하면 post 방식으로 데이터를 보낼때는 content 타입이 다음과 같아야 한다.

    (1) application/x-www-form-urlencoded : body에 key:value타입의 값을 넣는다.
    (2) text/plain : body에 단순 text값을 넣는다.
    (3) multipart/form-data : file 전송시 body에 바이너리 타입의 데이터를 넣는다.

0개의 댓글