oss存储前端直传向后台请求临时授权(下)
首先去阿里云下载aliyun-php-sdk-core和aliyun-php-sdk-sts包(上个文章给出了阿里链接文档,里面有下载的地址)和
composer require alibabacloud/client与composer require alibabacloud/sdk(记得使用中国镜像)
<?php
namespace App\Http\Controllers\Api\Sts;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Sts\Sts;
use PHPUnit\Framework\TestCase;
class Controller extends TestCase
{
/**
* @expectedException \AlibabaCloud\Client\Exception\ServerException
* @expectedExceptionMessageRegExp /EntityNotExist.Role: The specified Role not exists/
* @throws ClientException
* @throws ServerException
*/
//构建AssumeRole请求
public function stsOss()
{
//构建阿里云client时需要设置AccessKey ID和AccessKey Secret
AlibabaCloud::accessKeyClient('阿里ram用户id', '阿里ram用户key')
->regionId('cn-shanghai')(oss存储地)
->name('default');
$message = Sts::v20150401()
->assumeRole()
//指定角色ARN
->withRoleArn('acs:ram::161364*****:role/*****')(阿里ram用户的arn)(一定要给权限否则访问报错)
//RoleSessionName即临时身份的会话名称,用于区分不同的临时身份
->withRoleSessionName('client_name')
//设置权限策略以进一步限制角色的权限
//以下权限策略表示拥有所有OSS的只读权限
->withPolicy('{
"Statement":[
{
"Action":
[
"oss:Get*",
"oss:List*"
],
"Effect": "Allow",
"Resource": "*"
}
],
"Version": "1"
}')
->connectTimeout(60)
->timeout(65)
->request();
$code = $message->getStatusCode();
if ($code != 200) {
return response()->json('授权失败');
}
return response()->json($message['Credentials']);
}
}
成功返回:
{
"SecurityToken": "CAISlwJ1q6Ft5B2yfSjIr5aCfYOCjrJW55eoTG6Di20yXMlnt43g2zz2IHpEenRpCew**/wznWtT6vsZlqJ4T55IQ1Dza8J148yTTKFxtsyT1fau5Jko1beRewHKeSGZsebWZ+LmNpa/Ht6md1HDkAJq3LL+bk/Mdle5MJqP++MFDtMMRVuXYCYEZrZRPRAwjM4BKTmrQpTLCBPxhXfKB0dFoxd1jXgFiZ6y2cqB8BHT/jaYo603392ve8P6M5cxY8ciCYbsh7FMG/CfgHIK2X9j77xriaFIwzDDs+yGDkNZixf8aLCErIA2fFMgN/BmQvUf8KWnj45xvu3CioLw0A1ROuJYVSvSQo26ydfDAvmuMtsp8jh/q7lWVLoagAEgYUmaOMoZ+IsvuJRLD/tAMvqGau29U7LbrZsg8QG0O9Jm1MGQfVEE99t3LkKIkuJVgM59AQFt2jZSjDiAqqJlHJvB9migvgtAk00u4SfCE2C8eQqPLFyJrstRZVlahZXslaq81loR6Qi0dAHN0gPMi3yofh/I0bvZsq+J7noKeQ==",
"AccessKeyId": "STS.NU7696cmwPUCNH2omg*****",
"AccessKeySecret": "37C5pBQX88EiwgVbTPU1QrQifwRLacq7WGTQfP****",
"Expiration": "2020-08-10T06:33:11Z"
}
这是临时权限token与id和key
祝你今天愉快🤗微笑每一天💕💕💕
时间仓促,如有错误欢迎指出,欢迎在评论区讨论,如对您有帮助还请点个推荐、关注支持一下
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
若内容有侵犯您权益的地方,请公告栏处联系本人,本人定积极配合处理或删除。