Laravel Cookie返回null

时间:2018-07-14 18:39:59

标签: laravel cookies

我创建了auth api,我使用cookie来标识经过身份验证的用户,但是cookie始终返回null。我已经在Google上搜索了答案,但是问题没有解决

检查我的代码

AuthController.php

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

use App\User;
use App\Token;

class AuthController extends Controller
{
    protected $email;

    protected $token;

    function loginAction(Request $data) {

       $this->email = $data->email;

       $validatorMsg = [
          'email.required' => 'Email tidak boleh kosong',
          'email.email' => 'Masukan email yang valid',
          'email.exists' => 'Email tidak cocok dengan akun manapun',
          'password.required' => 'Password tidak boleh kosong'
       ];

       $validator = Validator::make($data->all(), [
          'email' => 'required|email|exists:users,email',
          'password' => 'required'
       ], $validatorMsg);

       if ($validator->fails()) {
          return response()->json([
              'type' => 'error',
              'message' => $validator->errors()
          ], 422);
       }

       $find = User::where('email', $this->email)->first();

       if (Hash::check($data->password, $find->password)) {

          $this->generateToken();

          return response()->json([
              'type' => 'success',
              'message' => 'Authentication successfully',
              'auth_token' => $this->token
          ], 200);

       } else {

          return response()->json([
              'type' => 'error',
              'message' => [
                'password' => 'Password tidak sesuai dengan akun terkait'
               ]
          ], 401);

       }
    }

    function registerAction(Request $data) {

       $validatorMsg = [
          'name.required' => 'Nama tidak boleh kosong',
          'email.required' => 'Email tidak boleh kosong',
          'email.email' => 'Masukan alamat email yang valid',
          'email.unique' => 'Alamat email sudah terdaftar',
          'password.required' => 'Password tidak boleh kosong',
          'password.min' => 'Password harus lebih dari 6 karakter',              
          'password_confirmation.required' => 'Password belum di konfirmasi',
          'password_confirmation.same' => 'Password tidak sama dengan password konfirmasi'             
       ];

       $validator = Validator::make($data->all(), [
          'name' => 'required',
          'email' => 'required|email|unique:users,email',
          'password' => 'required|min:6',
          'password_confirmation' => 'required|same:password'
       ], $validatorMsg);

       if ($validator->fails()) {
          return response()->json([
               'type' => 'error',
               'message' => $validator->errors(),
          ], 422);
       }

       $this->email = $data->email;


       $user = new User;
       $user->name = $data->name;
       $user->email = $data->email;
       $user->password = Hash::make($data->password);
       $user->save();

       $this->generateToken();

       return response()->json([
           'type' => 'success',
           'message' => 'Register succesfully',
           'auth_token' => $this->token
       ], 200);

    }

    function generateToken() {

       $this->token = str_random(50);

       cookie('auth_token', $this->token, 1440);

       $UID = User::where('email', $this->email)->first()->id;

       $find = Token::where('user_id', $UID)->first();

       if ($find != null) {

          $token = Token::where('user_id', $UID)->first();
          $token->auth_token = $this->token;
          $token->save();

       } else {

          $token = new Token;
          $token->user_id = $UID;
          $token->auth_token = $this->token;
          $token->save();

       }       
    }
}

该控制器显示用户是否成功对其进行身份验证,该控制器会生成cookie

RequireAuth.php(中间件)

<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Cookie;
use Closure;

use App\Token;

class RequireAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      // cookie('auth_token', 'wkwkand', 1440);

       $authToken = Cookie::get('auth_token');

       $find = Token::where('auth_token', $authToken)->first();

       dd($authToken);
       if ($find != null) {
          return redirect('/available');
       }

        return $next($request);
    }
}

用来验证用户是否具有auth_token的中间件,但是我已经设置了cookie。然后我检查dd()cookie的值为空

1 个答案:

答案 0 :(得分:0)

您没有将Cookie传递给响应。

生成Cookie实例

  

除非将此Cookie附加到响应中,否则不会将其发送回客户端   实例

在这里检查:https://laravel.com/docs/5.6/requests#cookies

尝试以下快速修复方法:

function registerAction(Request $data) {

   $validatorMsg = [
      'name.required' => 'Nama tidak boleh kosong',
      'email.required' => 'Email tidak boleh kosong',
      'email.email' => 'Masukan alamat email yang valid',
      'email.unique' => 'Alamat email sudah terdaftar',
      'password.required' => 'Password tidak boleh kosong',
      'password.min' => 'Password harus lebih dari 6 karakter',              
      'password_confirmation.required' => 'Password belum di konfirmasi',
      'password_confirmation.same' => 'Password tidak sama dengan password konfirmasi'             
   ];

   $validator = Validator::make($data->all(), [
      'name' => 'required',
      'email' => 'required|email|unique:users,email',
      'password' => 'required|min:6',
      'password_confirmation' => 'required|same:password'
   ], $validatorMsg);

   if ($validator->fails()) {
      return response()->json([
           'type' => 'error',
           'message' => $validator->errors(),
      ], 422);
   }

   $this->email = $data->email;


   $user = new User;
   $user->name = $data->name;
   $user->email = $data->email;
   $user->password = Hash::make($data->password);
   $user->save();

   $cookie = $this->generateToken();

   return response()->json([
       'type' => 'success',
       'message' => 'Register succesfully',
       'auth_token' => $this->token
   ], 200)->cookie($cookie);

}

function generateToken() {

   $this->token = str_random(50);

   $cookie = cookie('auth_token', $this->token, 1440);

   $UID = User::where('email', $this->email)->first()->id;

   $find = Token::where('user_id', $UID)->first();

   if (!$find) {

      $token = Token::where('user_id', $UID)->first();
      $token->auth_token = $this->token;
      $token->save();

   } else {

      $token = new Token;
      $token->user_id = $UID;
      $token->auth_token = $this->token;
      $token->save();

   }     
   return $cookie;
}