Single page application with HttpOnly cookie-based authentication and session management

I got this working on Vue.js 2 with credentials = true. Setting credentials from client site only half of the story. You need to set response headers from the server as well:

    header("Access-Control-Allow-Origin: http://localhost:8080");
    header("Access-Control-Allow-Credentials: true");

You can’t use wildcard for Access-Control-Allow-Origin like this:

header("Access-Control-Allow-Origin: *");

When you specify the credentials: true header, you are required to specify the orgin.

As you can see, this is a PHP code, you can model it to NodeJS or any server side scripting language you are using.

In VueJS I set credentials = true like this in the main.js:

Vue.http.options.credentials = true

In the component, I successfully logged in using ajax:

<template>
<div id="userprofile">
    <h2>User profile</h2>
    {{init()}}

</div>
</template>

<script>
    export default {  
        name: 'UserProfile',
        methods: {
        init: function() {


                // loggin in
              console.log('Attempting to login');

            this.$http.get('https://localhost/api/login.php')
            .then(resource =>  {
             // logging response - Notice I don't send any user or password for testing purposes  

            });

            // check the user profile

                console.log('Getting user profile');

                this.$http.get('https://localhost/api/userprofile.php')
                .then(resource =>  {
                    console.log(resource.data);
                })

        }
    }
    }

</script>

On the server side, things are pretty simple:
Login.php on sets a cookie without making any validation whatsoever (Note: this is done for testing purposes only. You are not advised to use this code in production without validation)

<?php

header("Access-Control-Allow-Origin: http://localhost:8080");
header("Access-Control-Allow-Credentials: true");

$cookie = setcookie('user', 'student', time()+3600, "https://stackoverflow.com/", 'localhost', false , true);

if($cookie){
  echo "Logged in";
}else{
  echo "Can't set a cookie";
}

Finally, the userprofile.php just verifies if a cookie = user is set

<?php

  header("Access-Control-Allow-Origin: http://localhost:8080");
    header("Access-Control-Allow-Credentials: true");


if(isset($_COOKIE['user'])){
  echo "Congratulations the user is ". $_COOKIE['user'];

}else{
  echo "Not allowed to access";
}

Successfully logged in

Successfully logged in

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)