0

I've created a custom GraphQl API

app\code\Vendor\Extension\etc\schema.graphqls

#Custom Module
type Query
{
    CustomGraphql (
        username: String @doc(description: "Email Address/Mobile Number")
        password: String @doc(description: "Password")
        fieldtype: String @doc(description: "Field Type")
        websiteId: Int = 1 @doc (description: "Website Id")
    ): CustomGraphqlOutput @resolver(class: "Vendor\\Extension\\Model\\Resolver\\CustomGraphql") @doc(description:"Custom Module Datapassing")
}
type CustomGraphqlOutput
{
    username: String
    password: String
    fieldtype: String
}

app\code\Vendor\Extension\Model\Resolver\CustomGraphql.php

<?php
namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;

class CustomGraphql implements ResolverInterface
{
    /**
     * @param Field $field
     * @param \Magento\Framework\GraphQl\Query\Resolver\ContextInterface $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return array|\Magento\Framework\GraphQl\Query\Resolver\Value|mixed
     * @throws GraphQlInputException
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        if (!isset($args['username']) || !isset($args['password']) || !isset($args['fieldtype'])||
            empty($args['username']) || empty($args['password']) || empty($args['fieldtype']))
        {
            throw new GraphQlInputException(__('Invalid parameter list.'));
        }
        $output = [];
        $output['username'] = $args['username'];
        $output['password'] = $args['password'];
        $output['fieldtype'] = $args['fieldtype'];
      
        return $output ;
    }
}

Now if I want to add Customer Authentication in the above API then how to Add? thanks

1 Answer 1

0

To Authenticate the customer we have to only add

/** @var ContextInterface $context */
        if (false === $context->getExtensionAttributes()->getIsCustomer()) {
            throw new GraphQlAuthorizationException(__('The current customer isn\'t authorized.'));
        }

this before any API so it will check that whether Customer is Authorized or not.. n also if we want to get the current customer ID then we can get it like

$customerId = $context->getUserId();

n you will get the customer ID

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.