我在Laravel 5.1应用程序中创建了一个API部分,在其中我使用JWT身份验证进行无状态登录和验证。该应用程序默认使用laravel提供的身份验证服务和"用户"表。我的 API 需要在"客户端"表上进行身份验证。我已经设法在使用 JWT 时解决了用户表的问题,方法是制作一个将 auth.php 配置文件更改为 model => 'Models'AuthClient'
和 table => 'clients'
的中间件。一切都很好,验证有效,当凭据正确时,它会创建令牌。
中间件:
public function handle($request, Closure $next)
{
'Config::set('auth.model', 'App'Models'AuthClient');
'Config::set('auth.table', 'clients');
return $next($request);
}
ApiAuth控制器登录功能:
public function authenticate(Request $request)
{
$cred = $request->only('email', 'password', 'client_code' );
$validator = $this->validator($cred);
if($validator->fails()) {
return response()->json($validator->errors());
}
$credentials = ['email'=> $cred['email'], 'password'=> $cred['password']];
/*
* If the user enters a "client_code", login the user with that credential
*/
if(issetNotEmpty($cred['client_code'])) {
'App'Models'AuthClient::$defaultAuth = 'client_code';
$credentials = ['client_code' => $cred['client_code'], 'password' => $cred['client_code']];
}
try {
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Datele de autentificare nu sunt corecte.'], 401);
}
} catch (JWTException $e) {
// something went wrong
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
}
我的问题是当我尝试像这样从令牌中检索登录的用户时:
public function getContracts(Request $request)
{
$client = JWTAuth::parseToken()->authenticate();
$contracts = $client->contracts;
dd($client);
return response()->json($contracts);
}
authenticate()
函数从"用户"表而不是"客户端"返回匹配模型,尽管我已经将身份验证.php和 jwt.php 设置为"模型''身份验证客户端"并且 ID 来自"客户端"。
身份验证模型:
class AuthClient extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
protected $table = 'clients';
public static $defaultAuth = 'email';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [ 'email', 'login_password', 'api_token'];
protected $hidden = ['login_password', 'api_token'];
}
我错过了什么?
谢谢!
我已经将中间件放在主路由组(api-amanet)中,我认为这确实起到了作用。在我更改身份验证之前.php在身份验证函数中,所以我猜测 Auth 类已经使用默认 auth.php 设置实例化,并且在我更改设置时没有"刷新"。
/** ********************* API ROUTES ********************** */
Route::group(['prefix' => 'api-amanet', 'middleware' => ['config.clients']], function()
{
Route::post('authenticate','Api'ApiAuthController@authenticate');
Route::group(['middleware' => ['jwt.auth']], function () {
Route::post('password/reset', 'Api'ApiAuthController@resetPassword');
Route::resource('update-profile','Api'ApiAuthController@updateClientProfile');
Route::resource('get-contracts','Api'ResourceController@getContracts');
});
});
希望这对其他人有所帮助。