Reputation: 3822
I would like to authenticate against Azure from my Node backend. The acquireTokenWithClientCredentials
helps me out. Unfortunately I have to pass in a callback but I would like to await it and return a Promise with the new fetched token.
First I will show my working code using a callback
@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);
}
}
}
I would like to note that I only fetch a new session if the current one has expired. I would like to await that callback and return a Promise instead. Other functions requesting the session don't have to deal with callbacks then. So my updated code should look like
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;
}
Is there a way I can await the acquireTokenWithClientCredentials
function and don't have to use a callback?
Upvotes: 1
Views: 908
Reputation: 3822
I think I got it working with this code. Basically I'm just returning a new promise
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;
}
Please let me know if this can be simplified :)
Upvotes: 2