问题
I am creating an android application which connects to AWS IoT using Amazon Cognito authentication. I am able to authenticate user successfully and I am able get the credentials. While updating the thing shadow using these credentials always return 403 Forbidden Exception. I have tried all my ways to troubleshoot the issue but I found no solutions.
My IAM Policy is:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:GetThingShadow",
"iot:UpdateThingShadow",
],
"Resource": [
"arn:aws:iot:us-west-2:<my_account>:thing/mythingname"
]
}
]
}
Android code for connecting endpoint:
userSession= AppHelper.getCurrSession();
credentialsProvider=new CognitoCachingCredentialsProvider(getApplicationContext(),POOL_ID,REGIONS);
Map<String,String> logins=new HashMap<String, String>();
logins.put("cognito-idp.us-west-2.amazonaws.com/user_pool_id",userSession.getIdToken().getJWTToken());
credentialsProvider.setLogins(logins);
iotDataClient=new AWSIotDataClient(credentialsProvider);
iotDataClient.setEndpoint(ENDPOINT);
Updating thing shadow:
UpdateThingShadowRequest request=new UpdateThingShadowRequest();
request.setThingName(thingName);
ByteBuffer payloadBuffer=ByteBuffer.wrap(updateState.getBytes());
request.setPayload(payloadBuffer);
UpdateThingShadowResult result=iotDataClient.updateThingShadow(request);
Any help with this regard would be appreciated.
回答1:
I had the same issue as you. I've found a solution.
That 403 status code mean that you need authorization.
If you read this documentation (near the end) : Publish/Subscribe Policy Exemple it's stated that you need 2 policies to make it work with Authenticated Cognito User. One for the Cognito Identity Pool and another for the Cognito User.
It's not possible to attach a policy to a cognito user with the UI, but you can do it through the CLI.
The command to attach a policy to a cognito user is :
aws iot attach-principal-policy --principal "cognito user id" --policy-Name "policy name"
You can find your cognito user id in :
Cognito > Manager Federated Identities > choose your identity pool > identity browser > and find your identity ID
I use this policy for testing purpose.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"iot:*"
],
"Resource": [
"*"
]
}
]
}
To make it reusable, you need to use a lambda function (here in JavaScript).
var AWS = require('aws-sdk');
var iot = new AWS.Iot();
exports.handler = function(event, context, cb) {
var params = {
policyName: 'your policy',
principal: 'your cognito id'
};
var out = iot.attachPrincipalPolicy(params, function(err, data) {
if (err) cb(err);
else cb(null, data);
});
};
回答2:
I am able to identify the issue. In my case, I was missing to set region
for AWS iot
client.
Region region = Region.getRegion(MY_REGION);
mIotAndroidClient.setRegion(region); // I was missing this piece of code
来源:https://stackoverflow.com/questions/40104559/forbidden-exception-on-accessing-aws-iot-using-amazon-cognito