node/express認証の例、password暗号化 / CSRF対応 / Redis 認証情報 #node #express #javascript

■ 概要:

前のnode/express 関連で、
ユーザー認証等の例となります。


■ 環境

node
express
Redis

■ 参考のコード

■ npm 追加

・暗号化

npm install bcrypt -save

・CSRF対応

npm install csrf --save

npm install express-session --save


■ 実装など

・app.js
前のCSRF対応と同様、express-session 設定しておきます。

・Login処理、Login画面起動
routes/index.js

/******************************** 
* 
*********************************/
router.get('/login', function(req, res) {
   LibCsrf.set_token(req, res) 
   res.render('login', { user : "" });
});
/******************************** 
* 
*********************************/
router.post('/login', function(req, res){
   try{
       if(LibCsrf.valid_token(req, res)== false){
           console.log("error, csrf token");
           res.redirect('/login')
       }
       var data = req.body
//        console.log(data )  
       let hashed_password = bcrypt.hashSync("1111", 10);
       if (data.email === "hoge@example.com" && bcrypt.compareSync(data.password,  hashed_password )) 
       {
//            console.log(hashed_password);    
           var user = {
               mail: data.email, password: hashed_password
           }
           var json = JSON.stringify( user );
           res.cookie('user', json );
           res.redirect('/')
       }else{
           console.log("error, login");
           res.clearCookie('user');
           res.redirect('/login')
       }        
   } catch (e) {
       console.log(e);
   }
});

LibCsrf.valid_token: CSRF トークン検証
bcrypt.hashSync, hash暗号化作成
bcrypt.compareSync ,暗号化文字と 入力passwordの検証
認証成功した場合、cookieにUser情報を保存し。TOPページ等にリダイレクトします。

■ Redis , User情報で。認証する

・参考のGit

■ 実装など

・redis 認証ログイン
routes/login.js

router.post('/',async function(req, res){
   try{
       client.on("error", function(error){ console.error(error); }); 
       if(LibCsrf.valid_token(req, res)== false){
           console.log("error, csrf token");
           res.redirect('/login')
       }
       var data = req.body
       var valid_user = await LibAuth.validRedisUserAuth(res ,client, data.email, data.password )
console.log( valid_user )  
       if (valid_user){
//            console.log(hashed_password);    
           res.redirect('/')
       }else{
           console.log("error, login");
           res.clearCookie('user');
           res.redirect('/login')
       }        
   } catch (e) {
       console.log(e);
   }

});

・LibAuth.validRedisUserAuth で、reids Userの mail, password を検証する例です

■ 関連する, アクション

ログイン: /login
ログアウト: logout
ユーザー追加: /users/add

■ 関連のページ

・node/expressで、 CSRF対応の例
https://note.com/knaka0209/n/n78ac5dc9db16




この記事が気に入ったらサポートをしてみませんか?