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

namespace AppHttpControllers;
use AppModelsUser;
use Session;

class UserController extends Controller {

  public function login(){
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    $requestArray = array();
    foreach($request as $key => $value){
      $requestArray[$key] = $value;
    }
    $user = User::login($requestArray);
    Session::put("activeuser", $user);
    Session::save();
    return json_encode(array('result'=>Session::get("activeuser")));

  }

Controller to fetch session details

namespace AppHttpControllers;
use Session;


class ThisSessionController extends Controller {

  public function getdetails($key)
  {

        return json_encode(array($key => Session::get($key)));

  }

}

config/session.php

        'driver' =>  'file',

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.

namespace AppHttpControllers;
use AppModelsUser;
use IlluminateHttpRequest;
use AppHttpRequests;
use JWTAuth;
use TymonJWTAuthJWTManager as JWT;
use TymonJWTAuthExceptionsJWTException;

class UserController extends Controller {

  public function login(Request $request){

   $credentials = $request->only('username', 'password');
   $user = User::login($requestArray);
   if($user){

     $payload = JWTFactory::make($credentials);
     $token = JWTAuth::encode($payload);
   }


    return json_encode(array('result'=>$token));

  }

Edit – 4

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

{"token":{}}

UserController@login code

$customClaims = ['foo' => 'bar', 'baz' => 'bob']; 
$payload = app('tymon.jwt.payload.factory')->make($customClaims);
$token = JWTAuth::encode($payload);

EDIT 5

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

public function login(Request $request){
    $credentials = $request->only('username', 'password');

   try {
        $user = User::login($credentials);
        if(!$user)
          throw new Exception("Error Processing Request", 1);

   } catch (Exception $e) {
       return response()->json(['error' => false]);
   }

   $token = JWTAuth::fromUser($user);

   return response()->json(compact('token'));  

  }

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.

  public function login(Request $request){

    // This is all unnecessary. You're in Laravel, take advantage of the services Laravel provides. Use [Request](https://laravel.com/docs/5.1/requests#retrieving-input) instead.
    //$postdata = file_get_contents("php://input");
    //$request = json_decode($postdata);
    //$requestArray = array();
    //foreach($request as $key => $value){
    //  $requestArray[$key] = $value;
    //}

    // change email to username depending on what you use to authenticate
    $credentials = $request->only('username', 'password');
    $user = User::login($requestArray);
    if($user){
        $token = JWTAuth::fromUser(User::where('username', $credentials['username'])->first());
    } else {
        return response()->json(array('error' => 'invalid credentials')))

    // all good so return the token
    return response()->json(compact('token'));

  }

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()

public function getCurrentUser()
{
    return JWTAuth::toUser()->toJson();
}

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