使用Cookie来存储令牌

我正在构建一个需要授权用户登录的应用程序,我读到localstorage不是一个安全的选择,所以我现在选择cookie来存储令牌,我相信我已成功将令牌存储在cookie中,但我不知道下一步,在客户端如何使用它们是我的代码

这是后端: 路线:

var express = require('express')
var router = express.Router()
var Controller = require('./controller')
var authController = require('./authController')
var BooksIdeaController = require('./BooksIdeaController')
router.post('/register',Controller.register);
router.post('/login',authController.login);
router.post('/booksIdea/:id',authController.verify,BooksIdeaController.addComment)
router.post('/booksIdea/addbook',BooksIdeaController.addBookIdea)
router.get('/booksIdea/show',BooksIdeaController.showBookIdea)
router.put('/booksIdea/edit/:id',BooksIdeaController.UpdateBookIdea)
router.delete('/booksIdea/delete/:id',BooksIdeaController.DeleteBookIdea)
module.exports = router;

authController.js文件

 const con = require('./db');
    var bcrypt = require('bcrypt');
    let jwt = require('jsonwebtoken');
    const express = require('express')
    var cookieParser = require('cookie-parser')
    const app = express()
    module.exports.login=function(req,res){
        var username=req.body.name;
        var password=req.body.password;
        con.query('SELECT * FROM users WHERE username = ?',[username],function (error,results,fields) {
          if (error) {
              res.json({
                status:false,message:'there are some error with query'
                })
          }else{
            if(results.length >0){
              bcrypt.compare(password,results[0].password,function (err,result) {
                if (result == true) {
            jwt.sign({user:results},'configSecret',(err,token)=>{
              // res.json({
              //   token:token
              // })
              res.cookie('token',token,{ httpOnly: true })
                .sendStatus(200);
              res.send('About this wiki');
            });



                //   res.json({
                //     status:true,//     message:'successfully authenticated'
                // })
                } else {
                  res.json({
                          status:false,message:"username and password does not match"
                         });
                }
              });
            }
            else{
              res.json({
                  status:false,message:"username does not exits"
              });
            }
          }
        });
    }

    module.exports.home=function(req,res){
    res.send('hello');
    }
    //////
    // if(password==results[0].password){

      // }else{
      //    
      // }
      module.exports.verify = function verifyToken(req,res,next) {
        // Get auth header value
        const bearerHeader = req.headers['authorization'];
        // Check if bearer is undefined
        if(typeof bearerHeader !== 'undefined') {
          // Split at the space
          const bearer = bearerHeader.split(' ');
          // Get token from array
          const bearerToken = bearer[1];
          // Set the token
          req.token = bearerToken;
          // Next middleware
          next();
        } else {
          // Forbidden
          res.sendStatus(403);
        }

      }

这是反应部分

import axios from 'axios'
export const login = user => {
  return axios
    .post('http://localhost:5001/login',{
      name: user.name,password: user.password
    })
    .then(response => {
      return response.data

    })
    .catch(err => {
      console.log(err)
    })
}
everaining 回答:使用Cookie来存储令牌

反应端:

HOC可以检查您的身份验证或不向服务器调用/ api / auth请求

/**
 * auth.js : it handles user is authenticated or not
 * 
 */
 
import React,{ Component } from 'react';
import { auth } from '../../actions'
import { connect } from 'react-redux';

export default function(ComposedClass,reload){
    class AuthenticationCheck extends Component{
    
        state = {
            loading : true
        }

        componentWillMount () {
            this.props.dispatch(auth())
        }

        componentWillReceiveProps (nextProps) {
            this.setState({
                loading : false
            })

            if(!nextProps.admin.login.isAuth){
                if(reload){
                    this.props.history.push('/login')
                }
            }
        } 
    
        render(){
            if(this.state.loading){
                return <div className="loader"> Loading... </div>
            }
            return(
               <ComposedClass {...this.props} users={this.props.users} />
            )
        }
    }

    function mapStateToProps(state){
        console.log(state)
        return{
            admin: state.users
        }
    }
    return connect(mapStateToProps)(AuthenticationCheck)
}

将所有路由传递给该HOC组件,如

import React from 'react';
import  { Switch,Route  } from 'react-router-dom';
import Home from './components/Home/home';
import Users from './components/UsersView/users';
import User from  './components/UserView/user';
import FourOFour from  './components/FourOFour/fourofour';
import AddUser from './containers/Admin/add';
import EditUser from './containers/Admin/edit';
import UserContainer from './containers/User/user_container.js';
import Login from './containers/Login/login';
import Signup from './containers/Signup/signup';
import Auth from './hoc/Auth/auth';
import Logout from './components/Logout/logout';


import Layout from './hoc/Layout/layout';


const Routes = () => {
    return (
        <Layout>
            <Switch> 
                <Route path="/signup" exact  component={ Auth(Signup,false) } />
                <Route path="/logout" exact  component={ Auth(Logout,true) } />
                <Route path="/login" exact  component={ Auth(Login,false) } />
                <Route path="/users/add" exact  component={ Auth(AddUser,false) } /> 
                <Route path="/users/:id/edit" exact  component={ Auth(EditUser,true) } />          
                <Route path="/users/:id" exact component={ Auth(UserContainer,true) } />
                <Route path="/users" exact component={ Auth(Users,false) } />
                <Route path="/" exact  component={ Auth(Home,null) } />
                <Route component={FourOFour}/>     
            </Switch>
        </Layout>
       
    );
};

export default Routes;

节点侧:

 /**
 * auth : Middleware which chack your tocken is valide or not
 */
    const  { Admin } = require('../models/admin');
    
    let auth = (req,res,next) =>{
        let token = req.cookies.auth;
        
        Admin.findByToken(token,(err,admin)=>{

            if (!admin) return res.json({
                error : true
            })
            
            req.token = token;
            req.admin = admin;

            next();
        })
        
    }

    
    module.exports = { auth }
    

您可以在要检查身份验证的路由中使用auth。

//admin auth : 
app.get("/api/auth",auth,(req,res) => { 
    console.log(auth)
    res.json({
        isAuth : true,id : req.admin._id,email : req.admin.email,})
})

有关更多信息,请访问我的Mern App Project

我希望这会对您有所帮助,并且可以做正确的举动,以便其他人从这个问题中受益。如果您有任何问题,请告诉我。

本文链接:https://www.f2er.com/3166444.html

大家都在问