如何使用Swift获取未经身份验证的身份

时间:2015-11-05 14:33:29

标签: swift amazon-web-services amazon-cognito

我已根据this AWS Developer Guide初始化凭据提供程序。我不确定它是否有效,以及如何检查。我似乎无法找到有关如何使用Cognito与Swift的任何文档。我将它作为单元测试运行,测试通过并且行identityId <AWSTask: 0x17d5fde0; completed = NO; cancelled = NO; faulted = NO;>输出:

identityProvider.identityId

但是,在调试期间,属性// MyAuth.swift import Foundation import AWSCognito class MyAuth { func getUnauthCognitoId()->Bool { let identityProvider = MyIdentityProvider() let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.USEast1, identityProvider: identityProvider, unauthRoleArn: Constants.ARNUnauth.value, authRoleArn: Constants.ARNAuth.value) let defaultServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration if let identityId = identityProvider.getIdentityId() { print("identityId", identityId) return true } else { return false } } } 为零。

以下是我的文件:

//  MyIdentityProvider.swift

import Foundation
import AWSCognito

class MyIdentityProvider: AWSAbstractCognitoIdentityProvider {
    var _token: String!
    var _logins: [ NSObject : AnyObject ]!

    // Header stuff you may not need but I use for auth with my server
    /*let acceptHeader = "application/vnd.exampleapp-api+json;version=1;"
    let authHeader = "Token token="
    let userDefaults = NSUserDefaults.standardUserDefaults()
    let authToken = self.userDefaults.valueForKey("authentication_token") as String*/

    // End point that my server gives amazon identityId and tokens to authorized users
    let url = "https://api.myapp.com/api/amazon_id/"

    func authenticatedWithProvider()->Bool {
        if let logins = _logins {
            return logins["ProviderName"] == nil
        }
        else {
            return false
        }
    }

    override var token: String {
        get {
            return _token
        }
    }

    override var logins: [ NSObject : AnyObject ]! {
        get {
            return _logins
        }
        set {
            _logins = newValue
        }
    }

    override func getIdentityId() -> AWSTask! {
        if self.identityId != nil {
            return AWSTask(result: self.identityId)
        }
        else if(!self.authenticatedWithProvider()) {
            return super.getIdentityId()
        }
        else{
            return AWSTask(result: nil).continueWithBlock({ (task) -> AnyObject! in
                if self.identityId == nil {
                    return self.refresh()
                }
                return AWSTask(result: self.identityId)
            })
        }
    }

    override func refresh() -> AWSTask! {
        let task = AWSTaskCompletionSource()
        if(!self.authenticatedWithProvider()) {
            return super.getIdentityId()
        }
        else {
            // TODO: Authenticate with developer
            return task.task
        }
        /*let request = AFHTTPRequestOperationManager()
        request.requestSerializer.setValue(self.acceptHeader, forHTTPHeaderField: "ACCEPT")
        request.requestSerializer.setValue(self.authHeader+authToken, forHTTPHeaderField: "AUTHORIZATION")
        request.GET(self.url, parameters: nil, success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
            // The following 3 lines are required as referenced here: http://stackoverflow.com/a/26741208/535363
            var tmp = NSMutableDictionary()
            tmp.setObject("temp", forKey: "ExampleApp")
            self.logins = tmp

            // Get the properties from my server response
            let properties: NSDictionary = response.objectForKey("properties") as NSDictionary
            let amazonId = properties.objectForKey("amazon_identity") as String
            let amazonToken = properties.objectForKey("token") as String

            // Set the identityId and token for the ExampleAppIdentityProvider
            self.identityId = amazonId
            self._token = amazonToken

            task.setResult(response)
            }, failure: { (request: AFHTTPRequestOperation!, error: NSError!) -> Void in
                task.setError(error)
        })*/
        return task.task
    }
}

并且

import XCTest
@testable import My

class MyTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock {
            // Put the code you want to measure the time of here.
        }
    }

    func testGetUnauthCognitoId() {
        let myAuth = MyAuth()
        XCTAssertTrue(myAuth.getUnauthCognitoId())
    }

}

String [] sf = new String[]{s.split(",")[0]};

2 个答案:

答案 0 :(得分:0)

getIdentityId返回AWSTask。由于AWSTask基本上BFTask具有不同的名称,因此您可以使用continueWithBlock syntax shown on the BFTask page获取identityId。类似的东西:

credentialProvider.getIdentityId().continueWithBlock {
    (task: AWSTask!) -> AWSTask in
    if task.error() {
        // failed to retrieve identityId.
    } else {
        print("identityId", task.result())
    }

答案 1 :(得分:0)

事实证明,如果您在应用程序中创建默认服务配置:didFinishLaunchingWithOptions:应用程序代理文件as described here中的应用程序委托方法:

let credentialsProvider = AWSCognitoCredentialsProvider(
        regionType: AWSRegionType.USEast1, identityPoolId: cognitoIdentityPoolId)

let defaultServiceConfiguration = AWSServiceConfiguration(
        region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)

AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration

每当您尝试使用任何AWS服务时,SDK都将使用未经身份验证的身份,并且您不一定需要创建cognitoIdentity对象。