| 92 | } |
| 93 | |
| 94 | export function xsrfInterceptorFn( |
| 95 | req: HttpRequest<unknown>, |
| 96 | next: HttpHandlerFn, |
| 97 | ): Observable<HttpEvent<unknown>> { |
| 98 | // Skip both non-mutating requests |
| 99 | // Non-mutating requests generally don't require a token. |
| 100 | if ( |
| 101 | !inject(XSRF_ENABLED) || |
| 102 | req.method === 'GET' || |
| 103 | req.method === 'HEAD' || |
| 104 | req.method === 'QUERY' |
| 105 | ) { |
| 106 | return next(req); |
| 107 | } |
| 108 | |
| 109 | try { |
| 110 | const locationHref = inject(PlatformLocation).href; |
| 111 | const {origin: locationOrigin} = new URL(locationHref); |
| 112 | // We can use `new URL` to normalize a relative URL like '//something.com' to |
| 113 | // 'https://something.com' in order to make consistent same-origin comparisons. |
| 114 | const {origin: requestOrigin} = new URL(req.url, locationOrigin); |
| 115 | |
| 116 | if (locationOrigin !== requestOrigin) { |
| 117 | return next(req); |
| 118 | } |
| 119 | } catch { |
| 120 | // Handle invalid URLs gracefully. |
| 121 | return next(req); |
| 122 | } |
| 123 | |
| 124 | const token = inject(HttpXsrfTokenExtractor).getToken(); |
| 125 | const headerName = inject(XSRF_HEADER_NAME); |
| 126 | |
| 127 | // Be careful not to overwrite an existing header of the same name. |
| 128 | if (token != null && !req.headers.has(headerName)) { |
| 129 | req = req.clone({headers: req.headers.set(headerName, token)}); |
| 130 | } |
| 131 | return next(req); |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests. |