使用 Auth0 通过单个应用程序登录对多个资源进行身份验证

Using Auth0 to authenticate against multiple resources with a single application login

我的应用程序使用 Auth0 进行了身份验证。用户输入他们的用户名 + 密码,Auth0 返回一个令牌,我的应用程序使用它来调用我的后端。

我的应用程序还在后台使用第 3 方应用程序,这些第 3 方应用程序都有自己的身份验证。当用户登录到我的应用程序时,它还需要出去并为所有这些第 3 方应用程序获取身份验证令牌。

例如,我的应用程序需要在 Watson 上使用 API,它使用不同的用户名 + 密码进行身份验证。用户无法知道用户名+密码是什么。相反,我的应用程序“知道”它们,该应用程序使用它们登录 Watson 并获取授权令牌以进行 API 调用。

Watson API 不是我的应用程序需要使用的唯一第 3 方 API。第 3 方 API 都有自己的身份验证方案。有些使用用户名 + 密码,其他使用 App ID 和 Secret 等。但在所有这些情况下,身份验证凭据都由我的应用程序拥有和管理 - 而不是我的应用程序的用户。

所以问题是,当用户登录到我的应用程序时,我如何使用 Auth0 自动出去并获取所有这些第 3 方身份验证令牌?

一旦 Auth0 身份验证令牌通过身份验证,然后在初始化事件中传递你的 watson API,使用 API 配置文件模块获取你的 watson API 的令牌。希望它能给出一些想法。

当用户通过 Auth0 进行身份验证后,客户端将收到 JSON Web 令牌 (JWT),可用于 API 服务器或其他第 3 方服务器。它还包含有关用户的信息,例如 UID 或电子邮件。

https://auth0.com/learn/json-web-tokens/

为了使用 Auth0 自动获取所有第 3 方身份验证令牌,您可以简单地使用 Rules 获取这些令牌并将其与您的 idToken 合并。然后客户端可以解码 JWT 并获得它需要的令牌或秘密。

规则是 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);
});

}

用户登录后,此规则将从Google请求Access_token,然后将其放入响应idToken。您可以将这种类似的模式用于其他 API。

https://auth0.com/docs/rules