2 years ago

#47653

test-img

David R

How to intercept a static resource request in angular

In my angular app, I have the possibility to access server static resources (like images, documents, etc.) by an url like: http://localhost:4200/resources/logos/user_logo.png.

In order to protect the access to those resources, I want to add an authorization header and pass a token into these requests so I can filter the access in my backend server.

This request to /resources is made outside the scope of my angular routes, I only have a proxy config redirecting the request directly to the backend target:

{
  "/api": {
     ...
  },
  "/resources": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug"
  }
}

At the same time, my authorization interceptor is not intercepting this type of requests (at least the log is not called), so currently I don't know how to solve this issue.

...
@Injectable()
export class AuthorizationInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('intercept funtion called');
        
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${CookieHelper.getCookie('accessToken')}`,
                timestamp: '' + Date.now()
            }
        });

        return next.handle(request).pipe(...));
    }
}

My interceptor is being provided in AppModule like:

@NgModule({
  imports: [
    CommonModule,
  ],
  declarations: [],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AuthorizationInterceptor,
    multi: true
  }]
})
export class AppModule { ... }

Thanks in advance!

angular

authorization

angular-http-interceptors

0 Answers

Your Answer

Accepted video resources