0

I am trying to use EventSource in my Angular for SSE. I have read that HttpInterceptor pattern only works for request sent by the HttpClient so EventSource is not captured for Authorisation with the server.

Is there a way to use interceptors to intercept all the streams ?

    startingPrinting() {
        //const headers = { 'Authorization': 'Bearer my-token' }
        const eventSource = new EventSource(environment.apiUrl + '/progress', { withCredentials: true });

        return new Observable<ProgressData>(observer => {
            eventSource.onmessage = event => {
                const messageData: ProgressData = JSON.parse(event.data);
                observer.next(messageData);
            };
        });
    }

and below is my JWTInterceptor

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('----- Inside JwtInterceptor -----');
        //console.log(this.authenticationService.userValue);
        // add auth header with jwt if user is logged in and request is to the api url
        const user = this.authenticationService.userValue;
        const isLoggedIn = user && user.jwt_token;
        const isApiUrl = request.url.startsWith(environment.apiUrl);
        if (isLoggedIn && isApiUrl) {
            console.log('Inside isLoggedIn of JWTInterceptor--------');
            request = request.clone({
                setHeaders: { Authorization: `Bearer ${user.jwt_token}` }
            });
        }
        return next.handle(request);
    }
}

cheers

Zolf

ZAJ
  • 793
  • 3
  • 23
  • 50
  • EventSource doesn't have API for headers. You won't be able to do that. There are workarounds though - https://stackoverflow.com/questions/28176933/http-authorization-header-in-eventsource-server-sent-events – mat.hudak Jun 14 '23 at 08:10

0 Answers0