express react_在30分钟内使用Express.js构建博客并进行React

express reactBuilding a web server sounds complicated, but it doesn't have to be! What if I told you that you can create a web server with just a couple lines of code? Yes! You can do things like this...
摘要由CSDN通过智能技术生成

express react

Building a web server sounds complicated, but it doesn't have to be! What if I told you that you can create a web server with just a couple lines of code? Yes! You can do things like this using Express.js (the most popular web framework for Node developers).

构建Web服务器听起来很复杂,但这不是必须的! 如果我告诉您可以仅用几行代码创建Web服务器该怎么办? 是! 您可以使用Express.js(Node开发人员最流行的Web框架)执行类似的操作。

In this tutorial you'll learn how to create a simple "My Blog" App that allows a user can create, edit, and delete a post. You'll also learn how to add authentication to the app so users have to sign in before being allowed to do any CRUD (create, read, update, delete) actions. The tutorial will use the fabulous Okta NodeJS OIDC Middleware for authentication. The back-end will use Express.js to power the server, Sequelize for storing and manipulating data, and Epilogue for automatically generating REST endpoints and controllers from the Sequelize data models.

在本教程中,您将学习如何创建一个简单的“我的博客”应用程序,该应用程序允许用户创建,编辑和删除帖子。 您还将学习如何向应用程序添加身份验证,以便用户必须先登录才能被允许执行任何CRUD(创建,读取,更新,删除)操作。 本教程将使用神话般的Okta NodeJS OIDC中间件进行身份验证。 后端将使用Express.js为服务器供电, Sequelize用于存储和处理数据,而Epilogue将根据Sequelize数据模型自动生成REST端点和控制器。

Express.js应用必备条件 ( Express.js App Prerequisites )

Before you begin, head over to https://developer.okta.com/ and create an account, or log in if you’ve already signed up. The Okta service is free, and is what you'll be using to handle the user registration, login, logout, etc. It's an API service for managing user identities.

在开始之前,请转到https://developer.okta.com/并创建一个帐户,或者如果已经注册则登录。 Okta服务是免费的,您将使用它来处理用户注册,登录,注销等操作。它是用于管理用户身份的API服务。

Once you've signed up for Okta, follow these steps below to configure it. This will make it easier to implement user authentication later on.:

注册Okta后,请按照以下步骤进行配置。 这将使以后更容易实现用户身份验证。

After you log in, you will see the Org Url in the top right corner of your dashboard, save it somewhere for later use. Click Application on the navigation menu.

登录后,您会在仪表板的右上角看到Org Url ,并将其保存在某处以备后用。 单击导航菜单上的应用程序

  • Click the Add Application button.

    单击添加应用程序按钮。

  • Select Web as the software, click the Next button.

    选择Web作为软件,单击“ 下一步”按钮。

  • Enter the following information, then click the Done button.

    输入以下信息,然后单击“ 完成”按钮。

  • Name: My Blog

    名称 :我的博客

  • Base URIs: http://localhost:3000/

    基本URIhttp://localhost:3000/

  • Login redirect URIs: https://localhost:3000/authorization-code/callback

    登录重定向URIhttps://localhost:3000/authorization-code/callback

You will then be redirected to the general page, scroll down you will see Client ID and Client Secret values, save these somewhere for later use. These are your app's API keys that it will use to securely handle user authentication later on via the OpenID Connect protocol.

然后,您将被重定向到常规页面,向下滚动您将看到Client IDClient Secret值,将它们保存在某个地方以备后用。 这些是您应用程序的API密钥,以后将通过OpenID Connect协议将其用于安全地处理用户身份验证。

NOTE: You might be wondering why you haven't written any code and are already using an API service here. The reason is that handling user authentication yourself is actually pretty tricky. There are very few ways to do it correctly, and lots of easy ways to mess up that are non-obvious. Using a free service like Okta to handle this piece of the application will make your project code a lot simpler later on.

注意 :您可能想知道为什么没有编写任何代码并且已经在这里使用API​​服务。 原因是您自己处理用户身份验证实际上很棘手。 正确执行此操作的方法很少,而且很多显而易见的简单方法也可以解决。 使用Okta之类的免费服务来处理这部分应用程序,将使您的项目代码稍后变得更加简单。

The way the Okta service works is by using the OAuth/OpenID Connect protocols behind the scenes to handle all of your user management. Okta handles user registration, login, password reset, multi-factor authentication, and lots of other stuff.

Okta服务的工作方式是通过在后台使用OAuth / OpenID Connect协议来处理所有用户管理。 Okta处理用户注册,登录,密码重置,多因素身份验证以及许多其他工作。

设置Express.js ( Set Up Express.js )

You should have node and npm installed, my Node version is v10.10.0 and npm version is 6.4.1. Create a project folder and basic set up with the following:

您应该已经安装了nodenpm ,我的Node版本是v10.10.0 ,npm版本是6.4.1 。 创建一个项目文件夹并使用以下内容进行基本设置:

mkdir myblog
cd myblog
npm init

Continue selecting enter to accept all default settings.

继续选择回车以接受所有默认设置。

You should now have this folder structure:

您现在应该具有以下文件夹结构:

myblog
└── package.json

0 directories, 1 file

Now, add two new files, index.js and .env, to your folder, so your project ends up looking like this:

现在,将两个新文件index.js.env添加到您的文件夹中,这样您的项目最终将如下所示:

myblog
├── .env
├── index.js
└── package.json

0 directories, 3 files

Now you can install the required npm modules that are needed for this Express.js app. To do so, run the following commands:

现在,您可以安装此Express.js应用程序所需的必需npm模块。 为此,请运行以下命令:

npm install express@4.16.4 --save

(module needed to start the Express web application)

(启动Express Web应用程序所需的模块)

npm install cors@2.8.5 --save

(module enable Cross-origin resource sharing)

(模块启用跨域资源共享)

npm install body-parser@1.18.3 --save

(module that helps to parse incoming request bodies)

(有助于解析传入的请求正文的模块)

npm install dotenv@6.2.0 --save

(module that will load our .env file into process.env variables)

(将我们的.env文件加载到process.env变量中的模块)

npm install nodemon@1.18.9 --save-dev

(tool that helps automatically restart the application when file changed)

(有助于在文件更改时自动重新启动应用程序的工具)

These two npm modules are for Okta authentication.

这两个npm模块用于Okta身份验证。

npm install @okta/oidc-middleware@1.0.2 express-session@1.15.6 --save

In your .env file, use the Org URL, Client ID, and Client Secret you got from the Okta console to fill in the following and paste it in the file (you got them in the setup credentials steps above):

在您的.env文件中,使用从Okta控制台获得的组织URL,客户端ID和客户端密钥填写以下内容并将其粘贴到文件中(在上述设置凭据步骤中获得了它们):

OKTA_ORG_URL={
    yourOktaOrgUrl}
OKTA_CLIENT_ID={
    yourClientId}
OKTA_CLIENT_SECRET={
    yourClientSecret}
REDIRECT_URL=http://localhost:3000/authorization-code/callback
RANDOM_SECRET_WORD='super secret'

NOTE: The RANDOM_SECRET_WORD setting should be a random string you type out. Just bang on the keyboard for a second to output a long random string, and use that value. This value should never be checked into source control as it is used to manage the integrity of your user sessions. It must be kept private on your web servers and should be extremely hard to guess.

注意RANDOM_SECRET_WORD设置应该是您键入的随机字符串。 只需敲击键盘一秒钟即可输出一个较长的随机字符串,然后使用该值。 永远不要将此值检查到源代码管理中,因为它用于管理用户会话的完整性。 它必须在Web服务器上保持私有状态,并且很难猜测。

In your index.js file, paste in the following code:

index.js文件中,粘贴以下代码:

require('dotenv').config();
const express = require('express');
const path = require('path');
const cors = require('cors');
const bodyParser = require('body-parser');
const session = require('express-session');
const {
      ExpressOIDC } = require('@okta/oidc-middleware');
const app = express();
const port = 3000;

// session support is required to use ExpressOIDC
app.use(session({
     
    secret: process.env.RANDOM_SECRET_WORD,
    resave: true,
    saveUninitialized: false
}));

const oidc = new ExpressOIDC({
     
    issuer: `${
       process.env.OKTA_ORG_URL}/oauth2/default`,
    client_id: process.env.OKTA_CLIENT_ID,
    client_secret: process.env.OKTA_CLIENT_SECRET,
    redirect_uri: process.env.REDIRECT_URL,
    scope: 'openid profile',
    routes: {
     
        callback: {
     
            path: '/authorization-code/callback',
            defaultRedirect: '/admin'
        }
    }
});

// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routes
app.use(oidc.router);
app.use(cors());
app.use(bodyParser.json());

app.get('/', (req, res) => {
     
  res.send('<h1>Welcome!!</h1>');
});

app.listen(port, () => console.log(`My Blog App listening on port ${
       port}!`))

Let me explain what the above code does. The line that starts with app.use(session…) created session middleware with the options we passed it. This is required for ExpressOIDC's configuration. OIDC stands for OpenID Connect, it is an authentication layer on top of OAuth 2.0. You can learn more about the OpenID Connect & OAuth 2.0 API here.

让我解释一下以上代码的作用。 以app.use(session…)开头的行创建了带有我们传递的选项的会话中间件。 这是ExpressOIDC的配置所必需的。 OIDC代表OpenID Connect,它是OAuth 2.0之上的身份验证层。 您可以在此处了解有关OpenID Connect&OAuth 2.0 API的更多信息

The line that starts with const oidc = new ExpressOIDC(...) created an instance of ExpressOIDC with the option we passed in. It enables your application to participate in the authorization code flow by redirecting the user to Okta for authentication and handling the callback from Okta. Once the flow is completed, a local session is created and the user context is saved for the duration of the session.

const oidc = new ExpressOIDC(...)开头的行使用我们传入的选项创建了ExpressOIDC的实例。通过将用户重定向到Okta进行身份验证并处理回调,它使您的应用程序可以参与授权代码流来自Okta。 流程完成后,将创建本地会话,并在会话持续时间内保存用户上下文。

The app.use(oidc.router) line is required in order for ensureAuthenticated and isAuthenticated to work. It also adds the following route:

必须使用app.use(oidc.router)行,以确保ensureAuthenticatedisAuthenticated正常工作。 它还添加以下路线:

  • /login - redirects to the Okta sign-in page by default

    /login login-默认情况下重定向到Okta登录页面

  • /authorization-code/callback - processes the OIDC response, then attaches user info to the session

    /authorization-code/callback处理OIDC响应,然后将用户信息附加到会话

Now that work is done, you can move on to the next step. In package.json, add "start": "./node_modules/.bin/nodemon index.js" under scripts. This will allow you to simply type npm start to start the application. nodemon is a utility that will monitor for any changes in your source and automatically reload, so you don’t have to restart your server manually.

现在工作已经完成,您可以继续下一步。 在package.json ,在脚本下添加"start": "./node_modules/.bin/nodemon index.js" 。 这将使您只需键入npm start即可启动应用程序。 nodemon是一个实用程序,它将监视源中的任何更改并自动重新加载,因此您不必手动重新启动服务器。

"scripts": {
    
    "start": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
 },

Run npm start then go to http://localhost:3000/ and you should see:

运行npm start然后转到http:// localhost:3000 / ,您应该看到:

Now you have your Express.js app set up! Next you’ll integrate with OpenID Connect (OIDC) to let the user sign in.

现在,您已经设置了Express.js应用程序! 接下来,您将与OpenID Connect(OIDC)集成,以使用户登录。

在Express中添加身份验证 ( Add Authentication in Express )

Because we have added app.use(oidc.router) to our index.js, we got the /login route for free, which means we don't have to set it up ourselves. Anytime a request goes to /login, Okta middleware will take care for us.

因为我们已经将app.use(oidc.router)添加到index.js ,所以我们免费获得了/login路由,这意味着我们不必自己进行设置。 每当有请求发送到/login ,Okta中间件都会为我们服务。

Let's add a link to let user login. In index.js, replace:

让我们添加一个链接以允许用户登录。 在index.js ,替换为:

app.get('/', (req, res) => {
     
  res.send('<h1>Welcome!!</h1>');
});

With:

带有:

app.get('/home', (req, res) => {
     
 res.send('<h1>Welcome!!</div><a href="/login">Login</a>');
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值