Đây là trình chặn mẫu đọc mã thông báo từ tiêu đề phản hồi nếu nó tồn tại và đặt tự động trên mọi yêu cầu cần.
import {Interceptor, HttpResponseMessage, RequestMessage} from "aurelia-http-client";
class CsrfHeaderInterceptor implements Interceptor {
private static readonly TOKEN_HEADER = 'X-CSRF-Token';
private latestCsrfToken: string;
response(response: HttpResponseMessage): HttpResponseMessage {
if (response.headers.has(CsrfHeaderInterceptor.TOKEN_HEADER)) {
this.latestCsrfToken = response.headers.get(CsrfHeaderInterceptor.TOKEN_HEADER);
}
return response;
}
request(request: RequestMessage): RequestMessage {
if (this.latestCsrfToken) {
if (['POST', 'PUT', 'PATCH'].indexOf(request.method) >= 0) {
request.headers.add(CsrfHeaderInterceptor.TOKEN_HEADER, this.latestCsrfToken);
}
}
return request;
}
}
Bạn đăng ký nó trong http của bạn/lấy khách hàng với ví dụ:
httpClient.configure((config) => {
config
.withBaseUrl("/api/") // adjust to your needs
.withHeader('Accept', 'application/json') // adjust to your needs
.withHeader('X-Requested-With', 'XMLHttpRequest') // adjust to your needs
.withInterceptor(new CsrfHeaderInterceptor());
});
Sử dụng ModSecurity. Đó là một mô-đun cho apache hoặc nginx, hoặc có thể hoạt động như một proxy ngược. Nó có tính năng chống CSRF tích hợp sẵn. Hoặc sử dụng một cái gì đó như cloudflare –