混淆了AWS开发者身份验证中登录流的逻辑



我认为我在实现开发人员身份验证身份时有一个不正确的流程,我一直在网上听到并做不同的事情。所以我想我应该展示我的整个流程,听听正确的方法是什么,并在底部提出一些问题和错误。

最初,我有一个带有密码和用户名的用户登录(我只是暂时使用nsuserdefaults,稍后我将使用KeyChain)。

注意:我还有一个回调,它会一直向下查看我是否正确地对用户进行了身份验证。

登录方式:

-(void)loginBusyTimeUser:(void(^)(BOOL))callBack{
//initialize nsuserdefualts should be keychain later
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *post = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                      [defaults objectForKey:@"username"], @"username",
                      [defaults objectForKey:@"password"], @"password",
                      nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:post options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"SOMELOGINURL"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:data
                                                            options:0
                                                              error:&error];
    if(!newJSON || [newJSON objectForKey:@"errorMessage"]){
        NSLog(@"%@",newJSON);
        callBack(false);
        NSLog(@"DID NOT AUTHENTICATE");
    }else{
        NSLog(@"%@",newJSON);
        [defaults setValue:[newJSON objectForKey:@"Token"] forKey:@"Token"];
        [defaults setValue:[newJSON objectForKey:@"IdentityId"] forKey:@"IdentityId"];
        [self authenticateUser:^(BOOL call){
            callBack(call);
        }];
    }
}] resume];

}

如果一切都成功了,我就用开发者身份验证流:用AWS Cognito对我的用户进行身份验证

-(void)authenticateUser:(void(^)(BOOL))callBack{
//Now after making sure that your user's credentials are sound, then initialize the IdentityProvider, in this case
//BusytimeAuthenticated
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
id<AWSCognitoIdentityProvider> identityProvider = [[BusytimeAuthenticated alloc] initWithRegionType:AWSRegionUSEast1
                                                                                         identityId:nil
                                                                                     identityPoolId:@"SOMEPOOLID"
                                                                            logins:@{@"cognito-identity.amazonaws.com": [defaults objectForKey:@"Token"]}
                                                                                       providerName:@"cognito-identity.amazonaws.com"
                                                   ];
credentialsProvider = [[AWSCognitoCredentialsProvider alloc] initWithRegionType:AWSRegionUSEast1
                                                               identityProvider:identityProvider
                                                                  unauthRoleArn:nil
                                                                    authRoleArn:nil];
configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSEast1
                                            credentialsProvider:self.credentialsProvider];
AWSServiceManager.defaultServiceManager.defaultServiceConfiguration = configuration;
[[credentialsProvider refresh] continueWithBlock:^id(AWSTask *task){
    if([task isFaulted]){
        callBack(false);
    }else{
    callBack(true);
    }
    return [defaults objectForKey:@"Token"];
}];

}

然后刷新方法会导致一些错误,所以我会显示我的"BusytimeAuthenticated"类(.m)

//
//  BusytimeAuthenticated.m
//  BusyTime
//
//  Created by akash kakumani on 10/14/15.
//  Copyright (c) 2015 BusyTime. All rights reserved.
//
#import "BusytimeAuthenticated.h"
@interface BusytimeAuthenticated()
@property (strong, atomic) NSString *providerName;
@property (strong, atomic) NSString *token;
@end
@implementation BusytimeAuthenticated
@synthesize providerName=_providerName;
@synthesize token=_token;

- (instancetype)initWithRegionType:(AWSRegionType)regionType
                        identityId:(NSString *)identityId
                    identityPoolId:(NSString *)identityPoolId
                            logins:(NSDictionary *)logins
                      providerName:(NSString *)providerName{
    if (self = [super initWithRegionType:regionType identityId:identityId accountId:nil identityPoolId:identityPoolId logins:logins]) {
        self.providerName = providerName;
    }
    return self;
}
// Return the developer provider name which you choose while setting up the
// identity pool in the Amazon Cognito Console
- (BOOL)authenticatedWithProvider {
    return [self.logins objectForKey:self.providerName] != nil;
}

// If the app has a valid identityId return it, otherwise get a valid
// identityId from your backend.
- (AWSTask *)getIdentityId {
    // already cached the identity id, return it
    if (self.identityId) {
        return [AWSTask taskWithResult:nil];
    }
    // not authenticated with our developer provider
    else if (![self authenticatedWithProvider]) {
        return [super getIdentityId];
    }
    // authenticated with our developer provider, use refresh logic to get id/token pair
    else {
        return [[AWSTask taskWithResult:nil] continueWithBlock:^id(AWSTask *task) {
            if (!self.identityId) {
                return [self refresh];
            }
            return [AWSTask taskWithResult:self.identityId];
        }];
    }
}

// Use the refresh method to communicate with your backend to get an
// identityId and token.
- (AWSTask *)refresh {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![self authenticatedWithProvider]) {
        return [super getIdentityId];
    }else{
        NSDictionary *post = [[NSDictionary alloc] initWithObjectsAndKeys:
                              [defaults objectForKey:@"username"], @"username",
                              [defaults objectForKey:@"password"], @"password",
                              nil];
        NSError *error;
        NSData *postData = [NSJSONSerialization dataWithJSONObject:post options:0 error:&error];
        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:@"SOMELOGINURL"]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:postData];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSDictionary *newJSON = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:0
                                                                      error:&error];
            if(!newJSON){
            NSLog(@"Failure in refresh: %@",newJSON);
            }else{
            NSLog(@"The IdentityID in the refresh method: %@",[newJSON objectForKey:@"IdentityId" ]);
            NSLog(@"The token in the refresh method: %@",[newJSON objectForKey:@"Token" ]);
            self.identityId = [newJSON objectForKey:@"IdentityId" ];
            self.token = [newJSON objectForKey:@"Token" ];
            }
        }] resume];
        return [AWSTask taskWithResult:self.identityId];
    }
    return [AWSTask taskWithResult:self.identityId];
}

@end

我的一些问题:

  1. DeveloperAuthenticationClient是否有必要解决我的问题?我看到了使用它们的示例应用程序,但我发现它们太令人困惑了。

  2. 我应该使用我的ProviderName还是应该使用"cognito identity.amazonaws.com"

  3. 我有时会遇到超时错误,并发现我的登录实现(使用API网关和lambda方法)可能存在一些冷启动问题。我解决这个问题的方法是将超时时间增加到20秒。这是解决这个问题的正确方法吗?

  4. 我在示例应用程序中看到,他们使用GetToken和Login作为两个独立的东西。我想如果我的登录也可以作为我的GetToken会更容易。这合适吗?

  5. 最后,如果时间允许,请解决您在我的代码中看到的任何问题。

错误:

[错误]AWSCredentialsProvider.m行:527|__40-[AWSCognitoCredentialsProvider-refresh]_block_invoke352|无法刷新。错误为[Error域=com.amazonaws.AWS认知凭据提供商错误域代码=1"identityId不应该为零"UserInfo={NSLocalizedDescription=identityId不应为nil}]

(我还发现上面的错误与self.identityId没有设置有关,因为请求在一个块中,其他部分首先执行,解决方案是:

- (AWSTask *)refresh {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![self authenticatedWithProvider]) {
    return [super getIdentityId];
}else{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [defaults objectForKey:@"IdentityId"];
    self.identityId = string;
    return [AWSTask taskWithResult:[defaults objectForKey:@"IdentityId"]];
}
NSString *string = [defaults objectForKey:@"IdentityId"];
return [AWSTask taskWithResult:[defaults objectForKey:@"IdentityId"]];
}

但我认为这不是正确的实施方式。)

我相信我的代码在某个时候可以工作,但在升级到新的SDK后就停止了工作。然而,可能只是我一开始没有注意到这个错误。

问题答案:

  1. 是的,你需要有一些实体(客户端)与你的后端系统通信。

  2. 您在登录映射中使用cognito-identity.amazonaws.com,但使用IdentityProvider模式进行刷新。这就是为什么第一次身份验证成功,但刷新尝试失败的原因。刷新中的逻辑永远不会启动。请查看我们关于如何实现开发人员身份验证的端到端示例。

  3. 据我所知,是的,这是一种方法,但你可能会面临性能问题。请通过他们的论坛联系AWS Lambda以获取更多指导。

  4. 我们强烈建议遵循样本中的流程。如果你已经建立了信任,getToken不需要你的身份验证凭据,而登录总是需要身份验证凭据的,所以最好不要混合使用这些凭据。

谢谢。。

最新更新