0

I wrote a SPA using a javascript framework (vuejs) at app.example.com, it's an additional tool for the main site that uses PHP, example.com.

Both app.example.com, and example.com share the same server and database (It uses SSL too), so user who register once will be able to be authenticated across all subdomains and main domain.

First problem, which is inter-connected to the second: the app.example.com sends the user email/password to our server for request authentication, if authenticated the server sets a session $_SESSION['appUserId] = 10, and the request returns the user information where I set a localStorage key with it's token. localStorage.setItem("appUserId", 10);

The problem is that, I'm not sure how to keep the user authenticated via app.example.com and example.com since right now, I'd have to check if the user is authenticated with every page request and app.example.com uses localStorage.

I know I can share the cookie between subdomain and domain but I'm not sure if that's the best way possible. For example, I could replace the localStorage for a cookie, but cookies can be modified via the browser.

I'm still learning about general security.

Craig
  • 474
  • 7
  • 20
  • You can use a cookie, but the cookie name should be a unique id generated by a random generator such as `uniq()` in PHP, and all the important stuff in a local storage. (Or server storage) Even if the hacker is modifying the cookie, he would need to know the other unique id's generated by your code. – Forbs Apr 18 '18 at 19:10
  • LocalStorage can be modified as well. It's still stored in the client. I think you should look into [JSON Web Tokens](https://jwt.io/). Those are stored on the client, but are signed so any modification would invalidate them. – Magnus Eriksson Apr 18 '18 at 19:35

1 Answers1

0

If you use session with PHP, it already takes care of keeping your user data between each request.

  1. User request home page example.com/home
  2. User authenticate example.com/login
  3. PHP set session cookie and store data in session
  4. User request next page example.com/nextpage, here the browser will send back the session cookie and PHP can load the stored data from the session

From PHP point of view the user is a known user and you can access his data. Now the tricky part of yours is by default PHP will create a cookie for the domain it was requested from. So if it got a request from app.example.com, if you then visit example.com that cookie won't be sent to PHP and PHP will not know about the user.

You want PHP to always create its cookie with the domain ".example.com". That would fix the issue of being authenticated (on PHP side) from one domain and not the other one.

Also I would avoid using browser storage for authenticating a user. Browser storage is not available in some browser in incognito.

zzarbi
  • 1,723
  • 2
  • 14
  • 27