Я хочу создать REST API с ПЛАТФОРМА API и Symfony 4.2. Я просто пытаюсь сделать аутентификацию пользователя, но каждый раз это не удается.
Я дам вам каждый шаг, чтобы вы могли видеть, где / почему я терплю неудачу:
Создайте проект Symfony и потребуйте все необходимое:
composer create-project symfony/skeleton stackoverflow
cd ./stackoverflow
composer req api server maker
Затем я создаю пользователя, и он автоматически создает поставщика безопасности и т. д.:
php bin/console make:user
Затем я следую инструкциям по установке LexikJWTAАутентификацияBundle:
composer req "lexik/jwt-authentication-bundle"
/**
* config/bundles.php
*/
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Nelmio\CorsBundle\NelmioCorsBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
ApiPlatform\Core\Bridge\Symfony\Bundle\ApiPlatformBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true],
Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle::class => ['all' => true],
];
mkdir -p config/jwt
openssl genrsa -out config/jwt/private.pem -aes256 4096 // pw: stackoverflow
openssl rsa -pubout -in config/jwt/private.pem -out config/jwt/public.pem // pw : stackoverflow
/**
* config/packages/lexik_jwt_authentication.yaml
*/
lexik_jwt_authentication:
secret_key: '%env(resolve:JWT_SECRET_KEY)%'
public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_ttl: 3600
/**
* config/packages/security.yaml
*/
security:
encoders:
App\Entity\User:
algorithm: argon2i
providers:
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
json_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
access_control:
- { path: ^/admin/users, roles: ROLE_SUPER_ADMIN }
- { path: ^/admin, roles: ROLE_ADMIN }
Запускаю сервер:
php bin/console server:run
И пробую тест из документации:
curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"johndoe","password":"test"}'
If it works, you will receive something like this:
{ "token" : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjE0MzQ3Mjc1MzYsInVzZXJuYW1lIjoia29ybGVvbiIsImlhdCI6IjE0MzQ2NDExMzYifQ.nh0L_wuJy6ZKIQWh6OrW5hdLkviTs1_bau2GqYdDCB0Yqy_RplkFghsuqMpsFls8zKEErdX5TYCOR7muX0aQvQxGQ4mpBkvMDhJ4-pE4ct2obeMTr_s4X8nC00rBYPofrOONUOR4utbzvbd4d2xT_tj4TdR_0tsr91Y7VskCRFnoXAnNT-qQb7ci7HIBTbutb9zVStOFejrb4aLbr7Fl4byeIEYgp2Gd7gY" }
Я должен добавить localhost: 8000, конечно, и я получаю очень большую ошибку, это похоже на источник сценария js на 1000 строк.
Поэтому я пропускаю и пытаюсь добавить кнопку авторизации в swagger:
/**
* config/packages/api_platform.yaml
*/
api_platform:
mapping:
paths: ['%kernel.project_dir%/src/Entity']
swagger:
api_keys:
apiKey:
name: Authorization
type: header
И когда я перехожу на localhost:8000, я вижу:
code 401
message "JWT Token not found"
Я также пробую весь этот ответ: https://github.com/lexik/LexikJWTAuthenticationBundle/issues/451#issuecomment-443216804
Я нашел это, если это может помочь: var\cache\dev\ContainerT2hNySI\getSecurity_Authentication_Listener_Json_LoginService.php
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the private 'security.authentication.listener.json.login' shared service.
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Firewall/ListenerInterface.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Firewall/UsernamePasswordJsonAuthenticationListener.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Authentication/AuthenticationSuccessHandlerInterface.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Authentication/CustomAuthenticationSuccessHandler.php';
include_once $this->targetDirs[3].'/vendor/lexik/jwt-authentication-bundle/Security/Http/Authentication/AuthenticationSuccessHandler.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Authentication/AuthenticationFailureHandlerInterface.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Authentication/CustomAuthenticationFailureHandler.php';
include_once $this->targetDirs[3].'/vendor/lexik/jwt-authentication-bundle/Security/Http/Authentication/AuthenticationFailureHandler.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Session/SessionAuthenticationStrategyInterface.php';
include_once $this->targetDirs[3].'/vendor/symfony/security-http/Session/SessionAuthenticationStrategy.php';
$a = ($this->services['event_dispatcher'] ?? $this->getEventDispatcherService());
$this->privates['security.authentication.listener.json.login'] = $instance = new \Symfony\Component\Security\Http\Firewall\UsernamePasswordJsonAuthenticationListener(($this->services['security.token_storage'] ?? ($this->services['security.token_storage'] = new \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage())), ($this->privates['security.authentication.manager'] ?? $this->getSecurity_Authentication_ManagerService()), ($this->privates['security.http_utils'] ?? $this->load('getSecurity_HttpUtilsService.php')), 'login', new \Symfony\Component\Security\Http\Authentication\CustomAuthenticationSuccessHandler(new \Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationSuccessHandler(($this->services['lexik_jwt_authentication.jwt_manager'] ?? $this->load('getLexikJwtAuthentication_JwtManagerService.php')), $a), array(), 'login'), new \Symfony\Component\Security\Http\Authentication\CustomAuthenticationFailureHandler(new \Lexik\Bundle\JWTAuthenticationBundle\Security\Http\Authentication\AuthenticationFailureHandler($a), array()), array('check_path' => '/api/login_check', 'use_forward' => false, 'require_previous_session' => false, 'username_path' => 'username', 'password_path' => 'password'), ($this->privates['logger'] ?? ($this->privates['logger'] = new \Symfony\Component\HttpKernel\Log\Logger())), $a, ($this->privates['property_accessor'] ?? $this->getPropertyAccessorService()));
$instance->setSessionAuthenticationStrategy(new \Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy('none'));
return $instance;
Мой локальный хост: 8000/api заголовки:
Cache-Control: no-cache, private Connection: close Content-Type: application/json Date: Thu, 24 Jan 2019 21:51:51 +0100, Thu, 24 Jan 2019 20:51:51 GMT Host: localhost:8000 Link: http://localhost:8000/api/docs.jsonld; rel = "http://www.w3.org/ns/hydra/core#apiDocumentation" WWW-Authenticate: Bearer X-Powered-By: PHP/7.2.14-1+ubuntu18.04.1+deb.sury.org+1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8 Accept-Encoding: gzip, deflate Accept-Language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3 Cache-Control: max-age=0 Connection: keep-alive DNT: 1 Host: localhost:8000 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Проблема может заключаться в том, что я не могу выполнить 2-ю / 3-ю ЧАСТИ. Получить токен и использовать токен, я не знаю, имеет ли это значение. (думаю, это название ошибки "токен не найден") так что все для этого FFS).
Ошибка, которую я получаю, когда пытаюсь получить токен, похожа на исходный код JS-скрипта на 1000 строк, я не могу сказать больше (я думаю, что вставка не разрешена так долго).
Нужна помощь, спасибо.
также проверьте эту проблему Github: github.com/lexik/LexikJWTAuthenticationBundle/issues/346
Добавьте это - SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 на вашем виртуальном хосте внутри <VirtualHost *:443> , а не внутри <Directory> . проверьте этот ответ: github.com/lexik/LexikJWTAuthenticationBundle/issues/…
В файле readme ветки Chapter7-api мой учебник я задокументировал все шаги, которые я прошел, чтобы добавить аутентификацию JWT. Полученный код находится в ветке главы8-api, возможно, это поможет, если вы найдете какую-то разницу с тем, что вы сделали.





у вас есть пользователи с паролями в вашей базе данных?