我想从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
函数,而不必使用回调?
我想我可以使用此代码。基本上我只是在返回新的承诺
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;
}
请让我知道是否可以简化:)