为什么我在Laravel中使用AWS SDK发出请求时会收到403 Forbidden错误,但在Postman中却可以正常工作?

vql8enpb  于 8个月前  发布在  Postman
关注(0)|答案(1)|浏览(73)

我目前正面临一个问题,试图从我的Laravel应用程序中发送请求到Apigateway URL。我最初使用Postman进行了成功的测试,在那里我提供了必要的access_key和secret_key进行身份验证,数据发送没有任何问题。
然而,当我尝试使用AWS SDK for PHP在Laravel项目中实现相同的功能时,我遇到了403 Forbidden错误。
我在下面沿着了我使用的代码以及我包含的库。有人可以帮助我了解可能导致此问题的原因以及如何解决它吗?

use Aws\Credentials\Credentials;
    use Aws\Signature\SignatureV4;
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request as GuzzelReques;

    $url = env('APIGATEWAY_URL') . "/@connections/" . $request->connectionId;
    $region = env('AWS_DEFAULT_REGION');
    $json = json_encode(["message" => "devolviendo prueba"]);

    $credentials = new Credentials(env('APIGATEWAY_ACCESS_KEY'),env('APIGATEWAY_SECRET_KEY'));

    $client = new Client();`your text`
    $request = new GuzzelReques('POST', $url, [], $json);
    $s4 = new SignatureV4("execute-api", $region);
    $signedrequest = $s4->signRequest($request, $credentials);
    $responseApi = $client->send($signedrequest);

更新

我重新审视了这个问题,发现我在Postman中使用的URL有一个路径段在MySQL中,这与我在环境变量中使用的配置方式不同。我做了必要的调整,现在错误已经改变了。下面,你会发现Laravel生成的跟踪的初始行

GuzzleHttp\Exception\ClientException: Client error: `POST https://api-id-api.us-east-1.amazonaws.com/Test/@connections/LsYfDcZxIAMCEiA=` resulted in a `410 Gone` response in /var/app/current/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

#0 /var/app/current/vendor/guzzlehttp/guzzle/src/Middleware.php(72): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response), NULL, Array, NULL)
x7rlezfr

x7rlezfr1#

经过一番搜索,我成功地找到了一种方法来签署请求并使其工作。为了防止其他人需要它,我将分享我用于此的代码。我还必须使用Credentials类,并发现使用ApiGatewayManagementApiClient类是必不可少的,下面是代码

use Aws\ApiGatewayManagementApi\ApiGatewayManagementApiClient;
use Aws\Credentials\Credentials;

$apiGatewayUrl = env('APIGATEWAY_URL');
$region = env('AWS_DEFAULT_REGION');
$accessKeyId = env('AWS_ACCESS_KEY_ID');
$secretAccessKey = "MRrhp6WGNGacS+17kLNz9Tbz0kaTSEf7VIRpkYHH";
$connectionId = $request->connectionId;

// Credentials configuration
$credentials = new Credentials($accessKeyId, $secretAccessKey);

// Create an ApiGatewayManagementApiClient client
$client = new ApiGatewayManagementApiClient([
   'region' => $region,
   'credentials' => $credentials,
   'endpoint' => $apiGatewayUrl."@connections",
]);

// Request configuration
$requestConfig = [
    'ConnectionId' =>  $connectionId,
    'Data' => json_encode(["message" => "Generacion de prueba request "]),
];

$response = $client->postToConnection($requestConfig);

相关问题