Asked By: user7312892
I tried to make an authentication system. Everything goes ok but it is a small problem, the user is disconnected every time he refreshes the page. I think I have somehow saved the token and the user in a session but I do not know how.
Full project is here: Github
// Token setup
function jwtSignUser(user) {
const ONE_WEEK = 60 * 60 * 24 * 7;
return jwt.sign(user, process.env.JWT_SECRET, {
expiresIn: ONE_WEEK
});
}
How I send the data
// Successfuly logged in
if (response) {
return res.send({
user: existingUser.toJSON(),
token: jwtSignUser(existingUser.toJSON())
});
}
Solution:
I solved this problem, you can find final project here
Github
I changed method of saving token to localStorage
Solution
Answered By: Anonymous
the problem seems to be that you are storing the token in memory, and not localStorage
https://github.com/gnome1337/coworking-lab/blob/Authentification/client/src/store/store.js#L15
state.token = token
the store is not actually stored if you do a refresh, however the localStarage would be. There is a good writeup here: https://auth0.com/blog/build-an-app-with-vuejs/ that will help you achieve this. Read the article, or tl;dr; below…
// src/auth/index.js
import {router} from '../index'
// URL and endpoint constants
const API_URL = 'http://localhost:3001/'
const LOGIN_URL = API_URL + 'sessions/create/'
const SIGNUP_URL = API_URL + 'users/'
export default {
// User object will let us check authentication status
user: {
authenticated: false
},
// Send a request to the login URL and save the returned JWT
login(context, creds, redirect) {
context.$http.post(LOGIN_URL, creds, (data) => {
localStorage.setItem('id_token', data.id_token)
localStorage.setItem('access_token', data.access_token)
this.user.authenticated = true
// Redirect to a specified route
if(redirect) {
router.go(redirect)
}
}).error((err) => {
context.error = err
})
},
signup(context, creds, redirect) {
context.$http.post(SIGNUP_URL, creds, (data) => {
localStorage.setItem('id_token', data.id_token)
localStorage.setItem('access_token', data.access_token)
this.user.authenticated = true
if(redirect) {
router.go(redirect)
}
}).error((err) => {
context.error = err
})
},
// To log out, we just need to remove the token
logout() {
localStorage.removeItem('id_token')
localStorage.removeItem('access_token')
this.user.authenticated = false
},
checkAuth() {
var jwt = localStorage.getItem('id_token')
if(jwt) {
this.user.authenticated = true
}
else {
this.user.authenticated = false
}
},
// The object to be passed as a header for authenticated requests
getAuthHeader() {
return {
'Authorization': 'Bearer ' + localStorage.getItem('access_token')
}
}
}