具有openid-client策略的Passport.js-TypeError:客户端必须是openid-client Client的实例

时间:2019-05-24 04:07:48

标签: reactjs typescript passport.js openid-connect

我正在使用打字稿构建MERN堆栈应用程序。我正在使用带有Openid客户端策略(https://github.com/panva/node-openid-client/blob/master/docs/README.md#strategy)的通行证进行用户身份验证。我收到以下typeError:

TypeError: client must be an instance of openid-client Client

我尝试使用Issuer.discover和新的Issuer(),并等待/异步,确保节点和我所有的软件包都是最新的,无济于事。

这是相关代码:

import { Issuer, Strategy, generators } from "openid-client";

const googleClient = Issuer.discover("https://accounts.google.com/.well-known/openid-configuration")
    .then((googleIssuer: { Client: any; }) => {
        return googleIssuer.Client;
    });

应该返回一个openid-client Client实例,但它返回一个未决的Promise。

2 个答案:

答案 0 :(得分:0)

您可以“等待”诺言,然后将“ then”语句的返回值分配给googleClient变量。

尝试

import { Issuer, Strategy, generators } from "openid-client";
​
let googleClient;
(async function discoverClient() {
  googleClient = await Issuer.discover("https://accounts.google.com/.well-known/openid-configuration")
  .then((googleIssuer: { Client: any; }) => {
    return googleIssuer.Client;
  });
})();

有关异步/等待https://javascript.info/async-await

的一些很好的信息

答案 1 :(得分:0)

解决方案,供他人参考。我必须把一切都放在诺言中。

Issuer.discover('https://accounts.google.com/.well-known/openid-configuration')
    .then((googleIssuer: { issuer: any; metadata: any; Client: any; }) => {
        // console.log('Discovered issuer %s %O', googleIssuer.issuer, googleIssuer.metadata);
        const client = new googleIssuer.Client({
            client_id: process.env.GOOGLE_ID,
            client_secret: process.env.GOOGLE_SECRET,
            redirect_uris: ['list of URIs here'],
            response_types: ['code token id_token'],
        });

        const params = {
            client_id: process.env.GOOGLE_ID,
            response_type: 'code token id_token',
            scope: 'openid profile email',
            nonce: generators.nonce(),
            redirect_uri: 'URI here',
            state: generators.state(),
            prompt: 'select_account',
            display: 'popup',
            login_hint: 'sub',
        };

        const verify = ( tokenSet: any, userInfo: any, done: (arg0: null, arg1: any) => void ) => {
            console.log('USERINFO: ', userInfo);
            console.log('TOKENSET: ', tokenSet);
            return done(null, tokenSet);
        };

        const options = {
            client,
            params,
        };
        Passport.use('openid-client', new Strategy( options, verify ));
    }).catch((err: any) => {
        if (err) {
            console.log(err);
        }
    });