How can I resolve the error "The security token included in the request is invalid" when running bedrock from aws php sdk

322 Views Asked by At

I am encountering an issue while utilizing the AWS PHP SDK to invoke the Bedrock service using AWS access key and secret key provided by my organization(the account managed by the organization). The keys are associated with an IAM role that has full access permissions to various AWS services, including Bedrock, SageMaker, OpenSearch, and Kendra. Despite having the necessary permissions, I am facing an error specifically when calling the InvokeModel function.

The error message is as follows:

Error: Error executing "InvokeModel" on "https://bedrock-runtime.us-east-1.amazonaws.com/model/ai21.j2-mid-v1/invoke"; AWS HTTP error: Client error: POST https://bedrock-runtime.us-east-1.amazonaws.com/model/ai21.j2-mid-v1/invoke resulted in a 403 Forbidden response: {"message":"The security token included in the request is invalid."} UnrecognizedClientException (client): The security token included in the request is invalid. - {"message":"The security token included in the request is invalid."}

It's worth noting that when I use my personal AWS account's access key and secret with full AdministratorAccess permissions, the code works without any issues, and I can successfully invoke the model.

 `<?php
 require   './vendor/autoload.php';

 use Aws\Exception\AwsException;
 use Aws\BedrockRuntime\BedrockRuntimeClient;

 $client = new BedrockRuntimeClient([
'region' => 'us-east-1',
'version' => 'latest',
// 'credentials' => [
//     'key' => 'keydemo',
//     'secret' => 'secretdemo',
// ],
]);

$prompt = 'Once upon a time, there was a princess who lived in a castle.';

try {
$request = [
    'modelId' => 'ai21.j2-mid-v1',
    'body' => json_encode([
        'prompt' => $prompt,
        'maxTokens' => 200,
        'temperature' => 0.5,
    ]),
];

$response = $client->invokeModel($request);

$completion = json_decode($response["body"],true);
echo "<pre>";

echo $completion["completions"][0]["data"]["text"];

} catch (AwsException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>`

I have also tried setting the cred through aws configure delete the previous configure and credential file and also checked the credential file if there is any field for session token.

1

There are 1 best solutions below

0
On

Looks like your organisation gives you temporary credentials. And you'll need to find the aws_session_token (which is valid for n minutes only) and put that to your credentials file.

Example:

[default] 
aws_access_key_id = AKIAIOSFODNN7EXAMPLE 
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
aws_session_token = IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZ2luX2IQoJb3JpZVERYLONGSTRINGEXAMPLE

Reference: https://docs.aws.amazon.com/cli/latest/userguide/cli-authentication-short-term.html