我已经使用 guard 创建了代码并验证了用户身份,但它没有为我提供 api_token
/**
* This'll provide login authentication to the user
* @param Request $request
* @return json
*/
public function authenticate(Request $request)
{
//getting and setting locale for the request
$locale = ($request->header('lang-code') == 'KO') ? "ko" : "en";
app()->setLocale($locale);
$credentials = $request->only('email','password');
try {
// verify the credentials and create a token for the user
if (!$token = auth()->attempt($credentials)) {
return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.failure')],401);
}
} catch (GeneralException $e) {
// something went wrong
return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.tokenNC')],500);
}
return response()->json(['success' => parent::SUCCESS, 'message' => trans('messages.api.login.success'), 'data' => auth()->user()],200);
}
上述功能工作正常,但当我使用 auth()->guard('api')->user()->api_token
时,我没有获得 token 。此列已在我的数据库中,即使我无法生成 api_token
这可能是这里的问题。
已编辑
routes/api.php:
Route::group(['namespace' => "Api\\v1", 'as' => 'api.v1.', 'prefix' => 'v1'], function () {
Route::any('/login', 'AccessController@authenticate');
});
config/auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
最佳答案
您可能需要确保任何将使用 token 身份验证的路由都受到 auth:api
中间件的保护。
像这个例子:
Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
Route::post('/authentificate', 'AuthController@authentificate');
});
关于php - 如何生成api_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40930362/