如何使用JSON响应替换默认的auth.basic响应?

时间:2016-02-10 19:22:30

标签: json authentication laravel-5

我有一个看起来像这样的路线组:

Route::group(['prefix' => 'recipe','middleware'=>['auth.basic']], function (){
     //Some things to do
});

当凭据无效时,Laravel输出"凭证无效。"如何使用自己的JSON响应覆盖此响应?

2 个答案:

答案 0 :(得分:0)

在AuthController中,试试这个:

public function postLogin(Request $request)
    {

            $this->validate($request, [
                'email' => 'required', 'password' => 'required',
            ]);

            $credentials = [
            'email' => $request->input('email'),
            'password' => $request->input('password')                         
            ];

            if (Auth::attempt($credentials, $request->has('remember')))
            {
                return redirect()->intended($this->redirectPath())
                ->with('success', 'You are successfully logged in');
            }        

            return Response::json(array(
               'success' => false,
               'errors' => $this->getFailedLoginMessage(),                                 
            ));           

    }

答案 1 :(得分:0)

我刚看了Illuminate\Auth\SessionGuard。方法getBasicResponse()似乎负责对登录尝试失败的响应(使用基本身份验证)。

protected function getBasicResponse()
{
    $headers = ['WWW-Authenticate' => 'Basic'];

    return new Response('Invalid credentials.', 401, $headers);
}

如何实际覆盖它似乎有点棘手。您可能需要扩展SessionGuard类并实现自己的getBasicResponse()方法。这是一个简单的部分,如何实际实例化你自己的后卫,而不是默认的,我还不知道。

相关问题