3
votes

I am using the following code to construct NSHTTPCookie But there is no options to set httpOnly flag for cookie

[cookieProperties setObject:@"name" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"value" forKey:NSHTTPCookieValue];
[cookieProperties setObject:[NSNumber numberWithBool: NO] forKey:NSHTTPCookieDiscard];
[cookieProperties setObject:[dictionary objectForKey:@"isSecure"] forKey:NSHTTPCookieSecure];


[cookieProperties setObject:@"abc.xyz.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"abc.xyz.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];
3

3 Answers

11
votes

There's an undocumented cookie property key (found through @mikewest):

// Undocumented property of NSHTTPCookie.
NSString* const kNSHTTPCookieHttpOnly = @"HttpOnly";

I tried it in Swift, and it the code does what it's expected to do.

import Foundation

extension HTTPCookiePropertyKey {
    static let httpOnly = HTTPCookiePropertyKey("HttpOnly")
}

let cookie = HTTPCookie(properties: [
  .domain: "example.org",
  .path: "/",
  .name: "Cookie Example",
  .value: "Om nom nom",

  .version: 1, // RFC2965 for HttpOnly cookies
  .httpOnly: true
])!

print(cookie.isHTTPOnly) // true
3
votes

From the Apple documentation:

HTTPOnly Property

A boolean value that indicates whether the receiver should only be sent to HTTP servers per RFC 2965. (read-only)

Declaration

SWIFT

var HTTPOnly: Bool { get } 

OBJECTIVE-C

@property(readonly, getter=isHTTPOnly) BOOL HTTPOnly

Returns YES if this cookie should only be sent via HTTP headers, NO otherwise.

Cookies may be marked as HTTP only by a server (or by a javascript). Cookies marked as such must only be sent via HTTP Headers in HTTP requests for URL's that match both the path and domain of the respective cookies.

You can only set the HTTPOnly flag from the server or through a javascript. This isn't possible through the native iOS application code.

-1
votes

Just an update in 2022, there is no .httpOnly anymore in HTTPCookiePropertyKey anymore. I guess the old approach is not working anymore. Any ideas on the js side?