ngrok验证auth
by Michael Ozoemena
迈克尔·奥索埃梅纳(Michael Ozoemena)
GatsbyJS is a framework that uses GraphQL and ReactJS to enable you to create feature-rich, super fast and dynamic web apps. It gives you the ability to consume data from virtually anywhere and use them in your app. In this tutorial, I’ll be showing you how to use Auth0 which is an authentication and authorization platform to add authentication to your GatsbyJS application and to your serverless function on Netlify.
GatsbyJS是一个使用GraphQL和ReactJS的框架,使您能够创建功能丰富,超快速和动态的Web应用程序。 它使您能够从几乎任何地方使用数据并在应用程序中使用它们。 在本教程中,我将向您展示如何使用Auth0(身份验证和授权平台)向您的GatsbyJS应用程序和Netlify上的无服务器功能添加身份验证。
I’ll assume you have at least a basic understanding of React, Node, and GraphQL.
我假设您至少对React,Node和GraphQL有基本的了解。
Here’s the Github Repository if you want to take a look at the source code.
如果您想看一下源代码,这里是Github存储库 。
Created in 2015, Gatsby is a simple way to build a website with React. Today, Gatsby is known to be used to build websites like blogs, portfolio pages, and even e-commerce applications. Gatsby sites are known for being blazingly fast, and that is because when you build a website using Gatsby, it comes with tons of performance optimizations out-the-box, unlike some other frontend frameworks that leave you to figure out how to make your website more performant. Gatsby’s secret to being fast is in the fact that it follows the PRPL architectural pattern, which stands for:
Gatsby创建于2015年,是使用React构建网站的简单方法。 如今,众所周知,盖茨比(Gatsby)可用于构建博客,投资组合页面,甚至是电子商务应用程序之类的网站。 盖茨比(Gatsby)网站以快速发展着称,这是因为当您使用盖茨比(Gatsby)建立网站时,它具有大量的性能优化功能,这与其他一些前端框架不同,您无需弄清楚如何创建网站更有表现力。 盖茨比之所以能做到快速,是因为它遵循PRPL架构模式,该模式代表:
Push critical resources for the initial URL route using <link prelo
ad>and http/2.
使用<link prelo
ad>和http / 2为初始URL路由推送关键资源。
Render initial route.
渲染初始路线。
Pre-cache remaining routes.
预缓存剩余路由。
Lazy-load and create remaining routes on demand.
延迟加载并根据需要创建其余路由。
It is a pattern developed by Google for structuring and serving Progressive Web Apps (PWAs), with an emphasis on the performance of app delivery and launch. You can read more about this pattern here.
这是Google开发的一种模式,用于构建和服务渐进式Web应用程序(PWA),并着重于应用程序交付和启动的性能。 您可以在此处阅读有关此模式的更多信息 。
Auth0, pronounced as “Auth Zero” is a robust authentication and authorization platform. It makes it super easy to do add things like user registration, password retrieval, sign in, social login, multi-factor authentication, enterprise login, single sign-on, and more, into your production application.
Auth0 (发音为“ Auth Zero”)是一个强大的身份验证和授权平台。 它使在生产应用程序中添加用户注册,密码检索,登录,社交登录,多因素身份验证,企业登录,单点登录等功能变得非常容易。
Auth0 pays close attention to the developer’s experience with their excellent blogs posts and robust and easy to understand documentation. With Auth0 you can make use of various identity standards:
Auth0凭借其出色的博客文章以及功能强大且易于理解的文档,密切关注开发人员的体验。 使用Auth0,您可以使用各种身份标准:
OAuth 1
OAuth 1
OAuth 2
OAuth 2
Open ID Connect
打开ID连接
JSON Web Tokens (JWT)
JSON Web令牌(JWT)
Security Assertion Markup Language (SAML)
安全声明标记语言(SAML)
WS-Federation
WS联合会
In this tutorial, we’ll focus on using a combination of JSON Web Tokens and Social logins with OAuth 2.
在本教程中,我们将重点介绍结合使用JSON Web令牌和OAuth 2的社交登录名。
Netlify is a platform that lets you deploy your project without worrying about certain overheads like Continuous Deployment, HTTP Certs, and more, created as a way to deploy and manage static websites that don’t have a backend.
Netlify是一个平台,让你无需担心某些开销一样持续部署,HTTP证证书部署您的项目, 更多的 ,以此来部署和管理没有后端静态网站创建。
Now, because not everyone wants to deploy a static website and there’s the need for support for a backend, Netlify added a feature called “Serverless functions” which are backends where you don’t have to worry about the server infrastructure.
现在,由于并非每个人都希望部署静态网站,并且需要后端支持,因此Netlify添加了一项称为“无服务器功能”的功能,这是无需担心服务器基础结构的后端。
Behind the scenes, Netlify functions stand between you and something called Amazon Web Services (AWS) Lambda which is where the real “serverless” happens, and it lives on Amazon’s AWS cloud platform. Netlify functions help simplify things for you, so you don’t have to deal directly with AWS and also be able to keep using all of Netlify’s other cool features like Continuous Deployment.
在幕后,Netlify功能位于您和称为Amazon Web Services(AWS)Lambda的东西之间,这是真正的“无服务器”发生的地方,它存在于Amazon的AWS云平台上。 Netlify功能可帮助您简化事情,因此您不必直接与AWS交易,也可以继续使用Netlify的所有其他出色功能,例如持续部署。
The word “serverless” doesn’t imply without a server; it means that you as a developer need not worry about the server infrastructure (physical and otherwise).
“无服务器”一词并不意味着没有服务器。 这意味着您作为开发人员无需担心服务器基础结构(物理的或其他)。
You can read more about Netlify and their Serverless Functions.
Our app is called “Micro Blog”. It’s a platform that allows users to create short, frequent posts. Each post contains some text content, username and profile image of the person making the post.
我们的应用程序称为“微博客”。 这是一个允许用户创建简短频繁帖子的平台。 每个帖子都包含一些文本内容,用户名和创建该帖子的人的头像。
Anyone can open the web app and view posts of every other person, but to make a post themselves, they need to log in. The app supports social logins and an email login.
任何人都可以打开Web应用程序并查看每个人的帖子,但是要自己发表帖子,他们需要登录。该应用程序支持社交登录名和电子邮件登录名。
If you are already familiar with most of this stuff and want to see the code, you can head over to the source code on Github.
如果您已经熟悉了其中的大部分内容并想查看代码,则可以转到Github上的源代码 。
Our front-end is a GatsbyJS app, and that means the first thing we need to do is install the Gatsby CLI node package from npm.
我们的前端是一个GatsbyJS应用程序,这意味着我们需要做的第一件事是从npm安装Gatsby CLI节点软件包。
Note: Use node version “>= 6.9.0 <7.0.0 || >= 8.9.0” else you get an error when you try to create a new Gatsby site, this is because of the dependency “css-loader@1.0.1”.
注意:使用节点版本“> = 6.9.0 <7.0.0 ||” > = 8.9.0”,否则当您尝试创建新的Gatsby网站时会收到错误消息,这是因为依赖项为“ css-loader@1.0.1”。
# install the Gatsby CLI globallynpm install -g gatsby-cli
# create a new Gatsby site using the default startergatsby new micro-blog
After the commands are done running, you should be able to enter into the directory called “micro-blog”, relative to where you executed the commands above.
命令执行完毕后,相对于执行上述命令的位置,您应该能够进入名为“微博客”的目录。
cd micro-blog
When you take a look at the contents of this directory, you’ll find a ton of generated content. At this point, you can fire up your Gatsby site and see it working. To do that, in your terminal run this:
查看该目录的内容时,会发现大量的生成内容。 此时,您可以启动您的Gatsby网站并查看它是否正常运行。 为此,请在您的终端中运行以下命令:
gatsby develop
This will start up your Gatsby site on http://localhost:8000/
.
这将在http://localhost:8000/
上启动您的Gatsby网站。
Next step is to add and modify content specific to our application.
下一步是添加和修改特定于我们应用程序的内容。
We’ll start with gatsby-config.js
. Replace the contents of the file with:
我们将从gatsby-config.js
开始。 将文件内容替换为:
You might want to update the “<YOUR NAME>” author placeholder value.
您可能要更新“ <YOUR NAME>”作者占位符值。
This file contains your Gatsby app settings, stuff like your site metadata and plugins. It’s a pretty important file Gatsby looks for when you start up your app. Within the app, we can use GraphQL to query the contents of this file.
该文件包含您的Gatsby应用设置,以及网站元数据和插件之类的内容。 这是Gatsby在启动应用程序时会查找的非常重要的文件。 在应用程序中,我们可以使用GraphQL查询该文件的内容。
Up next, src/components/header.js
:
接下来, src/components/header.js
:
This file is our shared header component. Now, a few things are going on here:
此文件是我们的共享标头组件。 现在,这里发生了一些事情:
We are importing some things from gatsby
library: Link
and navigate
. Link
is a React component used to link to other pages that are within your app like “/app/home”, while navigate
is a function that accepts a URL and programmatically navigates the user to the specified URL.
我们正在从gatsby
库中导入一些内容: Link
和navigate
。 Link
是一个React组件,用于链接到应用程序内的其他页面,例如“ / app / home”,而navigate
是一种接受URL并以编程方式将用户导航到指定URL的功能。
isLoggedIn
, logout
, and getUserNickname
are methods that check if the user is logged in, log out the user, and get a logged in user’s nickname for display purposes, respectively.
isLoggedIn
, logout
和getUserNickname
是分别用于检查用户是否登录,注销用户以及获取已登录用户的昵称(用于显示)的方法。
Button
is a component that displays a button element for the user. It accepts several props that help us easily give the button varying looks.
Button
是为用户显示按钮元素的组件。 它接受了几个道具,可以帮助我们轻松地给按钮赋予不同的外观。
Here’s what Button
looks like:
这是Button
外观:
As you’ll see, we are going to be making use of Styled Components a lot and specifically emotion
, which is one of the many supported CSS-in-JS packages for GatsbyJS.
如您所见,我们将大量使用样式化组件 ,尤其是emotion
,这是GatsbyJS支持CSS-in-JS软件包之一。
Later, we will take a look at src/services/auth.js
.
稍后,我们将看一下src/services/auth.js
Next important file to look at is /src/components/layout.js
:
下一个要查看的重要文件是/src/components/layout.js
:
This file is the wrapper file for our application. It includes the header, a footer, and renders children passed to it. We also see the imported graphql
package from gatsby
alongside StaticQuery
component. StaticQuery
accepts a query
prop which is a GraphQL query. Whatever value resolved from the query
is made available in the StaticQuery
component’s render prop.
该文件是我们应用程序的包装文件。 它包括页眉,页脚,并呈现传递给它的子级。 我们还看到了从gatsby
导入的graphql
包以及StaticQuery
组件。 StaticQuery
接受query
道具,它是GraphQL查询。 通过query
解析的任何值都可以在StaticQuery
组件的呈现道具中使用。
Taking a closer look at the query, we can see that it’s getting data from the gatsby-config.js
file.
仔细研究查询,我们可以看到它正在从gatsby-config.js
文件中获取数据。
Our accompanying CSS /src/components/layouts.css
stays almost the same with the generated one with the only difference being from line 8:
我们随附CSS /src/components/layouts.css
与生成CSS /src/components/layouts.css
几乎相同,唯一的区别是与第8行的区别:
body {
margin: 0;
background-color: #f2f9ff;
}
Let’s leave the /src/components
directory for now and take a look at /src/pages/index.js
:
让我们/src/pages/index.js
离开/src/components
目录,看看/src/pages/index.js
:
All files in /src/pages/
become pages in your Gatsby App. For example, index.js
becomes the homepage and /src/pages/app/home.js
becomes http://yourdomain.com/app/home
.
/src/pages/
所有文件都将成为Gatsby App中的页面。 例如, index.js
成为主页,/ /src/pages/app/home.js
成为http://yourdomain.com/app/home
。
On our homepage, we want our users to see the recent posts and ask them to log in or sign up if they want to create a post.
在我们的主页上,我们希望我们的用户查看最近的帖子,并要求他们登录或注册,如果他们想要创建帖子。
To get our recent posts, we need axios
, which is a promise-based library for making network requests in JavaScript. Install axios
by running this in your terminal:
为了获得我们最近的帖子,我们需要axios
,这是一个基于axios
的库,用于使用JavaScript发出网络请求。 通过在终端中运行以下axios
来安装axios
:
npm install axios
When our component mounts, we check if the user is logged in and we redirect them to /app/home
because we don’t want them being on this page if they are logged in. Admittedly, this is a pretty naïve approach, and we could make use of “Protected Routes” instead. Using “Protected Routes” means that this component will not even get the chance to be mounted at all. Due to the small size of this project, I’ve decided not to make use of Protected Routes.
装入组件后,我们会检查用户是否登录,并将其重定向到/app/home
因为如果他们登录,我们不希望它们出现在此页面上。诚然,这是一种非常幼稚的方法,我们可以改用“受保护的路线”。 使用“受保护的路线”意味着该组件甚至根本没有机会安装。 由于该项目的规模较小,我决定不使用保护路线。
In case you want to implement Protected Routes in your Gatsby App, please refer to this guide on the official Gatsby website.
如果您想在自己的盖茨比应用中实施保护路线,请参考盖茨比官方网站上的本指南 。
We create a request to get the posts when our component mounts and then update the state with the returned data. Updating the state causes our component re-render the childRecentPosts
component since it makes use of the said state.
我们创建一个请求以在组件装入时获取帖子,然后使用返回的数据更新状态。 更新状态会导致我们的组件重新呈现子级的RecentPosts
组件,因为它使用了所述状态。
Notice that the URI in the network request to fetch the posts data is an environment variable process.env.API_URI
. These environment variables aren’t the typical environment variables you find in a Node app. To create these environment variables, you need two files in your Gatsby application root directory: env.production
and env.development
. These files will be automatically loaded by Gatsby in the appropriate environment when you start up your app.
请注意,网络请求中获取帖子数据的URI是一个环境变量process.env.API_URI
。 这些环境变量不是您在Node应用程序中找到的典型环境变量。 要创建这些环境变量,您的Gatsby应用程序根目录中需要两个文件: env.production
和env.development
。 启动应用程序时,Gatsby将在适当的环境中自动加载这些文件。
As I mentioned earlier, these environment variables aren’t the same with your Node environment variables and what makes them different is that they aren’t private files that you typically exclude in your .gitignore
file. You have to push these files when you want to deploy your app because GatsbyJS will need to read these files on startup.
如前所述,这些环境变量与您的Node环境变量并不相同,而与之不同的是它们不是通常不在.gitignore
文件中排除的私有文件。 当您要部署应用程序时,必须推送这些文件,因为GatsbyJS将需要在启动时读取这些文件。
Mine looks something like:
我的看起来像:
AUTH0_DOMAIN=micro-blog.auth0.com
AUTH0_CLIENTID=cIovhIQvYOr6fk3yhDtKjB5EiIvLevxf
REDIRECT_URI='http://localhost:8000/callback'
API_URI='http://localhost:9000/.netlify/functions/'
In production, it’s a bit different:
在生产中,这有点不同:
AUTH0_DOMAIN=micro-blog.auth0.com
AUTH0_CLIENTID=cIovhIQvYOr6fk3yhDtKjB5EiIvLevxf
REDIRECT_URI='https://angry-shaw-7a81ce.netlify.com/callback'
API_URI='https://angry-shaw-7a81ce.netlify.com/.netlify/functions/'
In order to get these values for your own app, you need to create an Auth0 account if you don’t already have one.
为了获得您自己的应用程序的这些值,如果您还没有一个Auth0帐户,则需要创建一个。
Note that you can use Auth0 for free with limited features.
请注意,您可以免费使用Auth0,但功能有限。
After you’ve created an account, log in to your Auth0 management dashboard and create a new Auth0 Application. You can do that by clicking on the Applications menu item and then the Create Application button. You can update the application name from “My App” to whatever else you want to use. You can change this later if you wish. In my case, I use “Micro Blog”.
创建帐户后,登录到Auth0 管理仪表板并创建一个新的Auth0应用程序。 您可以通过单击“应用程序”菜单项,然后单击“ 创建应用程序”按钮来执行此操作。 您可以将应用程序名称从“我的应用程序”更新为您要使用的其他名称。 如果需要,可以稍后更改。 就我而言,我使用“微博客”。
Next, you select “Single Page Web App” and click on Create. This will immediately create your application.
接下来,选择“单页Web应用程序”,然后单击“ 创建” 。 这将立即创建您的应用程序。
Once you are done with creating your application, you should navigate to “Settings”, there you will find your AUTH0_CLIENTID
and AUTH0_DOMAIN
values.
创建AUTH0_CLIENTID
应用程序后,应导航至“设置”,在这里您将找到AUTH0_CLIENTID
和AUTH0_DOMAIN
价值观。
Note: For your .env.production
, you don’t have the REDIRECT_URI
and API_URI
at this point. Later on, after we create our Netlify app, we will get the application URL which we can then put in there appropriately.
注意:对于您的.env.production
,您没有REDIRECT_URI
和API_URI
这一点。 稍后,在创建Netlify应用程序之后,我们将获得应用程序URL,然后可以将其适当地放入其中。
Now, let’s take a look at src/components/recentPosts.js
:
现在,让我们看一下src/components/recentPosts.js
:
Again, here we make use of Styled Components. We also make use of a React lifecycle method shouldComponentUpdate
to prevent unnecessary re-renders when the RecentPosts
component is used in another component.
同样,这里我们使用样式化组件。 我们还利用React生命周期方法shouldComponentUpdate
来防止在另一个组件中使用RecentPosts
组件时不必要的重新渲染。
When a user clicks on the login button, we navigate the user to an Auth0 login page. After they have been authenticated, we redirect the user to a URL in our app called /callback
where we check that the user has been logged in properly and then save their details in localStorage
. Here’s what the /callback
page looks like:
当用户单击登录按钮时,我们会将用户导航到Auth0登录页面。 在对他们进行身份验证之后,我们将用户重定向到应用程序中的URL,该URL称为/callback
,在此我们检查用户是否已正确登录,然后将其详细信息保存在localStorage
。 /callback
页面如下所示:
We call the handleAuthentication
method which will get data from the URL, parse it, save the extracted data to localStorage
and then call the () => naviage('/app/hom
e') method to redirect the user to the main app.
我们调用handleAuthentication
方法,该方法将从URL中获取数据,进行解析,将提取的数据保存到localStorage
,然后调用() => naviage('/app/hom
e')方法将用户重定向到主应用。
Now, we take a look at the /pages/app/home.js
page, where only logged in users can access:
现在,我们来看看/pages/app/home.js
页面,只有登录的用户可以访问:
There isn’t much that is new here. The only things I’d mention are:
这里没有太多新内容。 我唯一要提到的是:
We create new posts in the handlePostSubmit
method and in there, we make a regular axios
call but with a headers
option containing the JWT token “id_token”. We do that because, in our Serverless Function, we will be needing that value in the headers to authenticate a request, making sure that only a logged in user can create a new post and that the token saved on the client side is actually valid and not tampered with. This greatly improves the security and reliability of our app.
我们在handlePostSubmit
方法中创建新帖子,然后在其中进行常规的axios
调用,但带有包含JWT令牌“ id_token”的headers
选项。 这样做是因为在无服务器功能中,我们将需要标头中的值来验证请求,从而确保只有登录的用户才能创建新帖子,并且确保保存在客户端的令牌实际上是有效的,并且不被篡改。 这大大提高了我们应用程序的安全性和可靠性。
We redirect the user to /
when they aren’t logged in properly and they manage to land on this page. We do that in the componentDidMount
lifecycle method. Again, Protected Routes are a better option in your production apps.
如果用户未正确登录,我们会将其重定向到/
,并设法进入该页面。 我们在componentDidMount
生命周期方法中执行此操作。 同样, 受保护的路线是您的生产应用程序中更好的选择。
Finally, we get to /src/services/auth.js
. We have been using functions from this file throughout the app, it’s time to take a look at it:
最后,我们进入/src/services/auth.js
。 在整个应用程序中,我们一直在使用此文件中的功能,现在该看看它了:
In this file we use auth0-js
a JavaScript library by Auth0 to handle the authentication parts of our app. Add it to your app by running this in your terminal:
在此文件中,我们使用auth0-js
JavaScript库来处理应用程序的身份验证部分。 通过在终端中运行此命令,将其添加到您的应用中:
npm install auth0-js
Next thing you see in this file is the creation of isBrowser
which states if our file is currently being executed within the context of a browser. This is important because during the build process you might run into errors trying to call things like window.localStorage
.
在此文件中看到的下一件事情是isBrowser
的创建,该声明说明了我们的文件当前是否正在浏览器的上下文中执行。 这很重要,因为在构建过程中,尝试调用诸如window.localStorage
类的内容时可能会出错。
Let’s take a look at some of the methods in this file:
让我们看一下此文件中的一些方法:
The getUser
method gets the user details from the access token previously stored in the localStorage
, after our user has been logged in. It uses the getAccessToken
method to fetch the access token stored.
用户登录后, getUser
方法从先前存储在localStorage
的访问令牌中获取用户详细信息。它使用getAccessToken
方法来获取存储的访问令牌。
The handleLogin
method is called when the user tries to log in. It redirects them to the Auth0 login page which in turn redirects the user to /callback
once they’ve been logged in.
用户尝试登录时,将调用handleLogin
方法。它将用户重定向到Auth0登录页面,该页面又将用户登录后重定向到/callback
。
The isLoggedIn
method checks that the JWT token “id_token” expiration date saved in localStorage
as expiresAt
hasn’t been exceeded, thereby invalidating the user’s session.
isLoggedIn
方法检查是否未超过保存在localStorage
中的JWT令牌“ id_token”的过期日期,即expiresAt
,从而使用户会话无效。
The handleAuthentication
method is what you see being used in the /callback
page. This method parses the URL hash and gets important values which we later save in localStorage
in the setSession
method.
您可以在/callback
页面中看到handleAuthentication
方法。 此方法解析URL哈希并获取重要的值,我们稍后将其保存在setSession
方法中的localStorage
中。
Finally, the logout
method logs the user out by deleting saved credentials. This works well but you could take it a step further by calling an endpoint on Auth0 which will invalidate the session completely. I stopped here for the sake of this tutorial.
最后, logout
方法通过删除保存的凭据将用户logout
。 这很好用,但是您可以通过在Auth0上调用一个端点来进一步采取措施 ,这将使会话完全无效。 为了本教程,我在这里停了下来。
Finally, we update line 6 on /src/components/seo.js
:
最后,我们在/src/components/seo.js
上更新第6 /src/components/seo.js
:
const SEO = ({ description = null, lang = "eng", meta = [], keywords = [], title }) => {
Making it use an ES6 arrow function and default values.
使它使用ES6箭头功能和默认值。
Next, we are going to build an API to serve a list of posts and to collect new posts. They are serverless functions hosted on Netlify. Our API needs to do a few things:
接下来,我们将构建一个API,以提供帖子列表并收集新帖子。 它们是Netlify上托管的无服务器功能。 我们的API需要做一些事情:
Have an endpoint to serve the list of posts: /.netlify/functions/postsRead
.
有一个端点来提供帖子列表: /.netlify/functions/postsRead
. /.netlify/functions/postsRead
。
Have an endpoint to collect new posts: /.netlify/functions/postsCreate
.
有一个端点来收集新帖子: /.netlify/functions/postsCreate
. /.netlify/functions/postsCreate
。
To get started, we need to install a few npm packages:
首先,我们需要安装一些npm软件包:
npm install netlify-lambda mongoose jwks-rsa jsonwebtoken dotenv
Next step is to create a directory called utils
in the root directory of our Gatsby App. Inside that directory is where our files that aren’t quite the API will live. One of such files is our /utils/db.js
file:
下一步是在我们的盖茨比应用程序的根目录中创建一个名为utils
的目录。 在该目录中,不是API的文件将驻留在该目录中。 我们的/utils/db.js
文件就是/utils/db.js
文件之一:
In this file, we establish a connection to our MongoDB database.
在此文件中,我们建立与MongoDB数据库的连接。
Something missing here is our .env
file (yes, a third one!). Mine looks something like this:
这里缺少我们的.env
文件(是,第三个文件!)。 我的看起来像这样:
DATABASE_PROD='mongodb://<username>:<password>@<db_url>'DATABASE_DEV='mongodb://localhost:27017/micro-blog'
I use mLab to host my database online and I have MongoDB installed on my development machine. You can follow this guide to install MongoDB on your development machine too.
我使用mLab在线托管数据库,并且在开发计算机上安装了MongoDB 。 您也可以按照本指南在开发计算机上安装MongoDB 。
The next file to focus on is /utils/index.js
, this file contains some other methods we will make use of in our Netlify functions.
下一个要关注的文件是/utils/index.js
,该文件包含我们将在Netlify函数中使用的其他一些方法。
The first method respondWith
is abstracting the logic of responding to requests that get to our Netlify functions. And the second method verifyToken
is verifying that the tokens sent in the headers of requests are valid.
第一种方法respondWith
是抽象响应到达Netlify函数的请求的逻辑。 第二种方法verifyToken
验证请求头中发送的令牌是否有效。
Finally, into the Netlify functions. Create a new directory in your application root called functions
(or anything else you find appealing) and in that directory, create three files:
最后,进入Netlify功能。 在您的应用程序根目录中创建一个新的目录,称为functions
(或其他您认为有吸引力的目录),并在该目录中创建三个文件:
postsCreate.js
postsCreate.js
postsRead.js
postsRead.js
postsModel.js
postsModel.js
The first two files will hold our implementation for creating and reading posts while the last file will describe our Posts Database Schema.
前两个文件将保留我们用于创建和读取帖子的实现,而最后一个文件将描述我们的Posts数据库架构。
Here’s what the postsModel.js
looks like:
这是postsModel.js
样子:
And postsCreate.js
:
和postsCreate.js
:
Lastly, postsRead.js
:
最后, postsRead.js
:
Now, to run our functions locally, we first create a new script in our package.json
file:
现在,要在本地运行我们的函数,我们首先在package.json
文件中创建一个新脚本:
"scripts": {// other scripts
"start:lambda": "NODE_ENV=development netlify-lambda serve functions"
}
I use “serve functions” because the “functions” directory is where I put my Netlify functions, yours could be different.
我使用“服务功能”,因为“功能”目录是我放置Netlify功能的位置,您的功能可能有所不同。
After creating that script, we run it in our terminal:
创建该脚本之后,我们在终端中运行它:
npm run start:lambda
The last thing we will do is to deploy our app to Netlify and to do that we need to first create a file on our application root called netlify.toml
. This file is a configuration file which Netlify will read while trying to build and deploy the app. Here’s what that file looks like:
我们要做的最后一件事是将应用程序部署到Netlify上,为此,我们需要首先在应用程序根目录上创建一个名为netlify.toml
的文件。 该文件是Netlify在尝试构建和部署应用程序时将读取的配置文件。 该文件如下所示:
[build] functions = "lambda" Command = "npm run prod"
The functions = lambda
instructs Netlify put the built functions in a folder called “lambda”. And the Command = "npm run prod"
specifies a script to run in order to build the entire app. This is pretty important because we need to build both our Gatsby App and our Netlify functions. Here’s what that script looks like in our package.json
:
functions = lambda
指示Netlify将构建的函数放在一个名为“ lambda”的文件夹中。 Command = "npm run prod"
指定要运行的脚本,以构建整个应用程序。 这非常重要,因为我们需要构建Gatsby App和Netlify函数。 这就是我们package.json
中的脚本:
"scripts": {
// previous scripts
"build:lambda": "netlify-lambda build functions",
"prod": "NODE_ENV=production npm run build; npm run build:lambda"
Here, we first run npm run build
which builds our Gatsby App and then run npm run build:lambda
which builds our Netlify functions. Again, here I use “functions” because that is the name of the folder where I put my Netlify functions.
在这里,我们首先运行npm run build
来构建我们的盖茨比应用程序,然后运行npm run build:lambda
来构建Netlify函数。 同样,在这里我使用“函数”,因为那是我放置Netlify函数的文件夹的名称。
After doing all that, we create a new Github Repository and push our code there. Create a new Netlify account if you don’t already have one. I prefer using the Github signup option in this case. When you are logged in, you click on the New site from Git button which will then take you through the process of creating a new Netlify app.
完成所有这些之后,我们创建一个新的Github存储库,并将我们的代码推送到那里。 如果您还没有一个新的Netlify帐户 ,请创建一个。 在这种情况下,我更喜欢使用Github注册选项。 登录后,单击Git上的New site按钮,这将带您完成创建新Netlify应用程序的过程。
If during the process of creating a new Netlify app, you don’t find your repository in the list shown, be sure that you have given Netlify access to all your repositories or at least that repository in particular.
如果在创建新的Netlify应用程序的过程中,您没有在显示的列表中找到您的存储库,请确保已授予Netlify访问所有存储库的权限,至少可以访问该存储库。
Before you deploy, click on the Show Advanced button and create a new variable called DATABASE_PROD
, setting the value to what’s in your .env
file. Remember that this file is excluded from your app in your .gitignore
so there’s no way for your app to read this value unless you do this.
在部署之前,单击“ 显示高级”按钮并创建一个名为DATABASE_PROD
的新变量,并将其值设置为.env
文件中的值。 请记住,此文件在.gitignore
已从您的应用程序中排除,因此除非您执行此操作,否则您的应用程序无法读取该值。
Also, add public/
as the Publish directory since that is the directory where Gatsby builds and dumps the files.
另外,将public/
添加为Publish目录,因为那是Gatsby构建和转储文件的目录。
Netlify will automatically handle deploying the Functions. After the app has been deployed, you should see the URL of your app on your dashboard.
Netlify将自动处理功能的部署。 部署应用程序后,您应该在仪表板上看到应用程序的URL。
And now that you have the app URL, you can update your .env.production
file accordingly.
现在您有了应用程序URL,就可以相应地更新.env.production
文件。
Thanks for reading!
谢谢阅读!
翻译自: https://www.freecodecamp.org/news/how-to-set-up-gatsbyjs-authentication-with-auth0-d07abdd5a4f4/
ngrok验证auth