【问题标题】:promisify the acquireTokenWithClientCredentials function from adal-node从 adal-node 承诺 acquireTokenWithClientCredentials 函数
【发布时间】:2019-12-23 22:19:27
【问题描述】:

我想从我的 Node 后端对 Azure 进行身份验证。 acquireTokenWithClientCredentials 帮助我。不幸的是,我必须传入一个回调,但我想等待它并返回一个带有新获取令牌的 Promise。

首先我将使用回调显示我的工作代码

@Injectable()
export class AuthenticationsService {
    private session: TokenResponse;

    private authenticationContext: AuthenticationContext;

    // -- setup the AuthenticationContext and configurations in the constructor --

    getSession(sessionCallback: Function): void {
        if (!this.session || this.session.expiresOn < new Date()) {
            this.authenticationContext.acquireTokenWithClientCredentials(resource, clientId, clientSecret, (error: Error, tokenResponse: TokenResponse) => {
                if (error) {
                    throw error;
                }

                this.session = tokenResponse;
                sessionCallback(this.session);
            });
        } else {
            sessionCallback(this.session);
        }
    }
}

我想指出,如果当前会话已过期,我只会获取一个新会话。我想等待那个回调并返回一个 Promise 。其他请求会话的函数则不必处理回调。所以我更新后的代码应该是这样的

async getSession(): Promise<TokenResponse> {
    if (!this.session || this.session.expiresOn < new Date()) {
        try {
            this.session = await this.authenticationContext.acquireTokenWithClientCredentials(resource, clientId, clientSecret);
        } catch (error) {
            throw error;
        }
    }

    return this.session;
}

有没有一种方法可以等待acquireTokenWithClientCredentials 函数而不必使用回调?

【问题讨论】:

    标签: javascript azure azure-active-directory adal adal.js


    【解决方案1】:

    我想我可以使用此代码。基本上我只是在返回一个新的承诺

    async getSession(): Promise<TokenResponse> {
        if (!this.session || this.session.expiresOn < new Date()) {
            return new Promise((resolve, reject) => {
                this.authenticationContext.acquireTokenWithClientCredentials(resource, clientId, clientSecret, (error: Error, tokenResponse: TokenResponse) => {
                    if (error) {
                        return reject(error);
                    }
    
                    this.session = tokenResponse;
                    return resolve(this.session);
                });
            });
        }
    
        return this.session;
    }
    

    请让我知道这是否可以简化:)

    【讨论】:

      猜你喜欢
      • 2017-04-05
      • 2019-01-23
      • 1970-01-01
      • 2017-07-09
      • 2015-08-26
      • 1970-01-01
      • 2019-12-17
      相关资源
      最近更新 更多