Stay logged with php session & angular

Published

I’m trying to make a login system on angular with a PhP backend.

When people login, this is the PhP script called :

// here check for good request
$account = // found the account thanks to PDO
$accountId = $account["id"];
session_start();
$_SESSION["accountId"] = $accountId;
setcookie("accountId", $accountId);

Then, when I want to get informations according to user, I call this script :

require 'include/bdd.php';

session_start();

if(!isset($_SESSION["accountId"]) && !isset($_COOKIE["accountId"])) {
    echo "You are not logged";
    die();
}
$accountId = isset($_SESSION["accountId"]) ? $_SESSION["accountId"] : $_COOKIE["accountId"];

// here get data
echo json_encode($myData);

When I’m doing this in my browser, it works.

But when I’m doing it with angular, the $_SESSION and $_COOKIE are empty.

My code in angular :

this.http.get<T>("http://my-url.com/script.php").toPromise().then((result) => console.log(result));

My question:

How should I use PhP/Angular request to make secure login and data-request according to logged account? Should I change of language (to Java/C#/…)* (it’s not a problem for me)?

What I tried ?

  • Use { withCredentials: true } on get method on angular:
this.http.get<T>("http://my-url.com/script.php", { withCredentials: true }).toPromise().then((result) => console.log(result));

But I get this error :

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request''s credentials mode is 'include'.
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

But I don’t understand how that’s possible to don’t use "*" such as it’s run from client-side, so from everywhere… I stay blocked one day about just fix CORS issue. This is not a valid option for me.

  • I begin with only $_SESSION, and that was working too. I tried to add with cookie, to be sure.
  • I think to put the accountId in the request, each time. But it’s clearly not secure, and not a very good idea…

Finally, I see lot of topic which have very lite answer, which don’t enable to fix my issue.

Source: Angular Questions

Answers

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq