node.js 인터페이스 구축(6): Node - jwt를 사용하여 token 구현
3174 단어 node.js
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:" !"});
}
})
})
})
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Express + AWS S3 이미지 업로드하기웹 사이트 및 모바일 애플리케이션 등에서 원하는 양의 데이터를 저장하고 보호할 수 있다. 데이터에 대한 액세스를 최적화, 구조화 및 구성할 수 있는 관리 기능을 제공한다. AWS S3 에 저장된 객체에 대한 컨테이너...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.