操作Laravel默认登录身份验证

3

有没有一种方法可以操纵Laravel 5.2的登录认证?我想将其更改为使用“用户名”而不是“电子邮件”,并将返回响应更改为JSON响应。

在Laravel 5.0中,我可以这样做。

在路由中,

//authentication routes
Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

在 AuthController 中,
public function postLogin(Request $request)
{     
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required',
    ]);

    $credentials = ($request->only('username', 'password'));
    if ($this->auth->attempt($credentials)) :   
        return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
    else:
        return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
    endif;

}

请问有什么帮助、想法、线索、建议或推荐吗?

2个回答

1

你只需要更改凭据数组:

$credentials = array(
    'email'                => Input::get('email'),
    'password'             => Input::get('password')
);

在您的情况下:
public function postLogin(Request $request)
{     
    $this->validate($request, [
        'email'    => 'required|email',
        'password' => 'required',
    ]);

    $credentials = ($request->only('email', 'password'));
    if ($this->auth->attempt($credentials)) :   
        return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
    else:
        return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
    endif;

}

希望它有所帮助!

我在哪里可以找到那个凭据数组和那个“public function postLogin”? - Juliver Galleto
什么??我已经复制了你的代码!!你在问什么??我不明白。 - Sangar82

1

Laravel 5.2带有一些与AuthenticatesUsers trait相关的功能(请参阅/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php)。您只需要将以下内容添加到您的AuthController。

// Change the field we grab the username/email from
public function loginUsername()
{
    return 'username';
}

// If the login is successful, send this as the response
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
    return response()->JSON([ 'success' => true, 'message' => 'Successfully logged in, redirecting...' ]);
}

// If the login fails, return this as the response
protected function sendFailedLoginResponse(Request $request)
{
    return response()->JSON([ 'success' => false, 'message' => 'Invalid username or password!' ]);
}

所有的功能都在AuthenticatesUsers.php中概述了。希望这能帮到你!
编辑:如下所述,您需要将请求门面添加到控制器中:
use Illuminate\Http\Request;

在将您的答案添加到authController.php后,我遇到了以下错误:“App\Http\Controllers\Auth\AuthController::sendFailedLoginResponse() 的第1个参数必须是App\Http\Controllers\Auth\Request的实例,但给定的是Illuminate\Http\Request的实例,在C:\wamp\www\Clinic and Inventory System\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php的第85行调用并定义” - Juliver Galleto
嗨,抱歉 - 只需在控制器顶部添加请求类即可使用 Illuminate\Http\Request;如果还有其他错误,请告诉我。 - Daelune

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接