graphql_如何在GraphQL中钉住社交身份验证

graphql

by Oladipupo Bello

由Oladipupo Bello

如何在GraphQL中钉住社交身份验证 (How to nail social authentication in GraphQL)

In this article you will learn how to perform social authentication in GraphQL server with Passport.JS.

在本文中,您将学习如何使用Passport.JSGraphQL服务器中执行社交身份验证

Perhaps you have an authentication system in place, using directives or resolver wrappers to protect your schema from unauthorized access and are wondering how to add authentication via Google, Facebook or any oauth provider to your API.

也许您已经建立了一个身份验证系统,使用指令或解析程序包装器来保护您的架构免遭未经授权的访问,并且想知道如何通过Google,Facebook或任何oauth提供商向您的API添加身份验证。

Well strap in, because a few lines of code and you’ll have just that.

好吧,因为几行代码就可以了。

I won’t go in-depth on how JWTs work or how to get an access token from a provider. This tutorial will focus on using an access token obtained on the client to get user data from a provider for registration and login.

我不会深入探讨JWT的工作方式或如何从提供商那里获取访问令牌 。 本教程将重点介绍如何使用在客户端上获得的访问令牌从提供程序获取用户数据以进行注册和登录。

I also will not go into how to set up authorization for your schema as a lot of amazing tutorials have been made on the subject.

我也不会讨论如何为您的模式设置授权,因为已经针对该主题进行了许多精彩的教程

内存通道短暂访问— GraphQL之前 (A Short Trip Down Memory Lane — Before GraphQL ⏰)

Authentication in REST is straightforward: stick your middleware on an endpoint and you’re done. In graphQL, however, there is only one endpoint so we need a different approach.

REST中的身份验证很简单:将中间件放在端点上就可以了。 但是,在graphQL中,只有一个端点,因此我们需要一种不同的方法。

要点 (The Gist)

Once you understand how to go about implementing social login, the sky will be the limit as to which framework, language, or database you choose to use in the end. So here goes:

一旦您了解了如何实施社交登录,最终将成为最终选择使用哪种框架,语言或数据库的极限。 因此,这里去:

Step 1: On the front-end, get the 3rd party authentication provider login popup to appear.

步骤1 :在前端,使第三方身份验证提供程序登录弹出窗口出现。

Step 2: (Still on the front-end) Grab the access token the provider returns after agreeing to login.

第2步 :(仍然在前端)获取提供商同意登录后返回的访问令牌。

Step 3: (Yep, still front-end) Send that token to the back-end as part of the input argument of your mutation.

步骤3 :(是的,仍然是前端)作为令牌的输入参数的一部分,将该令牌发送到后端。

Step 4: On the back-end, verify the token.

步骤4 :在后端,验证令牌。

Step 5: If the token is authentic, you will receive the user as part of the verification response (at least that’s the case with Passport.js, which we’ll be using).

步骤5 :如果令牌是真实的,您将在验证响应中收到用户(至少我们将使用Passport.js就是这种情况)。

Step 6: Save the user’s data to your database.

步骤6 :将用户的数据保存到您的数据库中。

Step 7: Return a JWT to the front-end. What you do with that token is out of scope for this tutorial, but it should probably be used to authenticate each of the logged in user’s actions.

步骤7 :将JWT返回前端。 您对该令牌所做的操作超出了本教程的范围,但可能应使用它来对每个登录用户的操作进行身份验证。

There you have it, the skeleton for creating social login with graphQL.

有了它,即使用graphQL创建社交登录的框架。

I’ll leave out steps 1, 2 and 3 as they have already been covered here. In practice it does not matter what frameworks/libraries you are using on the front-end. All that matters is grabbing an access code and running a mutation with it.

我将省略步骤1、2和3,因为这里已经介绍了它们 。 实际上,在前端使用什么框架/库都没有关系。 重要的是获取访问代码并对其进行更改。

Enough chit-chat. Let’s get started.

闲聊。 让我们开始吧。

First you’ll need to fetch authentication IDs and secrets from the various providers.

首先,您需要从各个提供程序获取身份验证ID和机密。

脸书 (Facebook)

Step 1: Go to https://developers.facebook.com/apps/ and select ‘Add a new app.’

第1步 :转到https://developers.facebook.com/apps/,然后选择“添加新应用”。

Step 2: Give your app a name and complete the security question.

步骤2 :为您的应用命名,并完成安全性问题。

Step 3: Select ‘Integrate Facebook Login’ and click confirm.

步骤3 :选择“集成Facebook登录”,然后单击“确认”。

Step 4: Copy down the App Id and App Secret values that are hiding somewhere on the same page.

第4步 :复制隐藏在同一页面某处的App IdApp Secret值。

谷歌 (Google)

Step 1: Go to the developer console: https://console.developers.google.com/ and create a project

步骤1 :转到开发人员控制台: https : //console.developers.google.com/并创建一个项目

Step 2: Look up ‘oauth credentials’ in the search bar, and click the single option that pops up.

第2步 :在搜索栏中查找“ oauth凭据”,然后单击弹出的单个选项。

Step 3: Try to find the ‘Create credentials’ button. If you find it, go ahead and click on it. Choose ‘Oauth Client Id’.

第3步 :尝试找到“创建凭据”按钮。 如果找到它,请继续并单击它。 选择“ Oauth客户端ID”。

For application type, select ‘web application’ .

对于应用程序类型,选择“ Web应用程序”

For Authorized origins add http://localhost:3000. In production, you’ll probably want to be a bit more specific.

对于授权来源,添加http:// localhost:3000。 在生产中,您可能需要更加具体。

Step 4: Click create and copy down the Client Id and Client Secret that are hiding somewhere on the same page.

步骤4 :单击创建,然后复制隐藏在同一页面上某处的客户端ID客户端密钥

API服务器 (The API Server)

Create a folder for your server:

为您的服务器创建一个文件夹:

mkdir graphql-social-auth && cd graphql-social-auth

Initialize the app with

初始化应用

npm init

or if you are using yarn

或者如果您使用纱线

yarn init

Let’s get an API server running. I’ll be using apollo-server here.

让我们运行一个API服务器。 我将在这里使用apollo服务器。

npm install --save apollo-server graphql

or if you are using yarn

或者如果您使用纱线

yarn add apollo-server graphql

Apollo Server will set an Express server up for you as long as you provide it with typeDefs and resolvers.

只要您为Apollo Server提供typeDefsresolvers它就会为您设置Express服务器。

typeDefs stands for Type Definitions which define the “shape” of your data. Resolvers, on the other hand, are responsible for fetching the data for those types.

typeDefs代表类型定义,它们定义数据的“形状”。 另一方面,解析程序负责获取这些类型的数据。

Create a file src/app.js and add the following code:

创建一个文件src / app.js并添加以下代码:

At this point we can start the server by running

此时,我们可以通过运行启动服务器

node src/app.js

After you start the server it should print a message to the console indicating that it’s ready.

启动服务器后,它应该向控制台打印一条消息,表明它已准备就绪。

? Server ready at http://localhost:4000/

Wondering how to change the port or hook up the server to an existing node.js application? Check out the apollo-server documentation for more info.

想知道如何更改端口或将服务器连接到现有的node.js应用程序? 请查看apollo服务器文档以获取更多信息。

To explore the newly created GraphQL API, open a browser to the link shown in the console, http://localhost:4000/. Apollo Server sets up GraphQL Playground for you so that you can start running queries and exploring schema quickly.

要浏览新创建的GraphQL API,请打开浏览器以访问控制台中显示的链接http://localhost:4000/ 。 Apollo Server为您设置了GraphQL Playground,以便您可以开始运行查询并快速浏览架构。

To run a query, copy the following query and then press the “▶️” button:

要运行查询,请复制以下查询,然后按“▶️”按钮:

query {  hello}

And the server should return a simple response:

服务器应该返回一个简单的响应:

{  "data": {    "hello": "world"  }}

Yay! The server works. Now here comes the fun part.

好极了! 服务器正常工作。 现在来了有趣的部分。

  1. We have to setup our graphQL schema and resolvers.

    我们必须设置我们的graphQL模式和解析器。
  2. We have to setup Passport and connect it to our resolvers to validate our tokens from the front end.

    我们必须设置Passport并将其连接到解析器,才能从前端验证我们的令牌。
  3. We will also need to setup Mongo to handle storing our users.

    我们还需要设置Mongo来处理存储我们的用户。

I’ll be using MongoDB because it’s easier to setup, but replacing it with MySQL should be a non-issue.

我将使用MongoDB,因为它更易于设置,但是用MySQL替换它应该不是问题。

First let’s install the necessary dependencies:

首先,让我们安装必要的依赖项:

npm install --save passport passport-facebook-token passport-google-token mongoose jsonwebtoken

or if you are using yarn

或者如果您使用纱线

yarn add passport passport-facebook-token passport-google-token mongoose jsonwebtoken

Next open the src folder and create the following files:

接下来打开src文件夹并创建以下文件:

mongoose.jspassport.jstypeDefs.jsresolvers.js

Add the following to src/mongoose.js:

将以下内容添加到src / mongoose.js中:

This will connect the app to the database and setup the user schema.

这会将应用程序连接到数据库并设置用户架构。

It will also create methods for generating JWTs and finding users from Facebook and Google in our database.

它还将创建用于生成JWT并在我们的数据库中从Facebook和Google查找用户的方法。

Add the following to src/passport.js:

将以下内容添加到src / passport.js中:

Don’t forget to replace the dummy client ids and secret with the ones from Facebook and Google.

不要忘记用Facebook和Google的虚拟客户端ID和密码替换虚拟客户端ID和密码。

With that said and done, all that’s left now is updating the graphQL types and resolvers.

说完这些,现在剩下的就是更新graphQL类型和解析器。

Let’s move the typeDefs and resolvers to separate files to keep our app.js neat and tidy. Add the following to src/typeDefs.js:

让我们将typeDefs和resolver移到单独的文件中,以使app.js保持整洁。 将以下内容添加到src / typeDefs.js中:

Next up src/resolver.js:

下一步src / resolver.js:

Next we refactor our src/app.js to import the schema from the separate files.

接下来,我们重构src / app.js以从单独的文件中导入模式。

Finally we add the request and response objects from express to our graphQL context. This will make them available in our mutation resolvers for use with Passport.JS.

最后,我们将来自express的请求和响应对象添加到我们的graphQL 上下文中 。 这将使它们在我们的突变解析器中可以与Passport.JS一起使用。

And we’re done.

我们完成了。

尝试一下 (Trying it out)

Run the following command in a separate window to get the Mongo daemon running:

在单独的窗口中运行以下命令以使Mongo守护程序运行:

mongod

Now restart the API server:

现在重新启动API服务器:

node src/app.js

To make sure everything is working properly, let’s grab some access tokens and do some test runs.

为了确保一切正常,让我们获取一些访问令牌并进行一些测试运行。

脸书 (Facebook)

Step 1: Open your app settings on https://developers.facebook.com/apps/ and select Roles -> Test Users in the sidebar on the left.

第1步:https://developers.facebook.com/apps/上打开您的应用设置,然后在左侧边栏中选择角色->测试用户。

Step 2: Click on edit and select ‘Change permissions this test user granted to app’

步骤2:点击“修改”,然后选择“更改此测试用户授予应用程序的权限”

Step 3: Add email to the permissions and click update.

步骤3:将电子邮件添加到权限,然后单击更新。

Step 4: Click on edit and select ‘Get an access token for this test user’

步骤4:点击“修改”,然后选择“为此测试用户获取访问令牌”

Step 5: Copy the access token and run the authFacebook mutation with it in the graphQL Playground.

步骤5:复制访问令牌,并在graphQL Playground中运行authFacebook变异。

谷歌 (Google)

As far as I know google doesn’t have a test user equivalent for their APIs. but we can use the Oauth Playground to grab ourselves a valid access token.

据我所知,谷歌没有等效的API测试用户。 但是我们可以使用Oauth Playground来获取有效的访问令牌。

Step 1: Go to https://developers.google.com/oauthplayground, select the ‘Google OAuth2 API v2’ scopes and click ‘Authorize APIs’:

第1步:转到https://developers.google.com/oauthplayground ,选择“ Google OAuth2 API v2”范围,然后单击“授权API”:

You’ll be redirected to the Google consent screen.

您将被重定向到Google同意屏幕。

Step 2: After providing your consent, find the ‘exchange authorization code for tokens button’ on the page and click on it. This will generate a valid refresh and access token for the signed in user.

第2步:征得您的同意后,在页面上找到“令牌交换授权码按钮”,然后单击它。 这将为已登录的用户生成一个有效的刷新访问令牌

Step 3: Copy the generated access token and run the authGoogle mutation with it in the graphQL Playground.

步骤3:复制生成的访问令牌,并在graphQL Playground中运行authGoogle突变。

而已! (That’s it!)

You made it all the way until the end! If you get stuck along the way, feel free to check out the code in this repository. If you have any questions or feedback, let me know in the comments down below.

一路走到最后! 如果您一路陷入困境,请随时查看此存储库中的代码。 如果您有任何疑问或反馈,请在下面的评论中告诉我。

Cheers!

干杯!

Ladi Bello

拉迪·贝洛

翻译自: https://www.freecodecamp.org/news/how-to-nail-social-authentication-in-graphql-27943aee5dce/

graphql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值