doushi1510
2016-01-22 18:13
浏览 46
已采纳

Laravel 5.1身份验证 - 令牌不匹配

I have a fresh install of Laravel 5.1 but am getting a token mismatch error when I try to login a user. I'm not using a form, rather I am using an ajax call that logs in the user after google verification has been satisfied.

My error is: TokenMismatchException in VerifyCsrfToken.php line 53

My controller that is getting hit with the ajax call:

<?php
    namespace App\Http\Controllers;
    use App\Email;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Google_Client; 
    use Auth;
    use App\User;
    class verify extends Controller
    {

    public function verifyIdToken(Request $request)
      {
    $user = User::where('name', 'Molly')->first();
        Auth::login($user);
        if (Auth::check($user))
{
    return response()->json(['Logged In' => "Yes!"]);
}
    }
      }

I don't get a response, just a 500 internal server error with the above error. I do see a laravel session cookie being returned however, so I am very confused as to what is going on. What is this token and why is it throwing an error?

For more information, my routes.php file is:

    if (Auth::guest()) {
    Route::get('/', function () {
        return view('welcome');
    });
} else {
    Route::get('/', ['middleware' => 'auth', function () {
        return view('mainview');
    }]);
}

Edit: Basically I want the controller hit in the ajax call to verify the user was logged in, without any internal server error so that on a refresh, they are rerouted to the mainview not the welcome page.

图片转代码服务由CSDN问答提供 功能建议

我全新安装了Laravel 5.1但是当我尝试登录用户时出现令牌不匹配错误。 我没有使用表单,而是在使用google验证后登录用户的ajax调用。

我的错误是:VerifyCrfToken.php中的 TokenMismatchException 第53行

我的控制器被ajax调用命中:

 &lt;?php 
 namespace App  \ Http \ Controllers; 
使用App \ Email; 
使用App \ Http \ Controllers \ Controller; 
使用Illuminate \ Http \ Request; 
使用Google_Client;  
使用Auth; 
使用App \ User; 
类验证扩展Controller 
 {
 
公共函数verifyIdToken(请求$请求)
 {
 $ user = User :: where('name',  'Molly') - &gt; first(); 
 Auth :: login($ user); 
 if(Auth :: check($ user))
 {
返回响应() - &gt; json([  '登录'=&gt;“是!”]); 
} 
} 
} 
   
 
 

我没有得到回复,只是一个 上述错误导致500内部服务器错误。 我确实看到了返回的laravel会话cookie,所以我对发生的事情感到非常困惑。 这个令牌是什么?它为什么会抛出错误?

有关更多信息,我的 routes.php 文件是: < pre> if(Auth :: guest()){ Route :: get('/',function(){ return view('welcome'); }); } else { Route :: get('/',['middleware'=&gt;'auth',function(){ 返回视图('mainview'); }]); }

编辑:基本上我希望在ajax调用中命中控制器来验证用户是否已登录,没有任何内部服务器错误,因此在刷新时,它们被重新路由到 mainview 而不是 welcome 页面。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtan6543 2016-01-22 18:42
    已采纳

    Try the following method, From Docs.

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题