prisma 风格设置_Prisma中的身份验证-第1部分:设置

news/2024/7/3 1:37:05

prisma 风格设置

Unless if you’re using something like Firebase to handle your authentication, it can be a bit tricky to handle it in a way that is both secure and easy to manage. In this three-part series, we’re going to be going over how to setup your GraphQL API for handling authorization, generating tokens, and securing your Prisma data from the outside world and against unauthorized users.

除非您使用Firebase之类的方法来处理身份验证,否则以既安全又易于管理的方式处理身份验证会有些棘手。 在这个由三部分组成的系列文章中,我们将讨论如何设置GraphQL API,以处理授权,生成令牌以及保护Prisma数据不受外界和未经授权的用户侵害。

先决条件 (Prerequisites)

You’re going to need to have a basic Prisma container setup and connected to some database, in this case, I’ll be using the Postgres setup.

您将需要基本的Prisma容器设置并连接到某些数据库,在这种情况下,我将使用Postgres设置。

If you don’t want to worry about the Prisma setup, you can copy this repo to get started. Just remember to move into the prisma folder and start a new Docker container.

如果您不想担心Prisma的设置,可以复制此存储库以开始使用。 只要记住要移入prisma文件夹并启动一个新的Docker容器即可。

$ npm install
$ docker-compose up -d -e ../.env
$ prisma deploy

建立 (Setup)

After you have the starter boilerplate cloned, your folder structure should look something like the following. You’ll need to add a new env file with your database credentials, and another which should be in the root of the project since we’ll be storing some secrets that Node.js will need as well.

克隆了入门模板之后,文件夹结构应如下所示。 您将需要使用数据库凭据添加一个新的env文件,另一个文件应位于项目的根目录中,因为我们将存储Node.js也需要的一些机密信息。

* prisma 📂
  * .env  -For database credentials
  * datamodel.graphql
  * docker-compose.yml
  * generated.graphql
  * prisma.yml
* src 📂
  * index.js
  * prisma.js
  * resolvers.js 
* .babelrc
* .env  -For Secrets
* .graphqlconfig
* package.json
* schema.graphql

Since we’re going to follow best practices and use env files for our important/secret information, we’re going to need the env-cmd package to get node to look at it before running anything.

由于我们将遵循最佳实践,并使用env文件获取重要/秘密信息,因此,在运行任何操作之前,我们需要env-cmd程序包让节点查看它。

$ npm install env-cmd --save

关闭服务器 (Closing Off the Server)

Currently, if we were to deploy our API as is, anyone would be able to read and write to our production database through Prisma. The first thing that we need to do it block any operations that don’t come with a valid authentication token, which we’ll add later.

当前,如果我们按原样部署API,则任何人都可以通过Prisma读写生产数据库。 我们需要做的第一件事是阻止任何没有有效身份验证令牌的操作,我们将在以后添加。

The first step is to add a secret that any user will be forced to provide to interact with the API, which is best for us to add as an environment variable.

第一步是添加一个秘密,任何用户将被迫提供与API交互的秘密,这对于我们最好添加为环境变量。

prisma.yml
棱镜
endpoint: http://192.168.99.100:4466 # or http://localhost:4466 
datamodel: datamodel.graphql
secret: ${env:API_SECRET}

For now it doesn’t matter what it is, I’ll just be using a string but you can use a token generator if you want.

现在,它无关紧要,我只使用一个字符串,但是如果需要,您可以使用令牌生成器 。

.env
.env
API_SECRET=SuperSecretSecret

When we redeploy we need to tell Prisma to look at our env file first by using the -e flag directing it to the correct file. It already uses the one in the same directory by default, we have to be explicit about files anywhere else.

重新部署时,我们需要通过使用-e标志将其定向到正确的文件,首先告诉Prisma查看我们的env文件。 默认情况下,它已经在同一目录中使用了该目录,我们必须明确说明其他位置的文件。

$ prisma deploy -e ../.env

Now that we have successfully broken our app, an attempt to use our Node.js connection should fail. A query should return a response like "Your token is invalid. It might have expired or you might be using a token from a different project.". To give it access, we first need to pass our secret to our Prisma instance.

既然我们已经成功破坏了我们的应用程序,则尝试使用我们的Node.js连接应该会失败。 查询应返回"Your token is invalid. It might have expired or you might be using a token from a different project."类的响应"Your token is invalid. It might have expired or you might be using a token from a different project." 。 要授予它访问权限,我们首先需要将我们的秘密传递给我们的Prisma实例。

prisma.js
pyramida.js
const prisma = new Prisma({
  typeDefs: 'src/generated.graphql',
  endpoint: 'http://192.168.99.100:4466/',
  secret: process.env.API_SECRET
})

And finally, just tell our start script to look at .env before running nodemon.

最后,只需告诉我们的启动脚本在运行nodemon之前先查看.env 即可 。

package.json
package.json
"scripts": {
  "get-schema": "graphql get-schema -p prisma",
  "start": "env-cmd .env nodemon src/index.js --ext js,graphql --exec babel-node"
},

For me, env-cmd versions 9+ kept throwing the error ‘This file does not have an app associated with it …“. As of this writing, this is still an open issue some users are getting, if this happens to you I recommend trying version 8.0.2 instead.

对我来说,env-cmd版本9+一直抛出错误“此文件没有与之关联的应用程序……”。 在撰写本文时,这仍然是一些用户遇到的未解决问题,如果您遇到这种情况,我建议改用8.0.2版。

The final step is to tell our get-schema command to look at our prisma.yml instead of the endpoint, since that would require the secret. We can do this by making a small addition to .graphqlconfig to look at prisma.yml instead.

最后一步是告诉我们的get-schema命令查看而不是终结prisma.yml而不是终结点,因为这将需要密码。 我们可以通过对.graphqlconfig进行少量添加来.graphqlconfig来查看prisma.yml

.graphqlconfig
.graphqlconfig
{
  "projects": {
    "prisma": {
      "schemaPath": "src/generated.graphql",
      "extensions": {
        "prisma": "prisma/prisma.yml",
        "endpoints": {
          "default": "http://192.168.99.100:4466/"
        }
      }
    }
  }
}

Now that Node has access, all of your interactions with Prisma should be done exclusively over there. If you need to play with the GraphQL Playground or the server itself you can generate a token to pass in the header.

现在,Node可以访问了,您与Prisma的所有交互都应该在那儿专门进行。 如果您需要使用GraphQL Playground或服务器本身,则可以生成令牌以传递标头。

Run this and copy the token it outputs.

运行此命令并复制其输出的令牌。

$ prisma token

Now in the bottom left of the GraphQL playground you should be able to open an HTTP HEADERS panel that accepts JSON. It just needs the property "Authorization" with the value "Bearer YOUR-COPIED-TOKEN".

现在,在GraphQL游乐场的左下方,您应该能够打开一个接受JSON的HTTP HEADERS面板。 它只需要值为"Bearer YOUR-COPIED-TOKEN"的属性"Authorization" "Bearer YOUR-COPIED-TOKEN"

密码 (Passwords)

Now we can get more into the fun stuff. Obviously our users are going to need an email and password to login with, so let’s add them now in both the datamodel and schema.

现在,我们可以将更多的乐趣带入其中。 显然,我们的用户需要登录时使用的电子邮件和密码,因此现在将它们添加到datamodelschema

datamodel.graphql
数据模型
type User {
  id: ID! @id 
  name: String! 
  email: String! @unique 
  password: String!
}

And don’t forget to deploy and regenerate the schema!

并且不要忘记部署和重新生成架构!

schema.graphql
schema.graphql
type User {
  id: ID! 
  name: String! 
  email: String! 
  password: String!
}

测验 (Testing)

Let’s add a query for all users, if all went well you should be able to create a user on the Prisma API and see it on your Node server.

让我们为所有用户添加一个查询,如果一切顺利,您应该能够在Prisma API上创建一个用户,并在您的Node服务器上看到它。

schema.graphql
schema.graphql
type Query {
  users: [User!]!
}
resolvers.js
resolvers.js
const Query = {
  users(parent, args, { prisma }, info) {
    const users = prisma.query.users(null, info);

    return users;
  }
};


总结思想 (Closing Thoughts)

Continue to Part 2 to learn about creating tokens for our users whenever they login or create an account.

继续阅读第2部分,以了解有关在用户登录或创建帐户时为他们创建令牌的信息。

翻译自: https://www.digitalocean.com/community/tutorials/graphql-authentication-setup

prisma 风格设置


http://www.niftyadmin.cn/n/3649288.html

相关文章

RxBus-mvp模式下对Rxjav的封装(一)

一、首先定义一个Presenter接口:DataBusSubscriber 用来接受数据 public interface DataBusSubscriber {void onEvent(Object data); }二、定义一个RxBus的封装类 public class RxBus {public static final String TAG "RxBus";private static volatile…

VS 2005 Team Suite 轻松搞定白盒测试

注:此文的Word版本首次发表于: http://bbs.5etesting.com/viewthread.php?tid18&highlight%B0%D7%BA%D0%B2%E2%CA%D4 VS 2005 Team Suite轻松搞定白盒测试 (此文已于《测试天地》杂志发表,如需转载,请与作者联系…

[推荐]dotNET中进程间同步/通信的经典框架

推荐一篇关于dotNET中常用的进程间同步或通信的框架文章:A C# Framework for Interprocess Synchronization and CommunicationBy Christoph Ruegg How to share resources and implement a rich message/data passing architecture between threads and processes …

Android 开发之RxJava 详解

我从去年开始使用 RxJava ,到现在一年多了。今年加入了 Flipboard 后,看到 Flipboard 的 Android 项目也在使用 RxJava ,并且使用的场景越来越多 。而最近这几个月,我也发现国内越来越多的人开始提及 RxJava 。有人说『RxJava 真是…

RxBus-mvp模式下对Rxjav的封装(二)

一、自定义注解,用于标记观察者模式 Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) Documented public interface RegisterBus {} 二、定义一个RxBus的类 public class RxBus {public static final String TAG "RxBus";private stati…

离子赝势文件_排除离子错误

离子赝势文件Below is a brief overview on how to get started troubleshooting bugs in your Ionic projects. 以下是有关如何开始对Ionic项目中的错误进行故障排除的简要概述。 介绍 (Introduction) There are two main types of bugs that occur when developing in Ionic…

QuickTest底层VB脚本驱动

sample Codes: **** Author: Wally Yu (俞戴龙)*** Import common functions into report function ****Dim fso : set fso createobject("scripting.filesystemobject")executeglobal fso.opentextfile("C:\Framework\FrameworkCore\Common\common.vbs&q…

[收藏]使用 WSE 2.0 从 WS-Routing 转移到 WS-Addressing

使用 WSE 2.0 从 WS-Routing 转移到 WS-Addressing发布日期: 5/202004| 更新日期: 5/20/2004Aaron SkonnardNorthface University适用于:Web Services Enhancements 2.0 for Microsoft.NETWS-Routing 规范WS-Addressing 规范摘要:…