user11825367
user11825367

Reputation:

How to set the token to local storage or cookies so that i can allow user to access certain web pages

I am trying to build an authentication system so, i used node , mysql,express for that so now i am simply saving and checking user exist in database can access but now i added JWT to it, so now i want this JWT token to store in localstorage or in cookies so, can someone guide me how can i do so

this is my authentication controller.js

var Cryptr = require('cryptr');
cryptr = new Cryptr('myTotalySecretKey');
var express = require('express');
const ap = express();
var jwt = require('jsonwebtoken');
var connection = require('./../config');

module.exports.authenticate = function (req, res) {
    var email = req.body.email;
    var password = req.body.password;


    connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields) {
        if (error) {
            res.json({
                status: false,
                message: 'there are some error with query'
            });
        } else {

            if (results.length > 0) {
                decryptedString = cryptr.decrypt(results[0].password);
                if (password == decryptedString) {
                    jwt.sign({ email, password },
                        'secretkey',
                        { expiresIn: '10days' },
                        (err, token) => {
                            console.log('token:' + token);
                            module.exports = token;
                            console.log(token);
                            res.redirect('/home.html');
                        }
                    );

                } else {
                    res.redirect('/login.html');
                    console.log("Wrong Input");

                }

            }
            else {
                res.redirect('/login.html');
            }
        }
    });
};

now i want to pass the token value to the local-storage or cookies so that i can restrict someone from acessing a page, i am reallly new to node js so any help would be appriciated

Upvotes: 4

Views: 2095

Answers (3)

Mat.Now
Mat.Now

Reputation: 1725

I show you one solution using jwt token, you choose another way:

  1. Back-end file e.g. api.js

    let jwt             = require('jsonwebtoken') 
    let secret          = 'yourSecret'; //secret key necessary to encode token
    let Cryptr = require('cryptr');
    let cryptr = new Cryptr('myTotalySecretKey');
    
    module.exports = function(router,upload) {
    
     function tokenAuth(req, res, next){
       let token = req.body.token || req.body.query || req.headers['x-access-token']
       if(token){
         jwt.verify(token, secret, function(err,decoded){
            if(err){
                res.json({ authenticated: false, message:'Invalid token'})
            } else {
                req.decoded = decoded;
                next()
            }
        })
      } else {
        res.json({success:false, message:'No token provided'});
      }
    }
    router.post('/authenticate', function(req, res){
      connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields){
      if(error) {
        res.json({ success:false, message: err })
      }
      if(!results.length){
       res.json({success:false, message:'User no found'})
      } else if (results.length>0){ 
       if(!req.body.password){
         res.json({success:false, message:'Password was not provided'});                    
       } else {  
         var validPassword = cryptr.decrypt(results[0].password);
         if(validPassword === req.body.password){                  
           res.json({success:false, message:'Incorrect password'})
         }  else {
          var token = jwt.sign({username: results[0].username, email: results[0].email}, secret, {expiresIn: '24h'})
          res.json({success:true, message:'You have logged in correctly!', token: token })
         }
        }
       }
      })
     })
     //If you want create a route for authenticated users for example comment posts, you can use our `tokenAuth function`
     router.post('/post/comment',tokenAuth,function(req,res){
       //access only for authenticated users
     }
    return router
    } 
    

    This tokenAuth function we'll be use in paths restricted to authenticated users

  2. server file e.g. server.js

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 80;
    const http = require('http').Server(app);
    const routes = require(path_to_api.js)(router);
    
    app.use('/myApi', routes)
    //***Here you should implement more details about your project such as routes, body parsers and other middlewares*****//
    //Connect to your database
    http.listen(port, ()=> console.log(`Server running on ${port}`))
    
  3. Front-end file e.g. controller.js

    function(login){
       return fetch('/myApi/authenticate',{
             method: 'POST',
             headers: {
                'Content-Type': 'application/json',
             },
             body: JSON.stringify(login)
          }).then(result=>result.json()).then(data=> window.localStorage.setItem('token', data.token))
    } 
    
    //`login` argument should be an object and should be like {username: 'user username', password: 'user password'}
    

Upvotes: 1

amirhaa
amirhaa

Reputation: 280

First I should notify you that do not put any secret things like password in jwt payload because the values of the payload could be accessed easily, you can try to copy paste a jwt in jwt.io site and see the payload.

set jwt in cookie like below, this will use express cookie method that does set Http Set-Cookie header:

res.cookie('jwt', generated_cookie)
   .redirect('/home.html');

Also if you want to use localStorage you can set jwt in header and then in your code get the jwt from the header of login request and save it in localStorage and after that you should pass it as header in all other request, but this approach is a better solution for api calls like when you use react or vue ...

res.set({x-token: generated_token});

// In your code get 
// get token from response
localStorage.setItem('token', token);
// now whenever calling api pass token as header

Upvotes: 1

virchau13
virchau13

Reputation: 1448

In order to make a user store cookies, you can use the Set-Cookie header. From MDN:

Set-Cookie: <cookie-name>=<cookie-value>

In order to pass a header using Express, you can use res.set(), e.g. res.set("Set-Cookie", "Token=" + token). I also suggest you use the HttpOnly cookie directive, since it seems from your post that you don't access this token directly via Javascript and you simply want to check it when the client requests a webpage: res.set("Set-Cookie", "Token=" + token + "; HttpOnly").

The client will send the Cookie header to you when it requests a resource. You can check this header using req.header('Cookie'), and the output will be "Token=<token>" if the user is authenticated. You can then check this token for authenticity.

Upvotes: 0

Related Questions