iOS: how to set httponly flag for NSHTTPCookie

6.5k Views Asked by At

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];
4

There are 4 best solutions below

2
On BEST ANSWER

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.

3
On

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
0
On

NSHTTPCookiePropertyKey is just a typedef used for a set of string constants. String literals can be used for any standard cookie attribute that doesn't have a corresponding NSHTTPCookiePropertyKey.

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:@{
    NSHTTPCookieName : @"name",
    NSHTTPCookiePath : @"/",
    NSHTTPCookieValue : @"value",
    NSHTTPCookieDomain : @".example.com",
    @"HttpOnly" : @YES
}];
0
On

Anyone stumbling across this:

let cookie = HTTPCookie(properties: [
.domain: "xxxx.xxxx",
.path: "/",
.name: "token",
.value: "xxxxxx",
.version: 1,
.secure: true,
.expires: NSDate(timeIntervalSinceNow: 1234),
.init(rawValue: "HttpOnly"): true

])!

print(cookie.isHTTPOnly) // true