3

I have a node.js (express, passport) application with rolling session authentication.

The application is simple enough, just login-password that returns the cookie for the session and a few API functions that are available only with authentication.

I want to use Vue.js as a front-end for that application but I'm unable to find any reliable documentation or a guide on how to implement such authentication in Vue. It seems like there is a heavy focus on JWT. Is it even possible to do in Vue?

I've tried simply using Axios to call the authentication function

<script>
    import router from "../router"    
    import axios from "axios"    
    export default {    
        name: "Login",    
        methods: {    
            login: (e) => {    
                e.preventDefault()    
                let email = "test@test.com"   
                let password = "password"    
                let login = () => {    
                    let data = {    
                        email: email,    
                        password: password    
                    }    
                    axios.post("/srv/login", data)    
                        .then((response) => {
                            router.push("/loginpage")    
                        })    
                        .catch((errors) => {    
                            console.log("Failed to log in")    
                        })    
                }    
                login()    
            }    
        }    
    }
</script>

This works in terms of log in but how do I store the session after I call this API? How do I handle the returned cookie and most importantly make the state of the app itself to the authenticated?

Riza Khan
  • 2,712
  • 4
  • 18
  • 42
Regs
  • 321
  • 1
  • 3
  • 11

1 Answers1

4

You do not have to do anything on the front-end part (Vue) - everything is done by the back-end.

You will do almost the same as what you do for a JWT - but instead of returning the token as part of the body you will put the token in a cookie:

const SECRET_KEY = '123456789'
const expiresIn = '30min'

// Create a token from a payload
function createToken(payload)
{
  return jwt.sign(payload, SECRET_KEY, { expiresIn })
} 

app.post('/login', (req, res, next) =>
{
  const { username, password } = req.body
  const userID = isAuthenticated({ username, password });
  if (userID === 0)
  {
    const status = 401
    const message = 'Incorrect username or password'
    res.status(status).json({ status, message })
    return
  }
  const accessToken = createToken({ id: userID })
  res.cookie('sessionCookieName', accessToken, {httpOnly: true})
  res.status(200).json({ success: true })
}; 

Then each of the other API endpoints will have to validate the token from the cookie:

// Verify the token
function verifyToken(token)
{
  return jwt.verify(token, SECRET_KEY)
}

app.get('/getArticle', (req, res, next) =>
{
  var cookie = req.cookies.sessionCookieName;
  try
  {
    verifyToken(cookie)
    next()
  }
  catch (err)
  {
    const status = 401
    const message = 'Unauthorized'
    res.status(status).json({ status, message })
  } 
});

You may also read these articles:

IVO GELOV
  • 13,496
  • 1
  • 17
  • 26
  • There is no point to create the JWT token. The secret will be in the FE as well, anyone could create a fake token. – Gergo Jan 03 '20 at 12:23
  • FE does not need a secret - it simply returns to the server what the server has already sent as a cookie. Only the server can and needs to verify the JWT. – IVO GELOV Jan 07 '20 at 14:24
  • ah, sorry my bad, I mixed something. – Gergo Jan 07 '20 at 15:08
  • 4
    A session and token (JWT) are two separate concepts: https://developer.okta.com/blog/2017/08/17/why-jwts-suck-as-session-tokens and http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/ – handy Nov 03 '20 at 18:52