swagger 我无法创建JWT端点

dpiehjr4  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(162)

我想添加一个端点到SwaggerUI来检索一个JWT标记。我做了API平台文档中所说的一切。
我创建了一个JwtDecorator.php文件:

<?php
// api/src/OpenApi/JwtDecorator.php

namespace App\OpenApi;

use ApiPlatform\OpenApi\Factory\OpenApiFactoryInterface;
use ApiPlatform\OpenApi\OpenApi;
use ApiPlatform\OpenApi\Model;

final class JwtDecorator implements OpenApiFactoryInterface
{
    public function __construct(
        private OpenApiFactoryInterface $decorated
    ) {}

    public function __invoke(array $context = []): OpenApi
    {
        $openApi = ($this->decorated)($context);
        $schemas = $openApi->getComponents()->getSchemas();

        $schemas['Token'] = new \ArrayObject([
            'type' => 'object',
            'properties' => [
                'token' => [
                    'type' => 'string',
                    'readOnly' => true,
                ],
            ],
        ]);
        $schemas['Credentials'] = new \ArrayObject([
            'type' => 'object',
            'properties' => [
                'email' => [
                    'type' => 'string',
                    'example' => 'johndoe@example.com',
                ],
                'password' => [
                    'type' => 'string',
                    'example' => 'apassword',
                ],
            ],
        ]);

        $schemas = $openApi->getComponents()->getSecuritySchemes() ?? [];
        $schemas['JWT'] = new \ArrayObject([
            'type' => 'http',
            'scheme' => 'bearer',
            'bearerFormat' => 'JWT',
        ]);

        $pathItem = new Model\PathItem(
            ref: 'JWT Token',
            post: new Model\Operation(
                operationId: 'postCredentialsItem',
                tags: ['Token'],
                responses: [
                    '200' => [
                        'description' => 'Get JWT token',
                        'content' => [
                            'application/json' => [
                                'schema' => [
                                    '$ref' => '#/components/schemas/Token',
                                ],
                            ],
                        ],
                    ],
                ],
                summary: 'Get JWT token to login.',
                requestBody: new Model\RequestBody(
                    description: 'Generate new JWT Token',
                    content: new \ArrayObject([
                        'application/json' => [
                            'schema' => [
                                '$ref' => '#/components/schemas/Credentials',
                            ],
                        ],
                    ]),
                ),
                security: [],
            ),
        );
        $openApi->getPaths()->addPath('/authentication_token', $pathItem);

        return $openApi;
    }
}

我的保镖.yaml

security:
  # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
  password_hashers:
    Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
    App\Entity\User: 'auto'
  enable_authenticator_manager: true
  # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
  providers:
    # used to reload user from session & other features (e.g. switch_user)
    app_user_provider:
      entity:
        class: App\Entity\User
        property: email
  firewalls:
    login:
      pattern: ^/api/login
      stateless: true
      json_login:
        check_path: /api/login_check # or api_login_check as defined in config/routes.yaml
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    api:
      pattern: ^/api/
      stateless: true
      provider: app_user_provider
      jwt: ~
    main:
      stateless: true
      lazy: true
      provider: app_user_provider
      json_login:
        check_path: /authentication_token
        username_path: email
        password_path: password
        success_handler: lexik_jwt_authentication.handler.authentication_success
        failure_handler: lexik_jwt_authentication.handler.authentication_failure
      jwt: ~

  access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }
    - { path: /api/docs, roles: PUBLIC_ACCESS } # Allows accessing the Swagger UI
    - { path: ^/authentication_token, roles: PUBLIC_ACCESS }
    # - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

when@test:
  security:
    password_hashers:
      Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
        algorithm: auto
        cost: 4 
        time_cost: 3 
        memory_cost: 10

我的服务.yaml


# This file is the entry point to configure your own services.

# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed

# https://symfony.com/doc/current/best_practices.html#use-parameters-for-application-configuration

parameters:

services:
  App\OpenApi\JwtDecorator:
        decorates: 'api_platform.openapi.factory'
        arguments: ['@.inner']
  App\State\UserProcessor:
    tags: ['api_platform.state_processor']
    bind:
      $decorated: '@api_platform.doctrine.orm.state.persist_processor'
    arguments:
      $passwordHasher: '@Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface'
  ApiPlatform\State\ProcessorInterface: ~

  _defaults:
    autowire: true # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

  App\:
    resource: '../src/'
    exclude:
      - '../src/DependencyInjection/'
      - '../src/Entity/'
      - '../src/Kernel.php'

但在我的swagger界面中看不到“/authentication_token”端点
堆栈:Symfony:6.1 PHP:可扩展性平台8.1:3.0

aij0ehis

aij0ehis1#

缺少两个配置文件:
config/api_platform.yaml

api_platform:
  swagger:
    api_keys:
      JWT:
        name: Authorization
        type: header

config/routes.yaml

authenticate:
    path: /authentication_token
    methods: ['POST']

相关问题