Here are two methods that I have in my code.
The issue I'm facing is with the `get` method which I am overriding from the Http module. The problem is that the authentication success callback is being triggered after the request has already been executed and a response has been returned. This results in the JWT token being added to the headers in the incorrect order and at the wrong time.
I don't have a deep understanding of promises and observables, so I'm unsure how to make it wait for the callback to finish before proceeding with executing the request and sending back the response.
authenticate(authCompletedCallback, errorCallback) {
let authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);
authContext.tokenCache.readItems().then((items) => {
if (items.length > 0) {
AUTHORITY_URL = items[0].authority;
authContext = new Microsoft.ADAL.AuthenticationContext(AUTHORITY_URL);
}
// Attempt to authorize user silently.
authContext
.acquireTokenSilentAsync(RESOURCE_URL, CLIENT_ID)
.then(authCompletedCallback, () => {
// We require user credentials so trigger authentication dialog.
authContext
.acquireTokenAsync(RESOURCE_URL, CLIENT_ID, REDIRECT_URL)
.then(authCompletedCallback, errorCallback);
});
});
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
this.authenticate((authResponse) => {
// This section gets executed second.
if (!options) {
options = { headers: new Headers() };
}
options.headers.set('Authorization', 'Bearer ' + authResponse.accessToken);
}, (err) => {
alert(JSON.stringify(err));
});
// This part gets executed first.
return super.get(url, options);
}