https://github.com/tymondesigns/jwt-auth非常适合为defualt guard验证用户,但我想从另一个表(auth:guard)登录用户
这是config / auth.php:
'defaults' => [
'guard' => 'user',
'passwords' => 'users',
],
'guards' => [
'user' => [
'driver' => 'jwt',
'provider' => 'users',
],
'student' => [
'driver' => 'jwt',
'provider' => 'students',
],
'father' => [
'driver' => 'jwt',
'provider' => 'fathers',
],
'mother' => [
'driver' => 'jwt',
'provider' => 'mothers',
],
],
正如我所提到的,jwt身份验证适用于'guard'=> 'user',因为它是默认的,但我想使用'guard'=>来验证学生“学生”没有改变默认警卫。
这是我的登录功能:
public function login(Request $request){
$credentials = $request->only('email', 'password');
$jwt = '';
try {
if (!$jwt = JWTAuth::attempt($credentials)) {
return response()->json([
'response' => 'error',
'message' => 'invalid_credentials',
], 401);
}
} catch (JWTAuthException $e) {
return response()->json([
'response' => 'error',
'message' => 'failed_to_create_token',
], 500);
}
return response()->json([
'message' => 'success',
'result' => ['token' => $jwt]
]);
}
为了更好地理解,我已按照文档中显示的所有步骤安装tymon / jwt-auth版本dev-develop。 任何帮助都非常感谢
答案 0 :(得分:1)
无需更改config/auth.php
中的提供程序。
您可以如下更改每个控制器中的__construct
功能。这样jwt知道要验证哪种模型。
父亲控制器
function __construct()
{
Config::set('jwt.user', Father::class);
Config::set('auth.providers', ['users' => [
'driver' => 'eloquent',
'model' => Father::class,
]]);
}
StudentController
function __construct()
{
Config::set('jwt.user', Student::class);
Config::set('auth.providers', ['users' => [
'driver' => 'eloquent',
'model' => Student::class,
]]);
}
答案 1 :(得分:0)
尝试这样的事情
public function login(Request $request)
{
//validate the user credentials
$this->validate($request,[
'email'=>'required | email',
'password'=>'required',
]);
//attempt to log in the admin
if(Auth::guard('student')->attempt(['email'=>$request->email,
'password'=>$request->password],$request->remember)){
//if successful, then redirect to their intended location
return redirect()->intended(route('dashboard'));
}
// if unsuccessful, then redirect them back to the login form with form data
return redirect()->back()->withInput($request->only('email','remember'));
}