首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Appsync在连接认知时返回401错误

Appsync在连接认知时返回401错误
EN

Stack Overflow用户
提问于 2018-02-28 01:30:03
回答 3查看 6.5K关注 0票数 3

因此,我已经建立了认知和应用同步,并将它们连接到我的iOS客户端。Appsync在控制台上工作得很好,但是当我从iOS发出任何请求时,我会得到一个401错误,没有任何错误消息。我可以登记出入白兰地很好。我想我可能是把错误的东西传递给什么东西了?

下面是我的应用程序委托代码:导入UIKit导入AWSAppSync导入AWSS3导入AWSCognitoIdentityProvider

代码语言:javascript
运行
复制
var credentialsProvider: AWSCognitoCredentialsProvider?
var pool: AWSCognitoIdentityUserPool?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var storyboard: UIStoryboard? {
        return UIStoryboard(name: "Main", bundle: nil)
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        AWSDDLog.sharedInstance.logLevel = .verbose
        AWSDDLog.add(AWSDDTTYLogger.sharedInstance)
        let configuration = AWSServiceConfiguration(region: AWSRegion, credentialsProvider: nil)

        let poolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: CognitoAppId, clientSecret: nil, poolId: CognitoPoolId)

        AWSCognitoIdentityUserPool.register(with: configuration, userPoolConfiguration: poolConfiguration, forKey: CognitoIdentityPoolId)

        pool = AWSCognitoIdentityUserPool(forKey: CognitoIdentityPoolId)

        NSLog("cognito pool username: \(pool?.currentUser()?.username ?? "unknown")")
        pool!.delegate = self

        credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegion, identityPoolId: CognitoIdentityPoolId, identityProviderManager: pool!)

        let databaseURL = URL(fileURLWithPath:NSTemporaryDirectory()).appendingPathComponent(database_name)

        do {
            // Initialize the AWS AppSync configuration
            let appSyncConfig = try AWSAppSyncClientConfiguration(url: AppSyncEndpointURL, serviceRegion: AWSRegion,
                                                                  credentialsProvider: credentialsProvider!,
                                                                  databaseURL:databaseURL)

            // Initialize the AppSync client
            appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncConfig)

            // Set id as the cache key for objects
            appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }
        }
        catch {
            NSLog("Error initializing appsync client. \(error)")
        }

        return true
    }

}

extension AppDelegate: AWSCognitoIdentityInteractiveAuthenticationDelegate {

    func startPasswordAuthentication() -> AWSCognitoIdentityPasswordAuthentication {
        let tabController = self.window?.rootViewController as! UITabBarController


        let loginViewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController


        DispatchQueue.main.async {
            tabController.present(loginViewController, animated: true, completion: nil)
        }

        return loginViewController
    }
}

以下是我所犯的错误:

代码语言:javascript
运行
复制
Error body: {
  "errors" : [ {
    "message" : "Unable to parse JWT token."
  } ]
})
errorDescription: (401 unauthorized) Did not receive a successful HTTP code.

iam政策:

代码语言:javascript
运行
复制
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "appsync:GraphQL",
            "Resource": "*"
        }
    ]
}

IAM TRust关系:

代码语言:javascript
运行
复制
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "us-west-2:94OBSCURED"
        }
      }
    }
  ]
}

如果你需要更多细节请告诉我。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-03-19 03:55:37

问题是:如果使用上述代码,则需要设置appsync以通过IAM (而不是认知)进行身份验证。这还需要对解析器进行更改,因为传递给identity对象的参数对于IAM和认知是不同的。

这是令人困惑的,因为您使用的是认知(用户池和联邦身份用户池),但不要选择认知。

票数 2
EN

Stack Overflow用户

发布于 2018-04-27 22:56:33

AppSync的初始化很棘手。所有AWS文档/示例都提供了IAM或API密钥作为身份验证的示例。如果您在AppSync中将认知用户池设置为身份验证,那么有两件事需要考虑。

1)为类创建一个扩展,如下所示。

代码语言:javascript
运行
复制
extension YourClassName: AWSCognitoUserPoolsAuthProvider {
  func getLatestAuthToken() -> String {
   let pool = AWSCognitoIdentityUserPool(forKey: APP_TITLE)
   let session =  pool.currentUser()?.getSession()
   return (session?.result?.idToken?.tokenString)!
  }
}

2)初始化credentialsProvider时不要使用AppSync。相反,使用userPoolsAuthProvider.userPoolsAuthProvider的值是在步骤1中创建的类,如果它是一个单独的类,那么在相同的类或类名的情况下,这个值可以是self。

代码语言:javascript
运行
复制
let appSyncConfig = try AWSAppSyncClientConfiguration.init(url: AppSyncEndpointURL, serviceRegion: AppSyncRegion, userPoolsAuthProvider:self, databaseURL:databaseURL)

CognitoUserPools需要JWT令牌,而IAM需要IdentityPoolProvider。传递credentialsProvider意味着告诉AppSync使用IAM作为auth。

票数 3
EN

Stack Overflow用户

发布于 2018-09-21 17:21:11

在本文中,向下滚动并查看题为“身份验证模式”的部分。这为iOS项目在使用AppSync时的api授权提供了很好的参考。我觉得这很有帮助。

https://awslabs.github.io/aws-mobile-appsync-sdk-ios/#configuration

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49020612

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档