Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wait for extension event to complete #403

Closed
janfejtek opened this issue Jun 27, 2024 · 2 comments
Closed

Wait for extension event to complete #403

janfejtek opened this issue Jun 27, 2024 · 2 comments

Comments

@janfejtek
Copy link

Hi, I would like to get microsoft token using MSAL library and then send it to server, but the extension does not wait for events to finish. Can this be somehow achieved? I can create PR but I'm not sure if it makes sense for the library or how the solution should look like.

Simplified version of my usage would be:

export class TokenExtension {

    initialize(naja) {
        naja.addEventListener('before', this.before.bind(this));
    }
    async before(event) {
       let token = await fetch('https://microsoft.com');
       event.request.headers.set('X-Token', token);
    }
}

I noticed similar point here #383 . Unfortunately, I'm too late for 3.0 release...

@jiripudil
Copy link
Member

Hi, I'm afraid this is not currently possible. Naja relies on DOM's standard EventTarget for event dispatch, and that API is, unfortunately, synchronous.

But the before event contains all you need to recreate the request, and can be default-prevented to abort the request. You can use all this to fetch the token and dispatch the request manually afterwards:

export class TokenExtension {
    initialize(naja) {
        this.naja = naja;
        naja.addEventListener('before', this.before.bind(this));
    }
    before(event) {
        const {request, method, url, data, options} = event.detail;

        // if the token is already in options, set up the request and early-return to proceed
        if (options.msalToken) {
            request.headers.set('X-Token', options.msalToken);
            return;
        }

        // call preventDefault() to abort current request processing
        event.preventDefault();

        // fetch the token and rerun the request, passing the token in options
        fetch('https://microsoft.com').then((msalToken) => this.naja.makeRequest(method, url, data, {...options, msalToken}));
    }
}

@jiripudil
Copy link
Member

I'm closing this in hope that this resolves your issue. Feel free to comment or reopen if you have further thoughts on the topic, though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants