【发布时间】: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