以thinkphp5为例
一、OOS介绍
对象存储OSS_云存储服务_企业数据管理_存储-阿里云 (aliyun.com)看官网介绍吧
二、前期准备需要
-
登录自己的阿里云平台,打开RAM访问控制平台,创建用户并赋予“调用STS服务AssumeRole接口的权限” 这个权限。
-
创建一个自定义的OOS数据库的权限策略
- 这个是配置对于 某些资源 的 某些权限 的 许可配置(不会写的可以直接用官方的权限集)
{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "oss:PutObject" ], "Resource": [ "acs:oss:*:*:examplebucket/exampledir", "acs:oss:*:*:examplebucket/exampledir/*" ] } ] }
-
创建RAM角色并赋予刚才设置的 自定义的权限策略
三、需要配置信息
-
引入sts-server包
快速搭建移动应用直传服务 - 对象存储 OSS - 阿里云 (aliyun.com)点击后,在步骤2处下载对应的php包。
-
配置文件位置,以下配置,均换成自己的。accessKeySecret和accessKeyId在创建RAM用户时生成,注意保存,是一次性文件,rolearn在创建RAM角色时有。
<?php return [ 'oss_sts_accessKeySecret' => '你的', 'oss_sts_accessKeyId' => '你的', 'oss_sts_roleArn' => '创建的', ];
四、样例
<?php
namespace app\service;
class StsService
{
protected $url = 'https://sts.aliyuncs.com';
protected $accessKeySecret;
protected $accessKeyId;
protected $roleArn;//指定角色的 ARN ,角色策略权限
protected $roleSessionName = 'client';//用户自定义参数。此参数用来区分不同的 token,可用于用户级别的访问审计。格式:^[a-zA-Z0-9\.@\-_]+$
protected $durationSeconds = '900';//指定的过期时间
public function __construct()
{
$this->accessKeySecret = config('aliyun.oss_sts_accessKeySecret');
$this->accessKeyId = config('aliyun.oss_sts_accessKeyId');
$this->roleArn = config('aliyun.oss_sts_roleArn');
}
public function setOptions($options = []) {
if (array_key_exists('accessKeySecret', $options)) {
$this->accessKeySecret = $options['accessKeySecret'];
}
if (array_key_exists('accessKeyId', $options)) {
$this->accessKeyId = $options['accessKeyId'];
}
if (array_key_exists('roleArn', $options)) {
$this->roleArn = $options['roleArn'];
}
if (array_key_exists('roleSessionName', $options)) {
$this->roleSessionName = $options['roleSessionName'];
}
if (array_key_exists('durationSeconds', $options)) {
$this->durationSeconds = $options['durationSeconds'];
}
return $this;
}
public function getStsOuah()
{
require_once VENDOR_PATH .'sts-server/aliyun-php-sdk-core/Config.php';
$iClientProfile = \DefaultProfile::getProfile("cn-hangzhou", $this->accessKeyId, $this->accessKeySecret);
$client = new \DefaultAcsClient($iClientProfile);
$request = new \Sts\Request\V20150401\AssumeRoleRequest();
$request->setRoleSessionName($this->roleSessionName);
$request->setRoleArn($this->roleArn);
// $request->setPolicy(VENDOR_PATH.'aliyuncs/sts-server/policy/bucket_write_policy.txt');
$request->setDurationSeconds($this->durationSeconds);
$response = $client->doAction($request);
$rows = array();
$body = $response->getBody();
$content = json_decode($body);
if ($response->getStatus() == 200){
$rows['statusCode'] = 200;
$rows['accessKeyId'] = $content->Credentials->AccessKeyId;
$rows['accessKeySecret'] = $content->Credentials->AccessKeySecret;
$rows['expiration'] = $content->Credentials->Expiration;
$rows['securityToken'] = $content->Credentials->SecurityToken;
}else{
$rows['statusCode'] = 500;
$rows['errorCode'] = $content->Code;
$rows['errorMessage'] = $content->Message;
}
return $rows;
}
}
运行之后就会返回结果,正常获取权限的话,状态码为200,异常时状态码为500