我的应用程序使用 Auth0 进行身份验证。用户输入他们的用户名 + 密码,Auth0 返回一个 token ,我的应用程序使用该 token 调用我的后端。
我的应用程序还在后台使用第 3 方应用程序,这些第 3 方应用程序都有自己的身份验证。当用户登录到我的应用程序时,它还需要出去并为所有这些第 3 方应用程序获取身份验证 token 。
例如,我的应用程序需要在 Watson 上使用一个 API,该 API 使用不同的用户名 + 密码进行身份验证。用户无法知道用户名+密码是什么。相反,我的应用程序“知道”它们,该应用程序使用它们登录 Watson 并获取授权 token 以进行 API 调用。
Watson API 并不是我的应用需要使用的唯一第 3 方 API。第三方 API 都有自己的身份验证方案。有些使用用户名 + 密码,其他使用 App ID 和 Secret 等。但在所有这些情况下,身份验证凭据都由我的应用程序拥有和管理,而不是由我的应用程序的用户拥有和管理。
所以问题是,当用户登录到我的应用程序时,我如何使用 Auth0 自动出去并获取所有这些第 3 方身份验证 token ?
最佳答案
当用户通过 Auth0 进行身份验证后,客户端将收到可与 API 服务器或其他第 3 方服务器一起使用的 JSON Web Token (JWT)。它还包含有关用户的信息,例如 UID 或电子邮件。
参见 https://auth0.com/learn/json-web-tokens/
为了使用 Auth0 自动获取所有第 3 方身份验证 token ,您可以简单地使用 Rules 获取这些 token 并将其与您的 idToken 合并。然后客户端可以解码 JWT 并获得它需要的 token 或 secret 。
规则是将在用户通过身份验证后执行的 JavaScript 代码。
这是来自 Auth0 的示例代码
function (user, context, callback) {
// this is the private key you downloaded from your service account.
// make sure you remove the password from the key and convert it to PEM using the following
// openssl pkcs12 -in yourkey.p12 -out yourkey.pem -nocerts -nodes
// finally, you should put this as a configuration encrypted in Auth0
var KEY = '....RSA private key downloaded from service account...';
// this is the email address of the service account created (NOT the Client ID)
var GOOGLE_CLIENT_ID_EMAIL = '.....@developer.gserviceaccount.com';
// the scope you want access to. Full list of scopes https://developers.google.com/admin-sdk/directory/v1/guides/authorizing
var SCOPE = 'https://www.googleapis.com/auth/admin.directory.user.readonly';
// a user of your Google Apps domain that this rule would impersonate
var ADMIN_EMAIL = 'foo@corp.com';
var token = jwt.sign({ scope: SCOPE, sub: ADMIN_EMAIL }, KEY, { audience: "https://accounts.google.com/o/oauth2/token", issuer: GOOGLE_CLIENT_ID_EMAIL, expiresInMinutes: 60, algorithm: 'RS256'});
request.post({ url: 'https://accounts.google.com/o/oauth2/token', form: { grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: token } }, function(err, resp, body) {
if (err) return callback(null, user, context);
var result = JSON.parse(body);
if (result.error) {
console.log(body);
// log and swallow
return callback(null, user, context);
}
context.idToken['https://example.com/admin_access_token'] = result.access_token;
callback(null, user, context);
});
}
用户登录后,这条规则会向谷歌请求Access_token,然后把它放在响应的idToken中。您可以将这种类似的模式用于其他 API。
关于authentication - 使用 Auth0 通过单个应用程序登录对多个资源进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47183390/