是否可以使用 UIWebView 的共享HTTPCookieStorage 手动设置 cookie?

发布于 2024-11-06 10:03:32 字数 335 浏览 0 评论 0原文

我的 iOS 应用程序内有 webview,需要身份验证 cookie 才能正确进行身份验证。我正在寻找一种在 iOS 应用程序的 webview 内设置 cookie 的方法,而无需发出出站请求来设置 cookie,因为我已经在客户端上有了身份验证信息。

这篇帖子向我们展示了 UIWebView cookie 的存储位置。

现在,我正在加载一个隐藏的 Web 视图来发出出站请求,但我不想发出外部请求来设置简单的 cookie。

I have webviews inside of an iOS application that require an authentication cookie to be properly authenticated. I'm looking for a way to set a cookie inside of an iOS application's webview without having to make an outbound request to set the cookie as I have auth information on the client already.

This post shows us where the UIWebView cookies are stored.

Right now I'm loading a hidden web view to make an outbound request but would prefer not to have to make an external request for setting a simple cookie.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

疑心病 2024-11-13 10:03:32

是的,你可以这样做。首先,在 applicationDidBecomeActive 中添加此行

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

cookieAcceptPolicy 在应用程序之间共享,并且可以在您不知情的情况下进行更改,因此您需要确保每次运行应用程序时都拥有所需的接受策略。

然后,设置 cookie:

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

该 cookie 的名称为 testCookie,值为 someValue123456,并将与任何 http 请求一起发送到 www.example.com。

对于设置 cookie 的一大警告,请在此处查看我的问题!

NSHTTPCookieStorage 状态未在应用程序退出时保存。有任何明确的知识/文档吗?

Yes, you can do this. First, in applicationDidBecomeActive add this line

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

The cookieAcceptPolicy is shared across apps and can be changed without your knowledge, so you want to be sure you have the accept policy you need every time your app is running.

Then, to set the cookie:

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"testCookie" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"someValue123456" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"www.example.com" forKey:NSHTTPCookieOriginURL];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
[cookieProperties setObject:@"0" forKey:NSHTTPCookieVersion];

// set expiration to one month from now or any NSDate of your choosing
// this makes the cookie sessionless and it will persist across web sessions and app launches
/// if you want the cookie to be destroyed when your app exits, don't set this
[cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

This cookie has the name testCookie and value someValue123456 and will be sent with any http request to www.example.com.

For one big caveat to setting cookies, please see my question here!

NSHTTPCookieStorage state not saved on app exit. Any definitive knowledge/documentation out there?

旧情勿念 2024-11-13 10:03:32

编辑:适应已编辑的问题

NSHTTPCookieStorage 有一个 -setCookies:forURL:mainDocumentURL: 方法,因此最简单的方法是使用 NSURLConnection 并实现 -connection:didReceiveResponse:,提取 cookie 并将其填充到 cookie jar 中:(

- ( void )connection: (NSURLConnection *)connection
          didReceiveResponse: (NSURLResponse *)response
{
    NSHTTPURLResponse        *httpResponse = (NSHTTPURLResponse *)response;
    NSArray                  *cookies;

    cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields:
                             [ httpResponse allHeaderFields ]];
    [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
            setCookies: cookies forURL: self.url mainDocumentURL: nil ];
}

您也可以简单地从中提取 NSDictionary 对象带有 propertiesNSHTTPCookie,然后将其读回磁盘就像使用 NSDictionary一样简单。 -dictionaryWithContentsOfFile: 然后使用 -initWithProperties: 创建 cookie。)

然后您可以在需要时将 cookie 从存储中拉出:

- ( void )reloadWebview: (id)sender
{
    NSArray                 *cookies;
    NSDictionary            *cookieHeaders;
    NSMutableURLRequest     *request;

    cookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
                cookiesForURL: self.url ];
    if ( !cookies ) {
        /* kick off new NSURLConnection to retrieve new auth cookie */
        return;
    }

    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies ];
    request = [[ NSMutableURLRequest alloc ] initWithURL: self.url ];
    [ request setValue: [ cookieHeaders objectForKey: @"Cookie" ]
              forHTTPHeaderField: @"Cookie" ];

    [ self.webView loadRequest: request ];
    [ request release ];
}

Edit: adapting for edited question

NSHTTPCookieStorage has a -setCookies:forURL:mainDocumentURL: method, so the easy thing to do is use NSURLConnection and implement -connection:didReceiveResponse:, extracting cookies and stuffing them into the cookie jar:

- ( void )connection: (NSURLConnection *)connection
          didReceiveResponse: (NSURLResponse *)response
{
    NSHTTPURLResponse        *httpResponse = (NSHTTPURLResponse *)response;
    NSArray                  *cookies;

    cookies = [ NSHTTPCookie cookiesWithResponseHeaderFields:
                             [ httpResponse allHeaderFields ]];
    [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
            setCookies: cookies forURL: self.url mainDocumentURL: nil ];
}

(You can also simply extract an NSDictionary object from the NSHTTPCookie with properties, and then write the dictionary to the disk. Reading it back in is as easy as using NSDictionary's -dictionaryWithContentsOfFile: and then creating the cookie with -initWithProperties:.)

Then you can pull the cookie back out of the storage when you need it:

- ( void )reloadWebview: (id)sender
{
    NSArray                 *cookies;
    NSDictionary            *cookieHeaders;
    NSMutableURLRequest     *request;

    cookies = [[ NSHTTPCookieStorage sharedHTTPCookieStorage ]
                cookiesForURL: self.url ];
    if ( !cookies ) {
        /* kick off new NSURLConnection to retrieve new auth cookie */
        return;
    }

    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies ];
    request = [[ NSMutableURLRequest alloc ] initWithURL: self.url ];
    [ request setValue: [ cookieHeaders objectForKey: @"Cookie" ]
              forHTTPHeaderField: @"Cookie" ];

    [ self.webView loadRequest: request ];
    [ request release ];
}
嘿哥们儿 2024-11-13 10:03:32

在 Swift 3 中,所有键都包装在 HTTPCookiePropertyKey 结构中:

let cookieProperties: [HTTPCookiePropertyKey : Any] = [.name : "name",
                                                       .value : "value",
                                                       .domain : "www.example.com",
                                                       .originURL : "www.example.com",
                                                       .path : "/",
                                                       .version : "0",
                                                       .expires : Date().addingTimeInterval(2629743)
                                                      ]

if let cookie = HTTPCookie(properties: cookieProperties) {
    HTTPCookieStorage.shared.setCookie(cookie)
}

In Swift 3 all of the keys are wrapped in the HTTPCookiePropertyKey struct:

let cookieProperties: [HTTPCookiePropertyKey : Any] = [.name : "name",
                                                       .value : "value",
                                                       .domain : "www.example.com",
                                                       .originURL : "www.example.com",
                                                       .path : "/",
                                                       .version : "0",
                                                       .expires : Date().addingTimeInterval(2629743)
                                                      ]

if let cookie = HTTPCookie(properties: cookieProperties) {
    HTTPCookieStorage.shared.setCookie(cookie)
}
兮颜 2024-11-13 10:03:32

需要解决 iOS 10 引入的 cookie 限制,这使得它们对不同的进程不可见。

这意味着在具有多处理功能的设备上,Web 视图是一个与应用程序不同的进程,这意味着您的“应用程序”会话不再自动传输到 Web 视图。

所以本质上,你需要这样做(即使之前的海报是正确的,它在 iOS10 之前是自动工作的)。

There is need to work around the limitations on cookies introduced by iOS 10, which makes them invisible to different processes.

This means that on devices with multiprocessing capability, webviews are a distinct process then your app, which means your "app" session is not transmitted automatically to the webview anymore.

So in essense, you will need to do it (even is previous posters where right, it was working automatically before iOS10).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文