2011-12-19 67 views
15

我正在使用AFNetworking作为我的iPhone应用程序的网络层,它连接到使用Devise进行身份验证的Rails服务器。如果我登录(通过POST调用)提供用户名/密码,那么在此之后,我执行的任何GET都可以。AFNetworking和Cookies

如果我关闭了应用程序(不仅仅是背景),那么我的所有GET请求都会失败,因为我猜他们没有通过身份验证。

所以我认为cookie存储在某个地方;有没有办法将它们保存在NSUserDefaults或类似的地方,以避免所有时间登录?

回答

9

Cookie确实会自动存储在应用程序的整个生命周期中,以便在特定服务器上执行任何后续请求。一个好的策略是将存储这样在钥匙串的用户名和密码,或在NSUserDefaults

// Setting 
[[NSUserDefaults standardDefaults] setObject:username forKey:@"username"]; 
[[NSUserDefaults standardDefaults] synchronize]; 

// Getting 
NSString *username = [[NSUserDefaults standardDefaults] objectForKey:@"username"]; 

您可能希望在组合中的Authorization HTTP标头时使用该AFHTTPClient与每个请求一起发送您的凭据。

+1

感谢回答,是的,这是我做的,让旧凭证。 我想避免的是在每次应用程序重新启动时登录的初始POST,我只是想知道是否可以扩展AFNetworking处理的cookie的生命周期。 – 2011-12-28 20:02:02

+26

其实,请不要在NSUserDefaults中存储用户名和密码。改用钥匙串。 Apple发布了一款KeychainWrapper,它的功能基本相同,但安全性更高。 – eddieroger 2012-08-12 04:15:38

75

如果您使用NSURLCredential,则无需担心NSUserDefaults或任何钥匙串包装。 确实NSURLCredential使用起来更简单,因为它允许您在两行代码中将用户名和密码存储在钥匙串中。

您的代码会是这样的,一旦用户登录:

NSURLCredential *credential; 

credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistencePermanent]; 
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:self.loginProtectionSpace]; 

然后,每个应用程序被启动时,您可以检查用户是否已经登录通过搜索任何凭据以自动重新登录您的用户(如果需要的话):

NSURLCredential *credential; 
NSDictionary *credentials; 

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace]; 
credential = [credentials.objectEnumerator nextObject]; 
NSLog(@"User %@ already connected with password %@", credential.user, credential.password); 

您还需要当用户想注销清理凭据:

NSURLCredential *credential; 
NSDictionary *credentials; 

credentials = [[NSURLCredentialStorage sharedCredentialStorage] credentialsForProtectionSpace:self.loginProtectionSpace]; 
credential = [credentials.objectEnumerator nextObject]; 
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:self.loginProtectionSpace]; 

loginProtectionSpace创建一次。请注意,此示例代码假定此空间中只有一个凭证,除非您管理多个账户,通常情况下是这样。

这里是你将如何创建一个NSURLProtectionSpace一个例子:

NSURL *url = [NSURL URLWithString:@"http://www.example.com"]; 
self.loginProtectionSpace = [[NSURLProtectionSpace alloc] initWithHost:url.host 
                    port:[url.port integerValue] 
                   protocol:url.scheme 
                   realm:nil 
                authenticationMethod:NSURLAuthenticationMethodHTTPDigest]; 
+0

创建NSURLProtectionSpace的代码在哪里?我看了一下Apple的文档,但是我不清楚如何创建一个。我指的是“self.loginProtectionSpace” – user798719 2013-09-01 04:08:10

+0

我想我的意思是,做端口和主机名的问题还是这些命名空间? – user798719 2013-09-01 04:36:41

+4

我已经用如何创建NSURLProtectionSpace的示例更新了我的答案。请替换您拥有的URL,并使用服务器使用的身份验证方法更新身份验证方法参数。 – Phil 2013-09-02 09:06:43