Cognito 和 DynamoDB:"not authorized to perform: dynamodb:UpdateItem on resource"

Cognito & DynamoDB: "not authorized to perform: dynamodb:UpdateItem on resource"

完全遵循 "Getting started" guide for Amazon DynamoDB on Android 之后,我最终创建了所有正确的表、角色策略等,并且该代码:

CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
        getApplicationContext(),
        "eu-west-1:01234567-abcd-8901-efab-234567890123", // Identity Pool ID
        Regions.EU_WEST_1 // Region
);

AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
final DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);

final Book book = new Book("My new book"); // Simplified version of Book
new Thread(new Runnable() {
    @Override
    public void run() {
        mapper.save(book);
        Log.v("Sync", "Book saved!");
    }
}).start();

重要说明,与本教程最大(但不明显)的区别是我住在欧洲,所以我所在的地区是 eu-west-1(爱尔兰)。

然而,在正确遵循所有内容后,我收到以下错误:

com.amazonaws.AmazonServiceException: User: arn:aws:sts::012345678901:assumed-role/Cognito_BookUnauth_Role/CognitoIdentityCredentials is not authorized to perform: dynamodb:UpdateItem on resource: arn:aws:dynamodb:us-east-1:012345678901:table/Books (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: AccessDeniedException; Request ID: 05OLSSM8F8EN15SO0JD8VELCNNVV4KQNSO5AEMVJF66Q9ASUAAJG)
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:709)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:385)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:196)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3257)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:965)
    at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper$SaveObjectHandler.doUpdateItem(DynamoDBMapper.java:1173)
    at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.executeLowLevelRequest(DynamoDBMapper.java:873)
    at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper$SaveObjectHandler.execute(DynamoDBMapper.java:1056)
    at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.save(DynamoDBMapper.java:904)
    at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.save(DynamoDBMapper.java:688)
    at com.davidferrand.books.run(MainActivity.java:136)
    at java.lang.Thread.run(Thread.java:818)

这个 "bug" 很棘手,我花了几个小时才解决它。本指南假定您位于 us-east-1 区域,这也是您创建的 AmazonDynamoDBClient 的默认端点。

一旦您的数据库位于不同的区域,您必须在创建 AmazonDynamoDBClient 时明确指定区域。

最好的方法是:

AmazonDynamoDBClient ddbClient = Region.getRegion(Regions.EU_WEST_1) // CRUCIAL
    .createClient(
        AmazonDynamoDBClient.class,
        credentialsProvider,
        new ClientConfiguration()
    );