身份验证登录问题RESTful iOS

3
嘿,大家好,我在我的应用程序的登录凭据认证方面遇到了问题。我目前在本地主机上运行一个rails网络服务,它具有一个主要的登录屏幕,用于显示函数的管理员用户和密码凭据。
问题是我正在创建一个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

任何帮助或更多问题,请让我知道,谢谢 :)
1个回答

1

端点寻址

我不知道 AFNetworking 如何处理远程地址,但是当你从 iOS 调用 localhost 来联系你的 Web 服务时,你正在犯一个简单的错误。问题在于 iOS 是一种操作系统,它有自己的 localhost。因此,当你认为你在调用远程 web 服务时,实际上你是在要求 iOS 在其内部查找该服务。因此,无论你是在本地运行你的 Rails web 服务还是在实际的远程服务器上运行,找出服务所在的服务器的 IP 地址,并将其用作端点,而不是使用 localhost

所以更新指向你的服务的所有内容,使用 IP 地址。不要改为使用 127.0.0.1,这将产生相同的效果。

例如:

#define BASE_URL @"http://admin:taliesin@192.168.0.1:3000"

认证:iOS

假设您的 Web 服务支持基本的 HTTP 认证,也就是说,您已经配置了基本的 HTTP 认证,那么从 iOS 进行身份验证不应该是一个大问题。

如果您使用 RESTKit,那么它将非常简单:

RKObjectManager *objectManager = [RKObjectManager sharedManager];
objectManager.client.authenticationType = RKRequestAuthenticationTypeHTTPBasic;
objectManager.client.username = username;
objectManager.client.password = password;

我在iOS上使用苹果的KeychainItemWrapper来存储/检索凭据。

//Store Account on Keychain (disk) for persistence.
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
KeychainItemWrapper *accountItem = appDelegate.accountItem;
[accountItem setObject:password forKey:(__bridge id)kSecValueData];
[accountItem setObject:username forKey:(__bridge id)kSecAttrAccount];   
username = password = nil; //keep account information only in the keychain.

我不知道你的代码是否正确,但处理基本的HTTP身份验证不应该那么复杂。也许AFNetworking没有像RESTKit那样将其抽象化?或者你没有使用来自AFNetworking的正确方法来进行基本的HTTP身份验证?基本身份验证不需要访问令牌,因此我建议在实现之前多了解一些基本身份验证的知识。


认证:Rails

关于在Rails上实现认证,这也不应该太复杂。你需要做的就是配置控制器,使用basic http auth向传入请求提供认证挑战。一种方法是使用before_filter: authenticate。这里有一个示例

我认为Railscasts非常棒,他们恰好有一个关于basic http auth和一个专门针对rails 3.1. authentication的教程。

干杯。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接