🍪 Ocookie

Cookie and Set-Cookie parser and serializer.

Installation

To install ocookie add the following to your pubspec.yaml

dependencies:
  ocookie: latest

Alternatively, you can run the following command:

dart pub add ocookie

Basic Usage

final cookie = Cookie('name', 'value');
print(cookie.serialize()); // name=value
print(Cookie.parse('a=b;b=c')); // {a: b, b: c}

final setCookie = Cookie.fromString(
  'sid=abc; Path=/; HttpOnly; Secure; SameSite=None',
);
print(setCookie.path); // /

final stored = StoredCookie.fromSetCookie(
  'sid=abc; Path=/; HttpOnly',
  requestUri: Uri.parse('https://example.com/login'),
);
print(stored.matches(Uri.parse('https://example.com/profile'))); // true
print(stored.toRequestCookie()); // sid=abc

final jar = CookieJar();
await jar.save(
  Uri.parse('https://example.com/login'),
  ['sid=abc; Path=/; HttpOnly'],
);
print(await jar.header(Uri.parse('https://example.com/profile'))); // sid=abc

final values = Cookie.splitSetCookie(
  'a=b; Expires=Wed, 21 Oct 2015 07:28:00 GMT, c=d; Path=/',
);
print(values); // [a=b; Expires=Wed, 21 Oct 2015 07:28:00 GMT, c=d; Path=/]

Utils

  • Cookie.serialize - Serialize a cookie instance to string.
  • Cookie.validate - Validate a cookie and return all errors.
  • Cookie.parse - Parse client-side cookie header map.
  • Cookie.fromString - Parse a set-cookie string to Cookie instance.
  • Cookie.splitSetCookie - Split a string of multiple set-cookie values into a set-cookie string list.
  • StoredCookie.fromSetCookie - Normalize a Set-Cookie value for request matching.
  • CookieJar - Save Set-Cookie values and build matching Cookie request headers.
  • CookieStore - Plug in custom persistence behind the jar policy layer.

CopyWith And Clear

final original = Cookie(
  'sid',
  'abc',
  path: '/demo',
  secure: true,
  sameSite: CookieSameSite.none,
);

final updated = original.copyWith(path: '/next');
final cleared = original.copyWith(
  clear: {CookieNullableField.path},
);

Validation

final cookie = Cookie(
  'sid',
  'abc',
  sameSite: CookieSameSite.none,
);

final errors = cookie.validate();
if (errors.isNotEmpty) {
  print(errors);
}

Security Constraints

  • SameSite=None requires Secure=true.
  • Partitioned=true requires Secure=true.

Flag Semantics

  • HttpOnly, Secure, and Partitioned are two-state flags.
  • Omitting a flag is equivalent to setting it to false.

API Reference

See the API documentation for detailed information about all available APIs.

License

MIT License

Libraries

ocookie