Я совершенно новый в рамках laravel / lumen. Я использую Lumen 5.2 для создания успокоительного API. Для аутентификации я пытаюсь реализовать аутентификацию JWT. https://laravelista.com/json-web-token-authentication-for-lumen статья для руководства. Я устанавливаю и настраиваю это https://github.com/tymondesigns/jwt-auth
пакеты. Он работает нормально и выдает мне следующую ошибку, если я не предоставляю токен {«error»: «token_not_provided»}. Но когда я пытаюсь сгенерировать токен, передавая электронную почту и пароль в запросе на публикацию, происходит сбой и выдается следующая ошибка ,
in AuthManager.php line 137
at Application->Laravel\Lumen\Concerns\{closure}('8', 'Undefined index: provider', 'D:\xamp\htdocs\lumen_api\vendor\illuminate\auth\AuthManager.php', '137', array('name' => 'api', 'config' => array('driver' => 'token'))) in AuthManager.php line 137
at AuthManager->createTokenDriver('api', array('driver' => 'token')) in AuthManager.php line 77
at AuthManager->resolve('api') in AuthManager.php line 57
at AuthManager->guard() in AuthManager.php line 244
at AuthManager->__call('once', array(array('email' => '[email protected]', 'password' => 'password'))) in IlluminateAuthAdapter.php line 39
at AuthManager->once(array('email' => '[email protected]', 'password' => 'password')) in IlluminateAuthAdapter.php line 39
at IlluminateAuthAdapter->byCredentials(array('email' => '[email protected]', 'password' => 'password')) in JWTAuth.php line 108
at JWTAuth->attempt(array('email' => '[email protected]', 'password' => 'password')) in Facade.php line 216
at Facade::__callStatic('attempt', array(array('email' => '[email protected]', 'password' => 'password'))) in AuthController.php line 45
at JWTAuth::attempt(array('email' => '[email protected]', 'password' => 'password')) in AuthController.php line 45
at AuthController->postLogin(object(Request))
at call_user_func_array(array(object(AuthController), 'postLogin'), array(object(Request))) in Container.php line 507
at Container->call(array(object(AuthController), 'postLogin'), array()) in RoutesRequests.php line 581
at Application->callControllerCallable(array(object(AuthController), 'postLogin'), array()) in RoutesRequests.php line 548
at Application->callLumenController(object(AuthController), 'postLogin', array(true, array('uses' => 'App\Http\Controllers\AuthController@postLogin'), array())) in RoutesRequests.php line 521
at Application->callControllerAction(array(true, array('uses' => 'App\Http\Controllers\AuthController@postLogin'), array())) in RoutesRequests.php line 489
at Application->callActionOnArrayBasedRoute(array(true, array('uses' => 'App\Http\Controllers\AuthController@postLogin'), array())) in RoutesRequests.php line 474
at Application->handleFoundRoute(array(true, array('uses' => 'App\Http\Controllers\AuthController@postLogin'), array())) in RoutesRequests.php line 376
at Application->Laravel\Lumen\Concerns\{closure}() in RoutesRequests.php line 624
at Application->sendThroughPipeline(array(), object(Closure)) in RoutesRequests.php line 382
at Application->dispatch(object(Request)) in RoutesRequests.php line 327
at Application->run(object(Request)) in index.php line 29
Вот мой код Authcontroller:
namespace App\Http\Controllers;
use Illuminate\Http\Exception\HttpResponseException;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use Illuminate\Http\Response as IlluminateResponse;
class AuthController extends Controller{/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
try
{
$this->validate($request, [
'email' => 'required|email|max:255', 'password' => 'required',
]);
}
catch (HttpResponseException $e)
{
return response()->json([
'error' => [
'message' => 'Invalid auth',
'status_code' => IlluminateResponse::HTTP_BAD_REQUEST
]],
IlluminateResponse::HTTP_BAD_REQUEST,
$headers = []
);
}
$credentials = $this->getCredentials($request);
try
{
// attempt to verify the credentials and create a token for the user
//$customClaims = ['email' => '[email protected]', 'password' => 'password'];
if ( ! $token = JWTAuth::attempt($credentials))
{
return response()->json(['error' => 'invalid_credentials'], 401);
}
}
catch (JWTException $e)
{
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
/**
* Get the needed authorization credentials from the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function getCredentials(Request $request)
{
return $request->only('email', 'password');
}
}
===================================
мой файл .env
APP_ENV=local
APP_DEBUG=true
APP_KEY=swe09w8w7r6t5y4uio321!@wsceszwer
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=api_db
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=memcached
QUEUE_DRIVER=sync
JWT_SECRET=cv4d4se065r1td0sw6e8d9za9q102jhes060a3wer
AUTH_DRIVER=jwt
AUTH_MODEL=\App\Models\User
AUTH_TABLE=users
Я много гуглю, но пока не могу найти решения. Пожалуйста, помогите мне разобраться.
заранее спасибо.
Вот структура каталогов папки продавца
Вы можете написать свой собственный auth
файл конфигурации в config/auth.php
(если он не существует, вы можете создать на себя). Посмотреть конфигурацию Вот.
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'api'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"|
| NOTE: "token" driver is not supported in JWT Auth
|
*/
'guards' => [
'api' => [
'driver' => 'session',
'provider' => 'users'
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
// We should get model name from JWT configuration
'model' => app('config')->get('jwt.user'),
],
],
];
К счастью, я создаю простую аутентификацию JWT, реализованную в Lumen Вот.
Других решений пока нет …