0

I am trying to make a simple login PHP API and calling it from Axios via VueJS.

On login attempt I send axios POST request to desired script on the same domain like so:

            axios.post("/api/open/auth/login", {
                data: {
                    username: this.name,
                    password: this.pass
                }
            })

Then in PHP I check inserted data from POST and if it's correct, I set session variables like so (there is session_start() at the beggining of the file):

        $_SESSION["userID"] = $row->id_users;
        $_SESSION["username"] = $row->name;

this works fine so far and I am certain that this part of code runs alright and session variables should be set, but I created another script, that is supposed to check, wheter the user is logged in by checking those session variables like so:

if ( isset($_SESSION["userID"]) && isset($_SESSION["username"]) )
{
    jsonResponseOk("Session is set.");
}
else
{
    jsonResponseError("Session is not set.");
}

Here is what I can't wrap my head around, although the session variables should be set, when I logged in before, this always falls to ELSE.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Because you are accessing an API there is no concept "session". – Jay Blanchard Feb 05 '20 at 15:10
  • PHP returns a session cookie to the user. You'd need to store that cookie and include it in subsequent requests. (For an API this design may not be ideal, statelessness is important.) – David Feb 05 '20 at 15:11
  • @JayBlanchard That doesn't seem correct to me, according to [this thread](https://stackoverflow.com/questions/676846/do-ajax-requests-retain-php-session-info) it seems like ajax requests on the same domain contain the session ID cookie automaticaly, therefore PHP should be able to read session data based on this ID set before, isn't it? – Patrik Šticha Feb 06 '20 at 08:06
  • 1
    @PatrikŠticha: *"contain the session ID cookie automaticaly"* - Read that question again carefully though and note how it's different from your scenario. Specifically statements like "I had a user logged onto my site" and "he clicked a 'Save' button". In that scenario the user is *manually* interacting with the login functionality. The browser is receiving the cookie in the response, saving it, and including it in subsequent requests. That's not what you're doing. You're making an AJAX request for the initial login. You need to handle the resulting cookie from the response. – David Feb 06 '20 at 11:59

1 Answers1

0

Web APIs not uses sessions you need to use JWT for verification of users. Web APIs are verifed sending bearer token and after verification you can store user id into cookies or localstorage. Check JWT here

Thank You

Priyanshu
  • 39
  • 1
  • 6