For a project i need a user authentication with GraphQL. Are there plans to build the Craft CMS User authentication and authorization in GraphQL?
Like: https://docs.craftcms.com/v3/dev/examples/login-form.html or https://docs.craftcms.com/v3/dev/examples/user-registration-form.html
No current plans for this, but you could pull it off by pointing your api route (or whatever it鈥檚 called) to a custom controller action instead, which does its own authentication, and then sets the active GraphQL schema before rerouting the request to graphql/api.
use Craft;
use craft\web\Controller;
use yii\web\Response;
class MyGraphqlController extends Controller
{
public $enableCsrfValidation = false;
public $allowAnonymous = ['api'];
public function actionApi(): Response
{
// do custom auth and get the desired schema here
// ...
// set the active schema
Craft::$app->gql->setActiveSchema($schema);
// re-route to graphql/api
return Craft::$app->runAction('graphql/api');
}
}
Note that there have been some breaking changes surrounding GraphQL schemas in Craft 3.4. You鈥檒l probably be best off if you update to that before working on this. You can update by changing your craftcms/cms requirement in composer.json to ^3.4.0-beta.5 and then running composer update. (We will be releasing RC1 next week and the GA release by the end of the month, so it鈥檚 pretty safe to start using 3.4 now.)
Does this work, is there an example anywhere?
Let's say I add JWT verification in the custom auth step can I then expose a different schema depending on success? Can this schema expose different fields/entries and optionally mutations?
Sorry not sure if this is the right place for this - I'm evaluating Craft for the first time and the docs mention defining a schema but there's no example.
@homerjam it works in theory :) I don鈥檛 know of any specific real-world examples, but the above code should serve as a good starting point.
@Jan10 @homerjam quite some time later, but if you're still looking for a solution to this problem I've just released a plugin that (hopefully!) handles all of this for you: https://plugins.craftcms.com/graphql-authentication
Most helpful comment
No current plans for this, but you could pull it off by pointing your
apiroute (or whatever it鈥檚 called) to a custom controller action instead, which does its own authentication, and then sets the active GraphQL schema before rerouting the request tographql/api.Note that there have been some breaking changes surrounding GraphQL schemas in Craft 3.4. You鈥檒l probably be best off if you update to that before working on this. You can update by changing your
craftcms/cmsrequirement in composer.json to^3.4.0-beta.5and then runningcomposer update. (We will be releasing RC1 next week and the GA release by the end of the month, so it鈥檚 pretty safe to start using 3.4 now.)