OssController.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Http\Controllers;
  3. use AliCloud\Core\Profile\DefaultProfile;
  4. use AliCloud\Core\DefaultAcsClient;
  5. use AliCloud\Core\Exception\ServerException;
  6. use AliCloud\Core\Exception\ClientException;
  7. use AliCloud\STS\AssumeRoleRequest;
  8. class OssController extends Controller
  9. {
  10. public function getSts()
  11. {
  12. $regionID = "cn-zhangjiakou";
  13. $endpoint = "sts.cn-zhangjiakou.aliyuncs.com";
  14. DefaultProfile::addEndpoint($regionID, $regionID, "Sts", $endpoint);
  15. $iClientProfile = DefaultProfile::getProfile($regionID, 'LTAIG3B3vMgxdnGg', 'EJY6vwMje1npqZYmIwrmUWlVTiVW18');
  16. $client = new DefaultAcsClient($iClientProfile);
  17. // 指定角色ARN
  18. $roleArn = "acs:ram::1211062998797452:role/ramoss-sts";
  19. // 在扮演角色时,添加一个权限策略,进一步限制角色的权限
  20. // 以下权限策略表示拥有可以读取所有OSS的只读权限
  21. $policy = <<<POLICY
  22. {
  23. "Statement": [
  24. {
  25. "Action": [
  26. "oss:Get*",
  27. "oss:List*",
  28. "oss:Put*"
  29. ],
  30. "Effect": "Allow",
  31. "Resource": "*"
  32. }
  33. ],
  34. "Version": "1"
  35. }
  36. POLICY;
  37. $request = new AssumeRoleRequest();
  38. // RoleSessionName即临时身份的会话名称,用于区分不同的临时身份
  39. $request->setRoleSessionName("alice");
  40. $request->setRoleArn($roleArn);
  41. $request->setPolicy($policy);
  42. $request->setDurationSeconds(3600);
  43. try {
  44. $response = $client->getAcsResponse($request);
  45. $result['region'] = $regionID;
  46. $result['accessKeyId'] = $response->Credentials->AccessKeyId;
  47. $result['accessKeySecret'] = $response->Credentials->AccessKeySecret;
  48. $result['stsToken'] = $response->Credentials->SecurityToken;
  49. $result['bucket'] = 'uptoyo';
  50. return $this->jsonSuccess($result);
  51. } catch (ServerException $e) {
  52. return jsonError($e->getMessage());
  53. } catch (ClientException $e) {
  54. return jsonError($e->getMessage());
  55. }
  56. }
  57. }