Điều gì xảy ra khi cookie hết hạn Javascript?

Cookies là các chuỗi dữ liệu nhỏ được lưu trữ trực tiếp trong trình duyệt. Chúng là một phần của giao thức HTTP, được xác định bởi đặc tả RFC 6265

Cookie thường được đặt bởi máy chủ web bằng cách sử dụng phản hồi

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
2 HTTP-header. Sau đó, trình duyệt sẽ tự động thêm chúng vào (hầu hết) mọi yêu cầu đối với cùng một miền bằng cách sử dụng tiêu đề HTTP
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
3

Một trong những trường hợp sử dụng phổ biến nhất là xác thực

  1. Khi đăng nhập, máy chủ sử dụng tiêu đề HTTP
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    2 trong phản hồi để đặt cookie có "số nhận dạng phiên" duy nhất
  2. Lần tới khi yêu cầu được gửi đến cùng một miền, trình duyệt sẽ gửi cookie qua mạng bằng cách sử dụng tiêu đề HTTP
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    3
  3. Vì vậy, máy chủ biết ai đã thực hiện yêu cầu

Chúng tôi cũng có thể truy cập cookie từ trình duyệt, sử dụng thuộc tính

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Có nhiều điều phức tạp về cookie và các tùy chọn của chúng. Trong chương này, chúng tôi sẽ đề cập chi tiết

Trình duyệt của bạn có lưu trữ bất kỳ cookie nào từ trang web này không?

// At javascript.info, we use Google Analytics for statistics,
// so there should be some cookies
alert( document.cookie ); // cookie1=value1; cookie2=value2;...

Giá trị của

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 bao gồm các cặp
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
8, được phân định bởi
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9. Mỗi cái là một cookie riêng biệt

Để tìm một cookie cụ thể, chúng ta có thể tách

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 cho
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9, sau đó tìm đúng tên. Chúng ta có thể sử dụng biểu thức chính quy hoặc hàm mảng để làm điều đó

Chúng tôi để nó như một bài tập cho người đọc. Ngoài ra, ở cuối chương, bạn sẽ tìm thấy các hàm trợ giúp để thao tác với cookie

Chúng ta có thể viết thư cho

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6. Nhưng nó không phải là một thuộc tính dữ liệu, nó là một bộ truy cập (getter/setter). Một nhiệm vụ cho nó được đối xử đặc biệt

Thao tác ghi vào

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 chỉ cập nhật các cookie được đề cập trong đó, nhưng không chạm vào các cookie khác

Chẳng hạn, cuộc gọi này đặt cookie có tên

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
4 và giá trị
// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
5

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies

Nếu bạn chạy nó, thì có thể bạn sẽ thấy nhiều cookie. Đó là bởi vì hoạt động

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
6 không ghi đè lên tất cả các cookie. Nó chỉ đặt cookie đã đề cập
// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
4

Về mặt kỹ thuật, tên và giá trị có thể có bất kỳ ký tự nào. Để giữ định dạng hợp lệ, chúng phải được thoát bằng hàm

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith
8 tích hợp

// special characters (spaces), need encoding
let name = "my name";
let value = "John Smith"

// encodes the cookie as my%20name=John%20Smith
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

alert(document.cookie); // ...; my%20name=John%20Smith

Hạn chế

Có một số hạn chế

  • Cặp
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    8, sau
    // special characters (spaces), need encoding
    let name = "my name";
    let value = "John Smith"
    
    // encodes the cookie as my%20name=John%20Smith
    document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
    alert(document.cookie); // ...; my%20name=John%20Smith
    8, không được vượt quá 4KB. Vì vậy, chúng tôi không thể lưu trữ bất kỳ thứ gì lớn trong cookie
  • Tổng số cookie trên mỗi miền được giới hạn trong khoảng hơn 20, giới hạn chính xác tùy thuộc vào trình duyệt

Cookie có một số tùy chọn, nhiều tùy chọn trong số đó rất quan trọng và nên được đặt

Các tùy chọn được liệt kê sau

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
1, được phân cách bởi
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
9, như thế này

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"

  • document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
    3

Tiền tố đường dẫn url phải là tuyệt đối. Nó làm cho cookie có thể truy cập được đối với các trang trong đường dẫn đó. Theo mặc định, đó là đường dẫn hiện tại

Nếu một cookie được đặt bằng

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
4, nó sẽ hiển thị ở các trang
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
5 và
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
6, nhưng không hiển thị ở trang
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
7 hoặc
document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
8

Thông thường, chúng ta nên đặt

document.cookie = "user=John; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"
9 vào thư mục gốc.
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
0 để có thể truy cập cookie từ tất cả các trang của trang web

  • // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    1

Miền xác định nơi có thể truy cập cookie. Tuy nhiên, trong thực tế vẫn còn những hạn chế. Chúng tôi không thể đặt bất kỳ tên miền nào

Không có cách nào để cookie có thể truy cập được từ một tên miền cấp 2 khác, vì vậy,

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
2 sẽ không bao giờ nhận được cookie được đặt tại
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3

Đó là một hạn chế về an toàn, để cho phép chúng tôi lưu trữ dữ liệu nhạy cảm trong cookie chỉ khả dụng trên một trang web

Theo mặc định, cookie chỉ có thể truy cập được tại miền đã đặt cookie

Xin lưu ý, theo mặc định, cookie cũng không được chia sẻ với tên miền phụ, chẳng hạn như

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
4

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user

…Nhưng điều này có thể thay đổi. Nếu chúng tôi muốn cho phép các tên miền phụ như

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
4 nhận cookie được đặt tại
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3, điều đó là có thể

Để điều đó xảy ra, khi đặt cookie tại

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3, chúng ta nên đặt rõ ràng tùy chọn
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
8 cho tên miền gốc.
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
1. Sau đó, tất cả các tên miền phụ sẽ thấy cookie đó

Ví dụ

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John

Vì lý do lịch sử,

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
0 (có dấu chấm trước
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
3) cũng hoạt động theo cách tương tự, cho phép truy cập cookie từ tên miền phụ. Đó là một ký hiệu cũ và nên được sử dụng nếu chúng tôi cần hỗ trợ các trình duyệt rất cũ

Tóm lại, tùy chọn

// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
8 cho phép tạo cookie có thể truy cập được tại các tên miền phụ

Theo mặc định, nếu cookie không có một trong các tùy chọn này, nó sẽ biến mất khi đóng trình duyệt. Những cookie như vậy được gọi là "cookie theo phiên"

Để cookie tồn tại khi đóng trình duyệt, chúng tôi có thể đặt tùy chọn

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
3 hoặc
// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
4

  • // at site.com
    // make the cookie accessible on any subdomain *.site.com:
    document.cookie = "user=John; domain=site.com"
    
    // later
    
    // at forum.site.com
    alert(document.cookie); // has cookie user=John
    5

Ngày hết hạn cookie xác định thời gian, khi trình duyệt sẽ tự động xóa nó

Ngày phải chính xác ở định dạng này, theo múi giờ GMT. Chúng ta có thể sử dụng

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
6 để lấy nó. Chẳng hạn, chúng tôi có thể đặt cookie hết hạn sau 1 ngày

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;

Nếu chúng tôi đặt

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
3 thành một ngày trong quá khứ, cookie sẽ bị xóa

  • // at site.com
    // make the cookie accessible on any subdomain *.site.com:
    document.cookie = "user=John; domain=site.com"
    
    // later
    
    // at forum.site.com
    alert(document.cookie); // has cookie user=John
    8

Đó là một giải pháp thay thế cho

// at site.com
// make the cookie accessible on any subdomain *.site.com:
document.cookie = "user=John; domain=site.com"

// later

// at forum.site.com
alert(document.cookie); // has cookie user=John
3 và chỉ định thời hạn hết hạn của cookie tính bằng giây kể từ thời điểm hiện tại

Nếu được đặt thành 0 hoặc giá trị âm, cookie sẽ bị xóa

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";

  • // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    0

Cookie chỉ nên được chuyển qua HTTPS

Theo mặc định, nếu chúng tôi đặt cookie ở

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
1, thì nó cũng xuất hiện ở
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
2 và ngược lại

Nghĩa là, cookie dựa trên tên miền, chúng không phân biệt giữa các giao thức

Với tùy chọn này, nếu một cookie được đặt bởi

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
2, thì nó sẽ không xuất hiện khi cùng một trang web được truy cập bởi HTTP, như
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
1. Vì vậy, nếu một cookie có nội dung nhạy cảm không bao giờ được gửi qua HTTP không được mã hóa, thì cờ
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
0 là điều đúng đắn

// assuming we're on https:// now
// set the cookie to be secure (only accessible over HTTPS)
document.cookie = "user=John; secure";

Đó là một thuộc tính bảo mật khác

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6. Nó được thiết kế để bảo vệ khỏi cái gọi là tấn công XSRF (giả mạo yêu cầu giữa các trang web)

Để hiểu cách nó hoạt động và khi nó hữu ích, hãy xem các cuộc tấn công XSRF

Hãy tưởng tượng, bạn đã đăng nhập vào trang web

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7. Đó là. bạn có cookie xác thực từ trang web đó. Trình duyệt của bạn sẽ gửi nó tới
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 với mọi yêu cầu, để nó nhận ra bạn và thực hiện tất cả các hoạt động tài chính nhạy cảm

Bây giờ, trong khi duyệt web trong một cửa sổ khác, bạn vô tình đến một trang web khác

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9. Trang web đó có mã JavaScript gửi biểu mẫu
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
0 đến
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 với các trường bắt đầu giao dịch tới tài khoản của tin tặc

Trình duyệt gửi cookie mỗi khi bạn truy cập trang web ________ 51 _______7, ngay cả khi biểu mẫu đã được gửi từ ________ 51 _______9. Vì vậy, ngân hàng nhận ra bạn và thực sự thực hiện thanh toán

Đó là cái gọi là cuộc tấn công “Cross-Site Request Forgery” (viết tắt là XSRF)

Các ngân hàng thực sự được bảo vệ khỏi nó tất nhiên. Tất cả các biểu mẫu được tạo bởi

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 đều có một trường đặc biệt, được gọi là “mã thông báo bảo vệ XSRF”, mà một trang xấu không thể tạo hoặc trích xuất từ ​​một trang từ xa. Nó có thể gửi một biểu mẫu ở đó, nhưng không thể lấy lại dữ liệu. Trang web
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 kiểm tra mã thông báo đó ở mọi dạng mà nó nhận được

Việc bảo vệ như vậy cần có thời gian để thực hiện mặc dù. Chúng tôi cần đảm bảo rằng mọi biểu mẫu đều có trường mã thông báo bắt buộc và chúng tôi cũng phải kiểm tra tất cả các yêu cầu

Tùy chọn cookie ________ 51 _______ 6 cung cấp một cách khác để bảo vệ khỏi các cuộc tấn công như vậy, mà (về lý thuyết) không yêu cầu “mã thông báo bảo vệ csrf”

Nó có hai giá trị có thể

  • // cookie will die in +1 hour from now
    document.cookie = "user=John; max-age=3600";
    
    // delete cookie (let it expire right now)
    document.cookie = "user=John; max-age=0";
    7 (giống như
    // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    6 không có giá trị)

Cookie có

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
7 sẽ không bao giờ được gửi nếu người dùng đến từ bên ngoài cùng một trang web

Nói cách khác, cho dù người dùng nhấp vào liên kết từ thư của họ hoặc gửi biểu mẫu từ

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9 hoặc thực hiện bất kỳ thao tác nào bắt nguồn từ miền khác, cookie sẽ không được gửi

Nếu cookie xác thực có tùy chọn

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6, thì cuộc tấn công XSRF không có cơ hội thành công vì gửi từ
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
9 không có cookie. Vì vậy,
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 sẽ không nhận ra người dùng và sẽ không tiến hành thanh toán

Bảo vệ khá đáng tin cậy. Chỉ các thao tác đến từ

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 mới gửi cookie
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6, e. g. gửi biểu mẫu từ một trang khác tại
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7

Mặc dù, có một sự bất tiện nhỏ

Khi người dùng theo một liên kết hợp pháp đến

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7, chẳng hạn như từ ghi chú của chính họ, họ sẽ ngạc nhiên rằng
// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
7 không nhận ra họ. Thật vậy,
// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
7 cookie không được gửi trong trường hợp đó

Chúng tôi có thể giải quyết vấn đề đó bằng cách sử dụng hai cookie. một cho "sự công nhận chung", chỉ với mục đích nói. “Xin chào, John” và một cái khác dành cho các hoạt động thay đổi dữ liệu với

// cookie will die in +1 hour from now
document.cookie = "user=John; max-age=3600";

// delete cookie (let it expire right now)
document.cookie = "user=John; max-age=0";
7. Sau đó, một người đến từ bên ngoài trang web sẽ thấy chào mừng, nhưng các khoản thanh toán phải được thực hiện từ trang web của ngân hàng để cookie thứ hai được gửi

  • // returns the cookie with the given name,
    // or undefined if not found
    function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    1

Một cách tiếp cận thoải mái hơn cũng bảo vệ khỏi XSRF và không phá vỡ trải nghiệm người dùng

Chế độ lỏng lẻo, giống như

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
2, cấm trình duyệt gửi cookie khi đến từ bên ngoài trang web, nhưng thêm một ngoại lệ

Một cookie

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
1 được gửi nếu cả hai điều kiện này đều đúng

  1. Phương thức HTTP là “an toàn” (e. g. NHẬN, nhưng không ĐĂNG)

    Danh sách đầy đủ các phương thức HTTP an toàn nằm trong đặc tả RFC7231. Về cơ bản, đây là những phương thức nên được sử dụng để đọc, nhưng không ghi dữ liệu. Họ không được thực hiện bất kỳ thao tác thay đổi dữ liệu nào. Theo một liên kết luôn là GET, phương pháp an toàn

  2. Hoạt động thực hiện điều hướng cấp cao nhất (thay đổi URL trong thanh địa chỉ của trình duyệt)

    Điều đó thường đúng, nhưng nếu điều hướng được thực hiện trong

    // returns the cookie with the given name,
    // or undefined if not found
    function getCookie(name) {
      let matches = document.cookie.match(new RegExp(
        "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
      ));
      return matches ? decodeURIComponent(matches[1]) : undefined;
    }
    4, thì đó không phải là cấp cao nhất. Ngoài ra, các phương thức JavaScript cho các yêu cầu mạng không thực hiện bất kỳ điều hướng nào, do đó chúng không phù hợp

Vì vậy, điều mà

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
1 làm, về cơ bản là cho phép thao tác “đi tới URL” phổ biến nhất có cookie. e. g. mở một liên kết trang web từ các ghi chú đáp ứng các điều kiện này

Nhưng bất cứ điều gì phức tạp hơn, chẳng hạn như yêu cầu mạng từ một trang web khác hoặc gửi biểu mẫu, sẽ mất cookie

Nếu điều đó phù hợp với bạn, thì việc thêm

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}
1 có thể sẽ không ảnh hưởng đến trải nghiệm người dùng và thêm khả năng bảo vệ

Nhìn chung,

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6 là một lựa chọn tuyệt vời

Có một nhược điểm

  • // +1 day from now
    let date = new Date(Date.now() + 86400e3);
    date = date.toUTCString();
    document.cookie = "user=John; expires=" + date;
    6 bị bỏ qua (không được hỗ trợ) bởi các trình duyệt rất cũ, năm 2017 hoặc lâu hơn

Vì vậy, nếu chúng tôi chỉ dựa vào

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6 để cung cấp sự bảo vệ, thì các trình duyệt cũ sẽ dễ bị tấn công

Nhưng chúng tôi chắc chắn có thể sử dụng

// +1 day from now
let date = new Date(Date.now() + 86400e3);
date = date.toUTCString();
document.cookie = "user=John; expires=" + date;
6 cùng với các biện pháp bảo vệ khác, chẳng hạn như mã thông báo xsrf, để thêm một lớp bảo vệ bổ sung và sau đó, trong tương lai, khi các trình duyệt cũ ngừng hoạt động, chúng tôi có thể sẽ loại bỏ mã thông báo xsrf

Tùy chọn này không liên quan gì đến JavaScript, nhưng chúng tôi phải đề cập đến nó cho đầy đủ

Máy chủ web sử dụng tiêu đề

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
2 để đặt cookie. Ngoài ra, nó có thể đặt tùy chọn
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
02

Tùy chọn này cấm mọi quyền truy cập JavaScript vào cookie. Chúng tôi không thể nhìn thấy một cookie như vậy hoặc thao tác với nó bằng cách sử dụng

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Điều đó được sử dụng như một biện pháp phòng ngừa, để bảo vệ khỏi một số cuộc tấn công nhất định khi tin tặc đưa mã JavaScript của chính anh ta vào một trang và đợi người dùng truy cập trang đó. Điều đó hoàn toàn không thể xảy ra, tin tặc sẽ không thể đưa mã của họ vào trang web của chúng tôi, nhưng có thể có lỗi cho phép họ làm điều đó

Thông thường, nếu điều đó xảy ra và người dùng truy cập trang web bằng mã JavaScript của hacker, thì mã đó sẽ thực thi và giành quyền truy cập vào

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 bằng cookie người dùng chứa thông tin xác thực. Điều đó thật xấu

Nhưng nếu một cookie là

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
02, thì
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 không nhìn thấy nó, vì vậy nó được bảo vệ

Đây là một tập hợp nhỏ các chức năng để hoạt động với cookie, thuận tiện hơn so với sửa đổi thủ công của

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6

Có nhiều thư viện cookie cho điều đó, vì vậy những thư viện này là dành cho mục đích demo. Hoàn toàn làm việc mặc dù

Cách ngắn nhất để truy cập cookie là sử dụng biểu thức chính quy

Hàm

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
08 trả về cookie với giá trị
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
09 đã cho

// returns the cookie with the given name,
// or undefined if not found
function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

Ở đây

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
10 được tạo động, để khớp với
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
11

Xin lưu ý rằng giá trị cookie được mã hóa, vì vậy,

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
12 sử dụng hàm
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
13 tích hợp để giải mã

Đặt

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
09 của cookie thành
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
15 đã cho với
// if we set a cookie at site.com website...
document.cookie = "user=John"

// ...we won't see it at forum.site.com
alert(document.cookie); // no user
0 theo mặc định (có thể được sửa đổi để thêm các giá trị mặc định khác)

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
0

Để xóa cookie, chúng ta có thể gọi nó với ngày hết hạn âm

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
1

Cập nhật hoặc xóa phải sử dụng cùng một đường dẫn và tên miền

Xin lưu ý. khi chúng tôi cập nhật hoặc xóa cookie, chúng tôi nên sử dụng chính xác các tùy chọn tên miền và đường dẫn giống như khi chúng tôi đặt nó

Cùng với nhau. bánh quy. js

Cookie được gọi là "bên thứ ba" nếu nó được đặt bởi một tên miền khác với trang mà người dùng đang truy cập

Ví dụ

  1. Một trang tại

    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    3 tải một biểu ngữ từ một trang web khác.
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    18

  2. Cùng với biểu ngữ, máy chủ từ xa tại

    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19 có thể đặt tiêu đề
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    2 với một cookie như
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    21. Một cookie như vậy bắt nguồn từ tên miền
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19 và sẽ chỉ hiển thị tại
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19

  3. Lần tới khi truy cập

    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19, máy chủ từ xa sẽ nhận cookie
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    25 và nhận ra người dùng

  4. Điều thậm chí còn quan trọng hơn là khi người dùng di chuyển từ

    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    3 sang một trang web khác
    // if we set a cookie at site.com website...
    document.cookie = "user=John"
    
    // ...we won't see it at forum.site.com
    alert(document.cookie); // no user
    2, cũng có biểu ngữ, thì
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19 sẽ nhận được cookie, vì nó thuộc về
    document.cookie = "user=John"; // update only cookie named 'user'
    alert(document.cookie); // show all cookies
    19, do đó nhận ra khách truy cập và theo dõi anh ta khi anh ta di chuyển giữa các trang web

Cookie của bên thứ ba thường được sử dụng cho các dịch vụ theo dõi và quảng cáo, do bản chất của chúng. Chúng bị ràng buộc với miền ban đầu, vì vậy

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
19 có thể theo dõi cùng một người dùng giữa các trang web khác nhau, nếu tất cả họ đều truy cập vào nó

Đương nhiên, một số người không thích bị theo dõi, vì vậy các trình duyệt cho phép tắt các cookie đó

Ngoài ra, một số trình duyệt hiện đại sử dụng các chính sách đặc biệt cho các cookie đó

  • Safari hoàn toàn không cho phép cookie của bên thứ ba
  • Firefox đi kèm với một "danh sách đen" các tên miền của bên thứ ba nơi nó chặn cookie của bên thứ ba

Xin lưu ý

Nếu chúng tôi tải tập lệnh từ miền của bên thứ ba, chẳng hạn như

document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
31 và tập lệnh đó sử dụng
document.cookie = "user=John"; // update only cookie named 'user'
alert(document.cookie); // show all cookies
6 để đặt cookie, thì cookie đó không phải là của bên thứ ba

Nếu tập lệnh đặt cookie, thì bất kể tập lệnh đến từ đâu – cookie thuộc về miền của trang web hiện tại

Chủ đề này hoàn toàn không liên quan đến JavaScript, chỉ là một điều cần lưu ý khi đặt cookie

Có một luật ở Châu Âu gọi là GDPR, thực thi một bộ quy tắc để các trang web tôn trọng quyền riêng tư của người dùng. Một trong những quy tắc này là yêu cầu quyền rõ ràng để theo dõi cookie từ người dùng

Xin lưu ý, đó chỉ là về theo dõi/xác định/ủy quyền cookie

Vì vậy, nếu chúng tôi đặt cookie chỉ lưu một số thông tin, nhưng không theo dõi cũng như không xác định người dùng, thì chúng tôi có thể tự do thực hiện

Nhưng nếu chúng tôi định đặt cookie có phiên xác thực hoặc id theo dõi, thì người dùng phải cho phép điều đó

Các trang web thường có hai biến thể tuân theo GDPR. Chắc hẳn bạn đã thấy cả hai trên web rồi

  1. Nếu một trang web chỉ muốn đặt cookie theo dõi cho người dùng được xác thực

    Để làm như vậy, biểu mẫu đăng ký phải có hộp kiểm như “chấp nhận chính sách quyền riêng tư” (mô tả cách sử dụng cookie), người dùng phải chọn hộp kiểm đó và sau đó trang web được tự do đặt cookie xác thực

  2. Nếu một trang web muốn đặt cookie theo dõi cho mọi người

    Để làm như vậy một cách hợp pháp, một trang web hiển thị “màn hình giật gân” theo phương thức cho người mới và yêu cầu họ đồng ý với cookie. Sau đó, trang web có thể đặt chúng và cho phép mọi người xem nội dung. Điều đó có thể gây khó chịu cho khách truy cập mới mặc dù. Không ai thích xem những màn hình giật gân kiểu “phải bấm” thay vì nội dung. Nhưng GDPR yêu cầu một thỏa thuận rõ ràng

GDPR không chỉ về cookie mà còn về các vấn đề khác liên quan đến quyền riêng tư, nhưng điều đó vượt quá phạm vi của chúng tôi

Hầu hết các cookie đều có ngày hết hạn. 'Cookie phiên' sẽ tự động bị xóa khi bạn đóng trình duyệt . 'Cookie liên tục' được lập trình để lưu lại trên máy tính của bạn trong một số tháng. Bạn có thể xóa chúng theo cách thủ công bất kỳ lúc nào trước khi chúng hết hạn.
Xóa Cookie bằng JavaScript . tài liệu. cookie = "tên người dùng=; hết hạn=Thứ năm, ngày 01 tháng 1 năm 1970 00. 00. 00 UTC; . set the expires parameter to a past date: document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; You should define the cookie path to ensure that you delete the right cookie.