问题是我正在创建一个RESTful iOS应用程序,与我的rails应用程序一起运行,它只接受这些JSON请求并绕过它们。
我想做的就是创建一种方法,让我输入管理员和密码而无需使用auth_token?看来这似乎是唯一的方法,先在钥匙串中验证管理员用户。我正在使用AFNetworking框架进行身份验证,SSKeychain作为帐户的包装器,以及SVProgressHUD用于轻量级huds。
我还将JSON和XML请求记录在i终端中,但由于无法连接到服务器而失败,出现以下错误:
error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo=0x7556d50 {NSErrorFailingURLStringKey=http://localhost:3000.json/, NSErrorFailingURLKey=http://localhost:3000.json/, NSLocalizedDescription=Could not connect to the server., NSUnderlyingError=0xeb805c0 "Could not connect to the server."}
这是我存储authClient凭据的方式,我想做的就是指定与登录Web服务客户端使用的相同信息。用户名为admin,密码为taliesin,但不确定如何操作?
这是我为AuthAPIClient、CredentialsStore和LoginViewController编写的代码。
更新:如果有人知道更简单的方法,请告诉我,非常感谢。
AuthAPIClient.m
#import "AuthAPIClient.h"
#import "CredentialStore.h"
#define BASE_URL @"http://admin:taliesin@localhost:3000"
@implementation AuthAPIClient
+ (id)sharedClient {
static AuthAPIClient *__instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURL *baseUrl = [NSURL URLWithString:BASE_URL];
__instance = [[AuthAPIClient alloc] initWithBaseURL:baseUrl];
});
return __instance;
}
- (id)initWithBaseURL:(NSURL *)url {
self = [super initWithBaseURL:url];
if (self) {
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setAuthTokenHeader];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tokenChanged:)
name:@"token-changed"
object:nil];
}
return self;
}
- (void)setAuthTokenHeader {
CredentialStore *store = [[CredentialStore alloc] init];
NSString *authToken = [store authToken];
[self setDefaultHeader:@"auth_token" value:authToken];
}
- (void)tokenChanged:(NSNotification *)notification {
[self setAuthTokenHeader];
}
@end
CredentialStore.m
#import "CredentialStore.h"
#import "SSKeychain.h"
#define SERVICE_NAME @"http://admin:taliesin@localhost:3000"
#define AUTH_TOKEN_KEY @"auth_token"
@implementation CredentialStore
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSString *user = [NSString stringWithFormat:@"%c%s%@", 'a', "a", @"a"];
NSString *password = [NSString stringWithFormat:@"%c%s%@", 'a', "a", @"a"];
NSURLCredential *credential = [NSURLCredential credentialWithUser:user
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
- (BOOL)isLoggedIn {
return [self authToken] != nil;
}
- (void)clearSavedCredentials {
[self setAuthToken:nil];
}
- (NSString *)authToken {
return [self secureValueForKey:AUTH_TOKEN_KEY];
}
- (void)setAuthToken:(NSString *)authToken {
[self setSecureValue:authToken forKey:AUTH_TOKEN_KEY];
[[NSNotificationCenter defaultCenter] postNotificationName:@"token-changed" object:self];
}
- (void)setSecureValue:(NSString *)value forKey:(NSString *)key {
if (value) {
[SSKeychain setPassword:@"taliesin"
forService:SERVICE_NAME
account:key];
} else {
[SSKeychain deletePasswordForService:SERVICE_NAME account:key];
}
}
- (NSString *)secureValueForKey:(NSString *)key {
return [SSKeychain passwordForService:SERVICE_NAME account:key];
}
@end
LoginViewApi.m
#import "LoginViewController.h"
#import "AuthAPIClient.h"
#import "CredentialStore.h"
#import "SVProgressHUD.h"
@interface UIViewController ()
@property (nonatomic, strong) IBOutlet UITextField *userTextField;
@property (nonatomic, strong) IBOutlet UITextField *passwordTextField;
@property (nonatomic, strong) CredentialStore *credentialStore;
@end
@implementation LoginViewController
+ (void)presentModallyFromViewController:(UIViewController *)viewController {
LoginViewController *loginViewController = [[LoginViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:loginViewController];
[viewController presentViewController:navController
animated:YES
completion:nil];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.credentialStore = [[CredentialStore alloc] init];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self
action:@selector(cancel:)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Login"
style:UIBarButtonItemStyleDone
target:self
action:@selector(login:)];
[self.userTextField becomeFirstResponder];
}
- (void)login:(id)sender {
[SVProgressHUD show];
id params = @{
@"admin": self.userTextField.text,
@"taliesin": self.passwordTextField.text
};
[[AuthAPIClient sharedClient] postPath:@"/auth/login.json"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *authToken = [responseObject objectForKey:@"auth_token"];
[self.credentialStore setAuthToken:authToken];
[SVProgressHUD dismiss];
[self dismissViewControllerAnimated:YES completion:nil];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (operation.response.statusCode == 500) {
[SVProgressHUD showErrorWithStatus:@"Something went wrong!"];
} else {
NSData *jsonData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:nil];
NSString *errorMessage = [json objectForKey:@"error"];
[SVProgressHUD showErrorWithStatus:errorMessage];
}
}];
}
- (void)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
任何帮助或更多问题,请让我知道,谢谢 :)