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

How to get Unauthenticated identity using Swift

我已经根据 this AWS Developer Guide 初始化了凭据提供程序。我不确定它是否有效,以及如何检查。我似乎找不到任何关于如何将 Cognito 与 Swift 结合使用的文档。我 运行 它作为一个单元测试,测试通过并且行 print("identityId", identityId) 输出:

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: 
            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())
    }

}

getIdentityId returns an AWSTask. Since AWSTask is essentially BFTask with a different name, you can get the identityId using the continueWithBlock syntax shown on the BFTask page。类似于:

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

事实证明,如果您在 application: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 对象。