node.js 인터페이스 구축(6): Node - jwt를 사용하여 token 구현

3174 단어 node.js
이전에 실행된 로그인 인터페이스가res.json ({msg: "success"} 로 정확하게 되돌아오면 실제 응용 프로그램에서 되돌아오는 것은token입니다.
token은 컴퓨터 인증에서 영패(임시)를 의미하며 일부 조작을 수행할 권리를 대표하는 대상이다.다음을 포함합니다.
액세스 토큰(Access token)은 액세스 제어 작업 바디의 시스템 객체를 나타냅니다.
보안 토큰(Security token) 또는 하드웨어 토큰, 예를 들어 U방패 또는 인증 토큰 또는 암호화 토큰이라고 불리는 컴퓨터 신분 검사의 물리 장치;
세션 토큰(Session token), 대화에서 유일한 신분 식별자;
영패화 기술(Tokenization)은 민감한 정보 항목의 처리 과정을 대체한다.
 
이번에 우리는 jsonwebtoken을 사용하여 token을 실현한다.우선 jsonwebtoken을 설치해보도록 하겠습니다.
npm install jsonwebtoken

다음api에서users.js에 jsonwebtoken 도입
const jwt = require('jsonwebtoken'); 

jwt에sign () 방법이 있습니다. 서명과 유사합니다.
jwt.sign(" ", " ", " ", " ");
// json
secretOrPublicKey( )  is a string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. If  jwt.verify  is called asynchronous,  secretOrPublicKey  can be a function that should fetch the secret or public key.
 
jwt를 사용하기 위해.sign () 방법, config의 키.js에 추가secretOrPublicKey。
module.exports = {
    mongoURI:"mongodb://127.0.0.1:27017/dbname",
    secretOrKey:"secret"
}

그런 다음 API의 사용자.js에서 도입
const User = require("../../models/Users");

다음에 로그인 인터페이스를 수정하고 isMatch의 정확한 반환값을 token으로 변경합니다
router.post("/login",(req,res)=>{
    const email = req.body.email;
    const password = req.body.password;
    // 
    User.findOne({email})
        .then(user =>{
            if(!user){
                return res.json({email:" "});  //return res.status(404).json({email:" "});
            }
            //    token
            bcrypt.compare(password,user.password)
                .then(isMatch=>{
                    if(isMatch){
                        const rule = {id:user.id,name:user.name};   
                        // id name token
                        // jwt.sign(" ", " ", " ", " ");
                        jwt.sign(rule,keys.secretOrKey,{expiresIn:3600},(err,token)=> {
                                if(err) {throw err};
                                res.json({
                                    success:true,
                                    token:"dj" + token     
                                // +taken token
                                        "success": true,
    // "token": "djeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjViN2Q5MDM0NjAwZGI5MGQ5MDhhN2U5YSIsIm
    // 5hbWUiOiJkaiIsImlhdCI6MTUzNDk5NzkxNCwiZXhwIjoxNTM1MDAxNTE0fQ.bWB-tcnmZDP2G2aJZKNztr7KpD_iTtaZYf4OtAivoXI"
                                });
                            })
                        // res.json({msg:"success"});
                    }else{
                        return res.json({password:" !"});  
                    //return res.status(400).json({password:" !"});
                    }
                })
            })
        })

좋은 웹페이지 즐겨찾기