使用 JavaScript、Auth0 和 Pusher 构建安全聊天 Web 应用程序

发布日期:2026-07-12 19:04:02   来源 : 杭州电子商务研究院    浏览量 :18
杭州电子商务研究院 发布日期:2026-07-12 19:04:02  
18

介绍

安全性很难。当我们构建应用程序时,我们希望只允许注册用户访问应用程序。我们希望能够管理用户帐户,查看他们上次登录的时间,禁用可疑帐户,并拥有一个仪表板来管理传入数据。我们可能还需要支持多因素身份验证和社交登录。

但安全性不仅难以实现,而且实施起来也需要时间。如果有一项服务可以帮您解决部分开发麻烦,那会怎样?为什么要花几周或几个月的时间自己进行身份验证?这就是Auth0 的优势所在。

本教程将深入介绍如何:

  • 使用 Pusher 构建聊天应用程序
  • 使用 Auth0 Lock 添加用户身份验证
  • 从 Auth0 仪表板管理用户。

Auth0 和 Pusher

Auth0是一家身份验证即服务 (或身份即服务) 提供商,专注于封装用户身份验证和管理。该服务提供了一个 SDK,允许开发人员轻松添加身份验证和管理用户。其用户管理仪表板可协助进行违规检测、多因素身份验证和无密码登录。

Pusher 的API 和托管基础架构使我们能够构建可扩展且可靠的实时应用程序。Pusher 的核心是通过渠道事件来工作的。渠道提供了一种过滤数据和控制对不同信息流的访问的方法。事件是 Pusher 系统中打包消息的主要方法,构成了所有通信的基础。

构建应用程序

我们将构建一个聊天应用程序,让用户可以进行交流,这样注册到特定频道的每个人都可以看到其他用户向该频道发送的消息。它的工作原理与 Slack 中的频道工作原理类似:只有一个频道供所有人交流。

以下是我们将要构建的内容:

设置后端

我们将首先构建后端,以便接收和广播聊天消息、提供静态文件以及设置 Auth0 和 Pusher。

首先,您需要注册一个 Pusher 和 Auth0 帐户。转到pusher.comauth0.com并注册一个帐户。要使用 Pusher API,我们必须从仪表板注册并创建一个 Pusher 应用程序。我们可以创建任意数量的应用程序,每个应用程序都会获得一个应用程序 ID 和密钥,我们将使用它在客户端或服务器端代码上初始化 Pusher 实例。

创建新的 Pusher 帐户要创建新的 Pusher 应用,请点击“您的应用”侧面菜单,然后点击抽屉下方的“创建新应用”按钮。这将打开设置向导。

  1. 输入应用程序的名称。在本例中,我将其命名为“聊天”。
  2. 选择一个集群。
  3. 如果您想要为开发、暂存和生产设置不同的实例,请选择“为多个环境创建应用程序”选项。
  4. 选择Vanilla JS作为前端,选择NodeJS作为后端。
  5. 单击“创建应用程序”按钮设置您的应用程序实例,完成该过程。

由于我们使用 Express 在 Node 中构建后端,因此让我们初始化一个新的 Node 应用程序并安装所需的依赖项。运行以下命令:

  1. npm init并选择默认选项
  2. npm i --save body-parser express pusher安装 express 和 Pusher node 包

添加一个名为server.js的新文件,该文件将包含用于验证 Pusher 客户端的逻辑,并呈现我们稍后将添加的静态文件。该文件将包含以下内容:

      var express = require('express');
var bodyParser = require('body-parser');
var Pusher = require('pusher');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var pusher = new Pusher({ appId: APP_ID, key: APP_KEY, secret:  APP_SECRET, cluster: eu });

app.post('/pusher/auth', function(req, res) {
    var socketId = req.body.socket_id;
    var channel = req.body.channel_name;
    var auth = pusher.authenticate(socketId, channel);
    res.send(auth);
});

app.post('/message', function(req, res) {
    var message = req.body.message;
    var name = req.body.name;
    pusher.trigger( 'private-chat', 'message-added', { message, name });
    res.sendStatus(200);
});

app.get('/',function(req,res){
        res.sendFile('/public/index.html', {root: __dirname });
});

app.use(express.static(__dirname + '/public'));

var port = process.env.PORT || 5000;
app.listen(port, function () {
    console.log(`app listening on port ${port}!`)
});
    

为了分解代码,我们首先通过传入一个包含应用程序 ID 和密钥详细信息的对象来实例化 Pusher。这些可以在Pusher 仪表板的“应用程序密钥”选项卡上找到。Pusher 还提供了一种在订阅时向频道验证用户的机制。为此,我们在服务器上公开一个端点,该端点将验证请求并以成功或失败响应。此端点将由 Pusher 客户端库调用,可以随意命名。我们在 Pusher 上为此端点使用了默认名称,即/pusher/auth。行var auth = pusher.authenticate(socketId, channel);使用 Pusher 对客户端进行身份验证,并向调用客户端返回身份验证代码。

为了允许此文件在我们启动 npm 时运行,我们使用以下值更新package.json :

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

创建 Auth0 客户端

创建 Auth0 客户端

  1. 从侧面菜单中选择客户端。
  2. 在新页面上,点击创建客户端按钮
  3. 输入应用程序的名称并选择“单页应用程序”作为选项
  4. 单击创建按钮来创建客户端。

Auth0 客户端为我们提供了客户端 ID 和密钥,我们将使用它们从代码中与 Auth0 进行交互。在设置选项卡上,我们可以看到名称、客户端 ID、密钥、客户端类型等。我想为我的域https://localhost:5000启用跨域资源共享 (CORS),并设置注销 URL 和身份验证后重定向 URL。使用https://localhost:5000更新以下设置

  1. 允许的回调 URL
  2. 允许的注销 URL
  3. 允许来源 (CORS)

构建前端

后端一切就绪后,我们就可以构建便于消息传递的网页。创建一个名为public的文件夹,其中包含 html 和 javascript 文件。创建两个新文件style.css 和 index.html,内容如下:

样式.css

      @import url("http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
.chat
{
    list-style: none;
    margin: 0;
    padding: 0;
}
.chat li
{
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px dotted #B3A9A9;
}
.chat li.left .chat-body
{
    margin-left: 60px;
}
.chat li.right .chat-body
{
    margin-right: 60px;
}

.chat li .chat-body p
{
    margin: 0;
    color: #777777;
}
.panel .slidedown .glyphicon, .chat .glyphicon
{
    margin-right: 5px;
}
.body-panel
{
    overflow-y: scroll;
    height: 250px;
}
::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    background-color: #F5F5F5;
}
::-webkit-scrollbar
{
    width: 12px;
    background-color: #F5F5F5;
}
::-webkit-scrollbar-thumb
{
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
    background-color: #555;
}
    

索引.html

      <!-- template from http://bootsnipp.com/snippets/6eWd -->
<!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script
        src="https://code.jquery.com/jquery-2.2.4.min.js"
        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
        crossorigin="anonymous"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.auth0.com/js/lock/10.18.0/lock.min.js"></script>
    <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
    <script src="index.js"></script>
</head>
<body>
    <div class="container">
    <div class="row form-group">
        <div class="col-xs-12 col-md-offset-2 col-md-8 col-lg-8 col-lg-offset-2">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <span class="glyphicon glyphicon-comment"></span> <span id="username"></span>
                    <div class="btn-group pull-right">
                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                            <span class="glyphicon glyphicon-chevron-down"></span>
                        </button>
                        <ul class="dropdown-menu slidedown">
                            <li><a><span class="glyphicon glyphicon-refresh">
                            </span>Refresh</a></li>
                            <li><a><span class="glyphicon glyphicon-ok-sign">
                            </span>Available</a></li>
                            <li><a><span class="glyphicon glyphicon-remove">
                            </span>Busy</a></li>
                            <li><a><span class="glyphicon glyphicon-time"></span>
                                Away</a></li>
                            <li class="divider"></li>
                            <li><a id="logout"><span class="glyphicon glyphicon-off"></span>
                                Sign Out</a></li>
                        </ul>
                    </div>
                </div>
                <div class="panel-body body-panel">
                    <ul class="chat">

                    </ul>
                </div>
                <div class="panel-footer clearfix"><
以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据