简体   繁体   English

Api-Platform 用户通过 GraphQL 登录

[英]Api-Platform User Login via GraphQL

I am creating an API using API-Platform and have set up my user entity etc using the standard symfony security bundle ( https://symfony.com/doc/current/security.html#retrieving-the-user-object )我正在使用 API 平台创建 API,并使用标准的 symfony 安全包( https://symfony.com/doc/current/security.html#retrieving-the-user-object )设置了我的用户实体等

I have the login working with REST at {url}/api/login using JWT but I cannot see any way of sending my login details with GraphQL我使用 JWT 在{url}/api/login使用 REST {url}/api/login但我看不到任何使用 GraphQL 发送登录详细信息的方式

The API-platform documentation shows how to set up security and how to setup GraphQL separately but doesn't really show how to combine them. API 平台文档展示了如何设置安全性以及如何单独设置 GraphQL,但并未真正展示如何组合它们。

https://api-platform.com/docs/core/graphql https://api-platform.com/docs/core/graphql

https://api-platform.com/docs/core/fosuser-bundle https://api-platform.com/docs/core/fosuser-bundle

How do I make the login accessible in GraphQL?如何在 GraphQL 中访问登录名? Currently, I only have the createUser updateUser and deleteUser mutations, I assume I would need an authenticateUser one?目前,我只有createUser updateUserdeleteUser突变,我想我需要一个authenticateUser吗?

I cannot see any way of sending my login details with GraphQL我看不到任何使用 GraphQL 发送登录详细信息的方式

Auth protected queries should be sent with Authorization header. Auth 受保护的查询应与Authorization标头一起发送。 Exact method depends on client-side technology, fe Apollo client supports this by middleware .确切的方法取决于客户端技术,fe Apollo 客户端通过中间件支持这一点。

You can use existing REST login endpoint (fetch/get token) or create login mutation -example . 您可以使用现有的REST 登录端点(获取/获取令牌)或创建登录突变 -示例

Another inspiration can come from a more complex example apollo-universal-starter-kit另一个灵感可以来自一个更复杂的例子apollo-universal-starter-kit

Yes, you'll need a custom mutation for the login.是的,您需要为登录进行自定义更改

Assuming you are using the API Platform standard docs for the API, you are using JWT to authenticate your calls, you need a UserMutationResolver for auth:假设您使用 API 平台标准文档作为 API,您使用 JWT 对您的调用进行身份验证,您需要一个 UserMutationResolver 进行身份验证:

<?php

namespace App\Resolver;

use ApiPlatform\Core\GraphQl\Resolver\MutationResolverInterface;
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Doctrine\ORM\EntityManagerInterface;

final class UserMutationResolver implements MutationResolverInterface
{
    public function __construct(
        private UserPasswordEncoderInterface $userPasswordEncoder,
        private JWTTokenManagerInterface $JWTManager,
        private EntityManagerInterface $em,
    )
    {}

    /**
     * @param User|null $item
     *
     * @return User
     */
    public function __invoke($item, array $context)
    {
        // Mutation input arguments are in $context['args']['input'].

        if ($context["info"]->fieldName == 'loginUser') {
            $userRepository = $this->em->getRepository("App:User");
            $user = $userRepository->findOneBy(['email' => $item->getEmail()]);
            if ($this->userPasswordEncoder->isPasswordValid($user, $item->getPlainPassword())) {
                $token = $this->JWTManager->create($item);
                $user->setToken($token);
            }
            return $user;
        }
    }
}

Then you add that custom mutation to the User entity.然后将该自定义更改添加到 User 实体。 Be sure to add the names of the auto-generated mutations/queries or they will disappear ( item_query , create , update , delete , collection_query ).请务必添加自动生成的item_query /查询的名称,否则它们将消失( item_querycreateupdatedeletecollection_query )。 You'll also need to disable some of the stages , since this is a mutation Api Platform will try and save this as a new user, which we don't want, so as you see below, 'write' => false and 'validate' => false您还需要禁用某些阶段,因为这是一个突变 Api 平台将尝试将其保存为我们不想要的新用户,因此如下所示, 'write' => false'validate' => false

// api/src/Entity/User.php

// imports etc .
// ...

#[ApiResource(
    normalizationContext: ["groups" => "user:read"],
    denormalizationContext: ["groups" => "user:write"],
    attributes: [
        'write' => true,
    ],
    graphql: [
        'item_query',
        'create',
        'update',
        'delete',
        'collection_query',
        'login' => [
            'mutation' => UserMutationResolver::class,
            'write' => false,
            'validate' => false, 
            'args' => [
                'email' => ['type' => 'String!', 'description'=> 'Email of the user ' ],
                'password' => ['type' => 'String!', 'description'=> 'Password of the user ' ]
            ]
        ],
    ],
    iri:"http://schema.org/Person",
)]
#[UniqueEntity(fields: ["email"])]
class User implements UserInterface
{
// ...

This will create a mutation that you can access like this:这将创建一个您可以像这样访问的突变:

mutation {
  loginUser(input: {email:"test1@test.com", password:"password"})  {
    user {
      token
    }
  }
}

and the result should look something like this:结果应该是这样的:

{
  "data": {
    "loginUser": {
      "user": {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2MTgzNjM1NDQsImV4cCI6MTYxODM2NzE0NCwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoidGVzdDFAdGVzdC5jb20ifQ.pSoAyNcaPa4MH2cxaAM4LJOGvirHfr94GMf_k20eXlF1LAaJyXRraKyC9hmBeKSUeAdIgowlfGFAHt96Z4EruBlkn2mbs3mj3uBWr2zqfNTVyQcicJDkJCO5EpbpexyLO5igD9qZU__4ctPvZcfWY-dJswSfiCTP1Uz0BiGFsGqb72chd8Rhn5Btls-D6b9Uuzl9ZZeLj2pIuBA-yi_CMm3CzopKIJ1NySMT8HyvafHcTdfpzFWFPoUqxkVAzt4U6tqBpEnTqmwRW_3kTisJhIY9xH2uXKghz2VWM6mvTL1PahZgbwLqsVb_sBOOEtiASpGf8WNc1uXtKNhBCb_YJw"
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM