Programming/JavaScript & TypeScript

[Node Express - Angular5] JWT 기반 사용자 인증 개발 - Node 편

Bonita SY 2019. 7. 19. 16:53
728x90
반응형

JWT 모듈 import와 JWT 비밀키 설정

var jwt = require('jsonwebtoken');

app.set('jwt-secret', "please_input_jwt_key in here");

 

 

JWT 생성

                        var u_token = new Promise(function(resolve, reject) { 
                            jwt.sign({ 
                                    user_id: id
                                }, 
                                req.app.get('jwt-secret'), 
                                { 
                                    expiresIn: '1h' 
                                }, (err, token) => { 
                                    if(err)     reject(err); 
                                    resolve(token); 
                                }); 

                        }); 
                        u_token.then(function(token){
                            res.status(200).json({"status": "OK", "token": token}); 
                        }).catch(function(err) {
                            res.status(403).json({"status": "None"}); 
                        });

 

JWT 검증

    var password = req.body.passwd; 
    var token = req.headers.authorization; 
    token = token.replace("Bearer ", ""); 

    if(!token) { 
        return res.status(403).json({ 
            "status": "None" 
        }); 
    } 

    var user_info = new Promise(function(resolve, reject) { 
        jwt.verify(token, req.app.get('jwt-secret'), (err, decoded) => { 
            if(err) reject(err); 
            resolve(decoded); 
        }); 
    }); 
    user_info.then(function(decoded){ 
        var id = decoded.id;  
            if(err) { 
                res.status(403).json({"status": "None"}); 
            } else {
                var exp_time = new Date; 
                exp_time.setDay(exp_time.getDay() + 1);
                ...
            }
    });
728x90
반응형