【问题标题】:Double authenticator with JWT in NodeJS ExpressNodeJS Express 中使用 JWT 的双重身份验证器
【发布时间】:2020-01-31 22:27:48
【问题描述】:

我目前正在尝试构建一个快速服务器,允许用户通过两个第三方服务进行身份验证:Google 和 Steam。身份验证是通过 JWT 完成的,当仅激活两个服务之一时它可以工作,但是当用户使用这两个服务之一登录时,我无法让受保护的路由工作。

代码:

const express = require('express');
const bodyParser = require('body-parser');
const {gAuth, gProtect} = require('./auth/google_auth');
const {sAuth, sProtect} = require('./auth/steam_auth');

const app = express();

gAuth(app);
sAuth(app);

//middlewares
app.use(express.static('views'));// folder in which to put the static files (html, css, js client)
app.use(bodyParser.json({limit: '50mb'})); // read json

//middlewares (just for the widget)
app.use(bodyParser.urlencoded({ extended: true , limit: '50mb'})); // read form enctype data
app.set('view engine', 'ejs'); // set the engine render ejs for dynamic building of html pages with ejs tags

//set up routers for v1 app
const genericRouter = require('./routes/generic_router'); //testing if the application is working
const secureRouter = require('./routes/secure_router'); //testing if normal auth is working

//set up routers for latest version app
app.use('/', genericRouter);
app.use('/', gProtect(), secureRouter);//protected end-points (requiring auth)
app.use('/', sProtect(), secureRouter);

module.exports = app;

问题出在

app.use('/', gProtect(), secureRouter);//protected end-points (requiring auth)
app.use('/', sProtect(), secureRouter);

bit,因为第二个 app.use 会覆盖第一个,导致所有通过 Google 进行的身份验证尝试都失败。我该怎么做才能使用户可以使用 Google 或 Steam 访问受保护的路由?

【问题讨论】:

    标签: node.js express authentication


    【解决方案1】:

    使用不同的端点

    app.use('/', genericRouter);
    app.use('/google', gProtect(), secureRouter);
    app.use('/steam', sProtect(), secureRouter);
    

    【讨论】:

    • 如果我需要访问安全端点 /secret 怎么办?在你的解决方案之后我无法到达它。
    • 尝试访问 /steam/secret 在未使用 Steam 登录时返回未经授权,但在登录时返回“无法获取 /steam/secret”。虽然 google 在这两种情况下都返回未经授权。
    • @texdade 您是否将这些 URL 添加到它们各自的第 3 方配置中的授权回调 URL 列表中?另外,我不知道您的 google_auth / steam_auth 代码的细节,因此很难进一步帮助您,此时我只是假设它正在经历典型的 OAuth 2.0 回调流程。如果特定 URL 需要身份验证,则需要在路由级别完成,例如app.get('/secret', authMiddleware()) - 我认为如果你更新你的问题,详细说明你正在尝试做什么,这会有所帮助,目前还不完全清楚。
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2018-12-06
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2018-08-20
    相关资源
    最近更新 更多