如果从浏览器调用,Laravel 5 Session在Postman中无法正常工作 [英] Laravel 5 Session working in Postman not working if called from browser

查看:195
本文介绍了如果从浏览器调用,Laravel 5 Session在Postman中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

登录后,我使用会话来设置用户详细信息.如果我使用邮递员,我可以获取会议详细信息.如果我尝试从浏览器登录,则显示为空

这是我的控制人

namespace App\Http\Controllers;
use App\Models\User;
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")));

  }

用于获取会话详细信息的控制器

namespace App\Http\Controllers;
use Session;


class ThisSessionController extends Controller {

  public function getdetails($key)
  {

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

  }

}

config/session.php

        'driver' =>  'file',

编辑1 作为信息点,我使用laravel仅进行api调用.因此,我的域名将是api.mydomain.com/sessiondetails/activeuser

这是问题吗?

编辑2

第一个对象是对会话get url的ajax调用,第二个对象是登录成功后的返回值.

两个令牌完全不同.

编辑-3

我用jwt更新了laravel,它抛出JWT :: Factory不可用.下面是我的更新代码.

namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use JWTAuth;
use Tymon\JWTAuth\JWTManager as JWT;
use Tymon\JWTAuth\Exceptions\JWTException;

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

  }

编辑-4

我更改了登录功能中的代码,并得到了

的结果

{"token":{}}

UserController @登录代码

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

编辑5

我最终可以在laravel中生成令牌的工作代码是

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'));  

  }

解决方案

PHP会话使用cookie来跟踪会话.您访问了mydomain.com页面,浏览器发送了该域的cookie,但是当javascript向api.mydomain.com发出请求时,它不包含cookie,因为它是跨域请求,因此无法跟踪会话. /p>

令牌身份验证是无状态的,这意味着没有会话可保存或从中检索.请求所需的所有信息都必须包含在请求中.因此,您可以从令牌中获取用户信息.

在登录页面上,您发布凭据并返回令牌.然后,您的前端会将令牌附加到每个后续请求.

此示例假设您使用 JWTAuth ,但是该概念适用于任何令牌服务. /p>

  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'));

  }

一旦有了令牌,就可以使用JWT中间件jwt.auth保护任何路由.要从令牌中获取用户信息,请使用JWTAuth::toUser()

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

您应该将这些信息存储在客户端,而不是请求从服务器获取会话数据.

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 App\Http\Controllers;
use App\Models\User;
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 App\Http\Controllers;
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

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 App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use JWTAuth;
use Tymon\JWTAuth\JWTManager as JWT;
use Tymon\JWTAuth\Exceptions\JWTException;

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'));  

  }

解决方案

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.

这篇关于如果从浏览器调用,Laravel 5 Session在Postman中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆