3

嘿伙计们,我的应用程序登录凭据的身份验证有问题。我目前有一个从我的本地主机运行的 Rails Web 服务,它具有一个主登录屏幕,供管理员用户使用密码凭据来显示功能。

问题是我正在创建一个与我的 rails 应用程序一起运行的 RESTful iOS 应用程序,它只接受这些 JSON 请求并绕过它们。

我想要的只是为我创建一种无需使用 auth_token 即可输入管理员和密码的方法?这似乎是唯一的方法,首先在钥匙串中简单地验证管理员用户。我使用框架 AFNetowrking 进行身份验证。SSKeychain 是帐户的包装器,而 SVProgressHUD 是轻量级的 hud

.我还在 i 终端中记录了 JSON 和 XML 请求,但由于无法连接到服务器并出现此错误而失败

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

登录视图API.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

任何帮助或更多问题,请让我知道干杯:)

4

1 回答 1

1

端点寻址

我不知道如何处理远程地址,但我认为您在致电联系您的网络服务AFNetworking时犯了一个简单的错误。问题是这是一个操作系统,它有自己的. 因此,当您认为您正在调用远程 Web 服务时,您实际上是在要求在自身内部查找该服务。因此,无论您是在本地运行 Rails Web 服务还是在实际的远程服务器上运行,都要找出运行该服务的服务器的 IP 地址,并将其用作端点而不是.localhostiOSiOSlocalhostiOSlocalhost

因此,更新指向您的服务的所有内容以使用 IP。不要将其更改为127.0.0.1,那将具有相同的效果。

例如:

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

验证: iOS

假设你的 web-service 支持,即你已经配置了基本的 http 认证;那么身份验证不iOS应该是一个大问题。

如果您要使用RESTKit,它会很简单:

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

我使用 AppleKeychainItemWrapper在 iOS 上存储/检索凭据。

//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.

我不知道您的代码是否正确,但处理起来应该不会那么复杂basic http auth。也许AFNetworking不像抽象它那样抽象RESTKit?或者也许你没有使用正确的方法AFNetworking来做basic http auth?基本身份验证不需要访问令牌,因此我建议您在实现它之前阅读更多有关基本身份验证的信息。


验证: Rails

至于在 上实现认证Rails,也不应该太复杂。您需要做的就是配置您的控制器以向传入的请求提出身份验证质询basic http auth。一种方法是使用before_filter: authenticate. 这是一个例子

我认为 Railscasts 非常棒,他们碰巧有一个关于基本 http auth的教程和一个专门针对rails 3.1 的教程。身份验证

干杯。

于 2012-12-07T15:56:09.270 回答