【发布时间】:2022-01-06 13:39:39
【问题描述】:
我正在构建一个 mern 应用程序。
使用 express 构建的后端公开了一个 api,用户可以创建数据并访问他们创建的数据。
我希望允许用户使用 google 登录并获得授权来创建和访问我控制的这个 api 上的资源(而不是在 google apis 上)。
我经常看到 oauth 2 / open id connect 文章,其中指出 Id 令牌供客户端使用,而资源服务器提供的访问令牌应用于访问 api。 例如https://auth0.com/blog/why-should-use-accesstokens-to-secure-an-api/
这样做的原因是,如果在 api 上使用,id 令牌上的 aud 属性将不正确。
我意识到有些消息来源说:如果 spa 和 api 由同一服务器提供并且具有相同的客户端 ID 和受众,我可以使用和 id 令牌对 api 进行身份验证,但我希望了解我能做什么当不是这种情况时怎么办?
我觉得使用 oauth2 进行授权对我的应用来说太过分了,而且我找不到任何有关如何使用 open id connect 对我的 api 进行身份验证的信息。
当您使用 google 登录到 Auth0 授权服务器时,肯定只是从 google 请求一个开放 id 连接 id 令牌?
我想知道使用授权码授予流程在 api 服务器上接收 id 令牌是否允许我通过我的 api 对用户进行身份验证?
在这种情况下,就 open id connect 而言,api 服务器是否是客户端,因此 aud 值是否正确?
我可以使用节点 googleapis 库生成一个 url 来访问 google oauth 服务器,如下所示:
const { google } = require("googleapis");
const oauth2Client = new google.auth.OAuth2(
'clientid','clientsecret',
"http://localhost:3000/oauthcallback",//this is where the react app is served from
);
const calendar = google.calendar({ version: "v3", auth: oauth2Client });
const scopes = ["openid"];
const url = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: "offline",
// If you only need one scope you can pass it as a string
scope: scopes,
});
async function getUrl(req, res) {
console.log(url)
res.status(200).json({
url,
});
}
并使用以下流程。
【问题讨论】:
-
这取决于实际的身份验证。假设使用 jwt(通常是这种情况),但使用对称密钥进行签名。这对于身份验证是完全安全的。但是客户端可能会自行伪造令牌来查询服务器上的资源。这会打开一个安全漏洞。
标签: node.js reactjs express openid-connect