阿里云STS token浅析

阿里云STS token浅析

非常想搞明白STS token在端上是如何使用的。因为OSS跟STS联系比较紧密,所以把这两个家伙一起研究了一下。里面有一些环节我现在也没搞太明白,只是记录一下,以后搞明白了再完善。

配置账号及角色

去RAM里面设置好子账号和角色,子账号需要AliyunSTSAssumeRoleAccess权限,角色需要AliyunOSSFullAccess权限。子账号需要有扮演OSS存取这个角色的能力,成功扮演该角色之后,就具有操作OSS资源的能力了。关于用户和角色关系,RAM和STS介绍里面有比较详细的描述。

这里有一个坑是角色一定要选择用户角色。之前错误选择了服务角色,导致AssumeRole一直提示无权限。

screenshot.png

获取STS token

  • 安装好Python SDK。Python测试起来比较方便。
pip install oss2
  • 运行脚本,获取STS token。
#!/usr/bin/env python
#coding=utf-8

from aliyunsdkcore import client
from aliyunsdksts.request.v20150401 import AssumeRoleRequest

clt = client.AcsClient('access key id', 'access key secret', 'cn-shanghai')

# 构造"AssumeRole"请求
request = AssumeRoleRequest.AssumeRoleRequest()

# 指定角色
request.set_RoleArn('acs:ram::1532770894211314:role/henshaoread2')

# 设置会话名称,审计服务使用此名称区分调用者
request.set_RoleSessionName('henshao')

#request.set_method('HMAC-SHA1')

# 发起请求,并得到response
response = clt.do_action_with_exception(request)

实际发出来的请求如下所示。STS API和签名规则可以参考STS文档

/?RoleSessionName=henshao
&Format=json
&Timestamp=2017-04-28T08%3A16%3A06Z
&RoleArn=acs%3Aram%3A%3A1532770894211314%3Arole%2Fhenshaoread2
&RegionId=cn-shanghai
&SignatureVersion=1.0
&AccessKeyId=LTAIAVqsmhvxNjGN
&SignatureMethod=HMAC-SHA1
&Version=2015-04-01
&Signature=9geUPq00G2g1tInX3XSvk77HZhY%3D
&Action=AssumeRole
&SignatureNonce=cc636798-de57-4c11-beb5-567124635220
  • 返回的STS token如下所示,里面包含了AK id、AK secret)和security token。
screenshot.png

另外一种获取STS token的方式是使用aliyuncli工具,也是非常方便的。

$ aliyuncli sts AssumeRole --AccessKeyId xxx --AccessKeySecret xxx --RoleArn xxx --RoleSessionName xxx
{
    "AssumedRoleUser": {
        "AssumedRoleId": "389053493353396514:henshao", 
        "Arn": "acs:ram::1532770894211314:role/henshaoread2/henshao"
    }, 
    "Credentials": {
        "AccessKeySecret": "4s7GoYW7bbFLqe3XGbiMdjveaHEvU1bNBNxdXPtkgLK2", 
        "SecurityToken": "CAIS8gF1q6Ft5B2yfSjIrIXFet3ArJFY1vamUB/3jHcbdLtt16jJ2jz2IHBFfHRrBeEdtfk0n2FW6/8elq5zRpleRUXDNQG7TybIslHPWZHInuDox55m4cTXNAr+Ihr/29CoEIedZdjBe/CrRknZnytou9XTfimjWFrXWv/gy+QQDLItUxK/cCBNCfpPOwJms7V6D3bKMuu3OROY6Qi5TmgQ41cn0zwgsfTunpfFs0GH0GeXkLFF+97DRbG/dNRpMZtFVNO44fd7bKKp0lQLu0kSqfwq3fcfpGyc74/AWgVLhxWLNfHU+9p1IQZ1PLigomnpBFFI/xqAAazzStWsfFdf3btxxYkakt15g06RJeGi/uKqElMfEGIRJ+vjHtLzFqyjtJJV7gLWgkSeinqglonDuRjcfy/oTPcpQ4u3SCcOh1X/e13jVbc1SuaIGnWOCbDFqtxH68+BcTSMl7rZCd/JfDIKIpWmtWBcL1HFkpRTG3Hd04BmB0PY", 
        "Expiration": "2017-11-02T06:01:53Z", 
        "AccessKeyId": "STS.MFp1gtANya4MR9FhwNx4A8mb8"
    }, 
    "RequestId": "14AA9E4A-EEF0-403A-9367-3255E836F382"
}

OSS客户端使用STS token获取文件

拿到STS token,客户端上就可以操作OSS资源了。

id<OSSCredentialProvider> credential = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:@"STS.DSVjYCefVuXKNP9CTyCfy83Uf" secretKeyId:@"7raTtc4LK3ZtHrw8wWse7sbWAJypWdox3cpp5nYwxdDk" securityToken:@"CAIS8gF1q6Ft5B2yfSjIpZDjIeP3iLl3wpqgTHaIp1QsT+lV1/b+hDz2IHBFfHRrBeEdtfk0n2FW6/8elq5zRpleRUXDNSGpOWeEslHPWZHInuDox55m4cTXNAr+Ihr/29CoEIedZdjBe/CrRknZnytou9XTfimjWFrXWv/gy+QQDLItUxK/cCBNCfpPOwJms7V6D3bKMuu3OROY6Qi5TmgQ41cn0zwgsfTunpfFs0GH0GeXkLFF+97DRbG/dNRpMZtFVNO44fd7bKKp0lQLu0kSqfwq3fcfpGyc74/AWgVLhxWLNfHU+9p1IQZ1PLigomnpBFFI/xqAAU0Ia5eMa0XreO/Uh0K6RXJmk9q8dEKrhhMuDEtCK/EUyb+v/8WSfeYez3z2wl9V5Pi7iUSFRciQKHnGyIVAVmBCGWvAZOad83dI8tft8Ks16/mER/wpysTKOcr+rrdn+JnPJDSFDKD5JBJSr0KXR1bbMU+9b0Nrej0P8kVwbhYd"];

OSSClient *client = [[OSSClient alloc] initWithEndpoint:@"oss-cn-shanghai.aliyuncs.com" credentialProvider:credential];

OSSGetObjectRequest * request = [OSSGetObjectRequest new];

request.bucketName = @"wla-test2";
request.objectKey = @"DragonMedium.png";

request.downloadProgress = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
    NSLog(@"%lld, %lld, %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
};

OSSTask * getTask = [client getObject:request];
[getTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"download object success!");
        OSSGetObjectResult * getResult = task.result;
        NSLog(@"download result: %@", getResult.downloadedData);

        UIImage *image = [[UIImage alloc] initWithData: getResult.downloadedData];
        image = nil;
    } else {
        NSLog(@"download object failed, error: %@" ,task.error);
    }
    return nil;
}];

成功获取到DragonMedium.png这张图片。

screenshot.png

稍微分析了一下OSS SDK里面的细节。在header里面有两个重要的字段,Authorization = "OSS " + AK.Id + ":" + sign,x-oss-security-token则是security token。

(lldb) po requestMessage.headerParams
{
    Authorization = "OSS STS.DSVjYCefVuXKNP9CTyCfy83Uf:spZmloXZZJZFBCE8st9fvRxKLag=";
    "User-Agent" = "aliyun-sdk-ios/2.6.0/iOS/10.3/en_US";
    "x-oss-security-token" = "CAIS8gF1q6Ft5B2yfSjIpZDjIeP3iLl3wpqgTHaIp1QsT+lV1/b+hDz2IHBFfHRrBeEdtfk0n2FW6/8elq5zRpleRUXDNSGpOWeEslHPWZHInuDox55m4cTXNAr+Ihr/29CoEIedZdjBe/CrRknZnytou9XTfimjWFrXWv/gy+QQDLItUxK/cCBNCfpPOwJms7V6D3bKMuu3OROY6Qi5TmgQ41cn0zwgsfTunpfFs0GH0GeXkLFF+97DRbG/dNRpMZtFVNO44fd7bKKp0lQLu0kSqfwq3fcfpGyc74/AWgVLhxWLNfHU+9p1IQZ1PLigomnpBFFI/xqAAU0Ia5eMa0XreO/Uh0K6RXJmk9q8dEKrhhMuDEtCK/EUyb+v/8WSfeYez3z2wl9V5Pi7iUSFRciQKHnGyIVAVmBCGWvAZOad83dI8tft8Ks16/mER/wpysTKOcr+rrdn+JnPJDSFDKD5JBJSr0KXR1bbMU+9b0Nrej0P8kVwbhYd";
}

参考资料

  1. OSS访问控制
  2. OSS访问控制-iOS端
  3. OAuth2.0协议原理与实现:TOKEN生成算法
  4. 小米帐户 OAuth 2.0 文档
  5. 百度云访问控制

最后非常感谢 @周卓 大神的鼎力支持😀

Comments are closed, but trackbacks and pingbacks are open.