Skip to content
Advertisement

Laravel 5 Session working in Postman not working if called from browser

After login I use session to set the user details. If i use postman i can get the session details. If i try logging from my browser its showing null

Here is my controller

JavaScript

Controller to fetch session details

JavaScript

config/session.php

JavaScript

Edit 1 As a point of information, i use laravel to make only api calls. So my domain will be api.mydomain.com/sessiondetails/activeuser

Is this the problem?

Edit 2

enter image description here

The first object is the ajax call to the session get url and second object is the return value after login success.

Two tokens were totally different.

Edit – 3

I have updated laravel with jwt and it is throwing JWT::Factory is not available. below is my updated code.

JavaScript

Edit – 4

I changed the code inside login function and i get result as

JavaScript

UserController@login code

JavaScript

EDIT 5

My final working code that could generate the token in laravel is

JavaScript

Advertisement

Answer

PHP Sessions use a cookie to keep track of the session. You visit the page mydomain.com and the browser sends cookies for that domain, but when the javascript makes requests to api.mydomain.com it doesn’t include cookies because it’s a cross domain request so the session can’t be tracked.

Token authentication is stateless meaning there is no session to save to or retrieve from. All the information needed for the request must be included in the request. So you get the user information from the token.

On your login page you post the credentials and return a token. Your frontend will then attach the token to every subsequent request.

This example assumes you use JWTAuth, but the concept would work with any token service.

JavaScript

Once you have a token you can use the JWT middleware jwt.auth to protect any route. To get the user info from the token use JWTAuth::toUser()

JavaScript

Instead of making requests to get session data from the server, you should store that information on the client side.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement