link2740 link2741 link2742 link2743 link2744 link2745 link2746 link2747 link2748 link2749 link2750 link2751 link2752 link2753 link2754 link2755 link2756 link2757 link2758 link2759 link2760 link2761 link2762 link2763 link2764 link2765 link2766 link2767 link2768 link2769 link2770 link2771 link2772 link2773 link2774 link2775 link2776 link2777 link2778 link2779 link2780 link2781 link2782 link2783 link2784 link2785 link2786 link2787 link2788 link2789 link2790 link2791 link2792 link2793 link2794 link2795 link2796 link2797 link2798 link2799 link2800 link2801 link2802 link2803 link2804 link2805 link2806 link2807 link2808 link2809 link2810 link2811 link2812 link2813 link2814 link2815 link2816 link2817 link2818 link2819 link2820 link2821 link2822 link2823 link2824 link2825 link2826 link2827 link2828 link2829 link2830 link2831 link2832 link2833 link2834 link2835 link2836 link2837 link2838 link2839 link2840 link2841 link2842 link2843 link2844 link2845 link2846 link2847 link2848 link2849 link2850 link2851 link2852 link2853 link2854 link2855 link2856 link2857 link2858 link2859 link2860 link2861 link2862 link2863 link2864 link2865 link2866 link2867 link2868 link2869 link2870 link2871 link2872 link2873 link2874 link2875 link2876

[Vue.js] Authentication using Jwt and nodejs

when having two issues.

1.when when trying to perform authentication using JWT token and Nodejs when able to log in and log out but when I logged in if I refresh the page the navbar disappears.

when when not logged in in the login page I gave a link to the registration page when I click that it is not redirecting to that page. This is happening when I don’t give the nav bar to authenticate.

This is Login page

<template>
<div class=”container”>
<div class=”row”>
<div class=”col-md-6 mt-5 mx-auto”>
<form v-on:submit.prevent=”login”>
<h1 class=”h3 mb-3 font-weight-normal”>Please sign in</h1>
<div class=”form-group”>
<label for=”email”>Email Address</label>
<input type=”email” v-model=”email” class=”form-control” name=”email” placeholder=”Enter Email” required>
</div>
<div class=”form-group”>
<label for=”password”>Password</label>
<input type=”password” v-model=”password” class=”form-control” name=”email” placeholder=”Enter Password” required>
</div>
<button class=”btn btn-lg btn-danger btn-block” type=”submit”>Login</button>
<a href=”/register”>New User? Register here</a>
</form>
</div>
</div>
</div>
</template>

<script>
import axios from ‘axios’
import router from ‘../router’
import EventBus from ‘./EventBus’
import Navbar from ‘@/components/Navbar’
export default {
components: {Navbar},
data () {
return {
email: ‘’,
password: ‘’
}
},

methods: {
login () {
axios.post(‘http://localhost:5000/users/login',
{
email: this.email,
password: this.password
}).then((res) => {
localStorage.setItem(‘usertoken’, res.data)
this.email = ‘’
this.password = ‘’
if (res) {
this.emitMethod()
router.push({ name: ‘profile’ })
}
}).catch(err => {
console.log(err, alert(‘User doesnot exist’))

})
},
emitMethod () {
EventBus.$emit(‘logged-in’, ‘loggedin’)
}
}
}
</script>

This is the script when using for logout

logout () {
localStorage.removeItem(‘usertoken’)
}

User routes

const express = require(“express”)
const users = express.Router()
const cors = require(“cors”)
const jwt = require(“jsonwebtoken”)
const bcrypt = require(“bcryptjs”)

const User = require(“../model/User”)
users.use(cors())

process.env.SECRET_KEY = ‘secret’

users.post(“/register”, (req, res) => {
const today = new Date()
const userData = {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password,
city: req.body.city,
cycle: req.body.cycle,
created: today
}

User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({ status: user.email + ‘ registered’ })
})
.catch(err => {
res.send(‘error: ‘ + err)
})
})
} else {
res.json({ “error”: ‘User already exists’ })

}
})
.catch(err => {
res.send(‘error: ‘ + err)
})
})

users.post(“/login”, (req, res) => {
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
let token = jwt.sign(user.dataValues, process.env.SECRET_KEY, {
expiresIn: 1440
})
res.send(token)
}
} else {
res.status(400).json({ error: ‘User does not exist’ })
}
})
.catch(err => {
res.status(400).json({ error: err })

})
})

users.get(‘/profile’, (req, res) => {
var decoded = jwt.verify(req.headers[‘authorization’], process.env.SECRET_KEY)

User.findOne({
where: {
userId: decoded.userId
}
})
.then(user => {
if (user) {
res.json(user)
} else {
res.send(‘User does not exist’)
}
})
.catch(err => {
res.send(‘error: ‘ + err)
})
})

users.put(“/:userId”, (req, res) => {
if (!req.body.firstName,
!req.body.lastName,
!req.body.city,
!req.body.cycle,
!req.body.biography) {
res.status(400)
res.json({
error: “Bad Data”
})
} else {
User.update(
{ firstName: req.body.firstName,
lastName: req.body.lastName,
city: req.body.city,
cycle: req.body.cycle,
biography: req.body.biography
},
{ where: { userId: req.params.userId } }
)
.then(() => {
res.send(“Contact updated”)
})
.error(err => res.send(err))
}
})

module.exports = users

Solution :

when not sure if the web app you are building is just for fun or you are planning to use it in production, if so I will suggest you not to use localStorage to save the token. A JWT needs to be stored in a safe place inside the user’s browser.

If you store it inside localStorage, it’s accessible by any script inside the page (which is as bad as it sounds as an XSS attack can let an external attacker get access to the token).

Don’t store it in local storage (or session storage). If any of the 3rd part scripts you include in the page gets compromised, it can access all the users’ tokens.

The JWT needs to be stored inside an HttpOnly cookie, a special kind of cookie that’s only sent in HTTP requests to the server, and it’s never accessible (both for reading or writing) from JavaScript running in the browser.

Source:

https://auth0.com/docs/security/store-tokens
https://logrocket.com/blog/jwt-authentication-best-practices/
https://blog.usejournal.com/sessionless-authentication-withe-jwts-with-node-express-passport-js-69b059e4b22c

Now going back to the original question, I see

import Navbar from ‘@/components/Navbar’

But I don’t you use it in the template, also can you post the vue.js component in which you are having issues with?