文档首页/ 对象存储服务 OBS/ SDK参考/ .NET/ 临时授权访问/ 使用临时URL进行授权访问
更新时间:2024-06-24 GMT+08:00
分享

使用临时URL进行授权访问

开发过程中,您有任何问题可以在github上提交issue,或者在华为云对象存储服务论坛中发帖求助。接口参考文档详细介绍了每个接口的参数和使用方法。

OBS客户端支持通过访问密钥、请求方法类型、请求参数等信息生成一个在Query参数中携带鉴权信息的URL,可将该URL提供给其他用户进行临时访问。在生成URL时,您需要指定URL的有效期来限制访客用户的访问时长。

如果您想授予其他用户对桶或对象临时进行其他操作的权限(例如上传或下载对象),则需要生成带对应请求的URL后(例如使用生成PUT请求的URL上传对象),将该URL提供给其他用户。

通过该方式可支持的操作以及相关信息见下表:

操作名

HTTP请求方法(OBS .NET SDK对应值)

子资源(OBS .NET SDK对应值)

是否需要桶名

是否需要对象名

创建桶

HttpVerb.PUT

N/A

获取桶列表

HttpVerb.GET

N/A

删除桶

HttpVerb.DELETE

N/A

列举桶内对象

HttpVerb.GET

N/A

列举桶内多版本对象

HttpVerb.GET

SubResourceEnum.Versions

列举分段上传任务

HttpVerb.GET

SubResourceEnum.Uploads

获取桶元数据

HttpVerb.HEAD

N/A

获取桶区域位置

HttpVerb.GET

SubResourceEnum.Location

获取桶存量信息

HttpVerb.GET

SubResourceEnum.StorageInfo

设置桶配额

HttpVerb.PUT

SubResourceEnum.Quota

获取桶配额

HttpVerb.GET

SubResourceEnum.Quota

设置桶存储类型

HttpVerb.PUT

SubResourceEnum.StoragePolicy

获取桶存储类型

HttpVerb.GET

SubResourceEnum.StoragePolicy

设置桶访问权限

HttpVerb.PUT

SubResourceEnum.Acl

获取桶访问权限

HttpVerb.GET

SubResourceEnum.Acl

开启/关闭桶日志

HttpVerb.PUT

SubResourceEnum.Logging

查看桶日志

HttpVerb.GET

SubResourceEnum.Logging

设置桶策略

HttpVerb.PUT

SubResourceEnum.Policy

查看桶策略

HttpVerb.GET

SubResourceEnum.Policy

删除桶策略

HttpVerb.DELETE

SubResourceEnum.Policy

设置生命周期规则

HttpVerb.PUT

SubResourceEnum.Lifecycle

查看生命周期规则

HttpVerb.GET

SubResourceEnum.Lifecycle

删除生命周期规则

HttpVerb.DELETE

SubResourceEnum.Lifecycle

设置托管配置

HttpVerb.PUT

SubResourceEnum.Website

查看托管配置

HttpVerb.GET

SubResourceEnum.Website

清除托管配置

HttpVerb.DELETE

SubResourceEnum.Website

设置桶多版本状态

HttpVerb.PUT

SubResourceEnum.Versioning

查看桶多版本状态

HttpVerb.GET

SubResourceEnum.Versioning

设置跨域规则

HttpVerb.PUT

SubResourceEnum.Cors

查看跨域规则

HttpVerb.GET

SubResourceEnum.Cors

删除跨域规则

HttpVerb.DELETE

SubResourceEnum.Cors

设置桶标签

HttpVerb.PUT

SubResourceEnum.Tagging

查看桶标签

HttpVerb.GET

SubResourceEnum.Tagging

删除桶标签

HttpVerb.DELETE

SubResourceEnum.Tagging

上传对象

HttpVerb.PUT

N/A

追加上传

HttpVerb.POST

SubResourceEnum.Append

下载对象

HttpVerb.GET

N/A

复制对象

HttpVerb.PUT

N/A

删除对象

HttpVerb.DELETE

N/A

批量删除对象

HttpVerb.POST

SubResourceEnum.Delete

获取对象属性

HttpVerb.HEAD

N/A

设置对象访问权限

HttpVerb.PUT

SubResourceEnum.Acl

查看对象访问权限

HttpVerb.GET

SubResourceEnum.Acl

初始化分段上传任务

HttpVerb.POST

SubResourceEnum.Uploads

上传段

HttpVerb.PUT

N/A

复制段

HttpVerb.PUT

N/A

列举已上传的段

HttpVerb.GET

N/A

合并段

HttpVerb.POST

N/A

取消分段上传任务

HttpVerb.DELETE

N/A

恢复归档存储对象

HttpVerb.POST

SubResourceEnum.Restore

通过OBS .NET SDK生成临时URL访问OBS的步骤如下:

  1. 通过ObsClient.CreateTemporarySignature生成带签名信息的URL。
  2. 使用任意HTTP库发送HTTP/HTTPS请求,访问OBS服务。

如果遇到跨域报错、签名不匹配问题,请参考以下步骤排查问题:

  1. 未配置跨域,需要在控制台配置CORS规则,请参考配置桶允许跨域请求
  2. 签名计算问题,请参考URL中携带签名排查签名参数是否正确;比如上传对象功能,后端将Content-Type参与计算签名生成授权URL,但是前端使用授权URL时没有设置Content-Type字段或者传入错误的值,此时会出现跨域错误。解决方案为:Content-Type字段前后端保持一致。

以下代码展示了如何使用临时URL进行授权访问,包括:创建桶、上传对象、下载对象、列举对象、删除对象。

创建桶

// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.Method = HttpVerb.PUT;
request.Expires = exipreSeconds;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Creating bucket using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用PUT请求创建桶
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "PUT";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}

string location = "your bucket location";
            
webRequest.SendChunked = true;
webRequest.AllowWriteStreamBuffering = false;
using (Stream requestStream = webRequest.GetRequestStream())
{
    byte[] buffer = Encoding.UTF8.GetBytes("<CreateBucketConfiguration><LocationConstraint>" + location + "</LocationConstraint></CreateBucketConfiguration>");
    requestStream.Write(buffer, 0, buffer.Length);
}

HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

上传对象

// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.ObjectKey = "objectkey";         
request.Method = HttpVerb.PUT;
request.Expires = exipreSeconds;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Creating object using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用PUT请求上传对象
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "PUT";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}
            
webRequest.SendChunked = true;
webRequest.AllowWriteStreamBuffering = false;
using (Stream requestStream = webRequest.GetRequestStream())
{
    byte[] buffer = Encoding.UTF8.GetBytes("Hello OBS");
    requestStream.Write(buffer, 0, buffer.Length);
}

HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

下载对象

// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.ObjectKey = "objectkey";         
request.Method = HttpVerb.GET;
request.Expires = exipreSeconds;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Getting object using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用GET请求下载对象
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "GET";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}
            
HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

列举对象

// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.Method = HttpVerb.GET;
request.Expires = exipreSeconds;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Getting object list using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用GET请求获取对象列表
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "GET";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}
            
HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

删除对象

// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.ObjectKey = "objectkey";
request.Method = HttpVerb.DELETE;
request.Expires = exipreSeconds;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Deleting object using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用DELETE请求删除对象
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "DELETE";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}
            
HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

初始化分段上传任务

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 初始化配置参数
ObsConfig config = new ObsConfig();
config.Endpoint = "https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全;本示例以ak和sk保存在环境变量中为例,运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
string accessKey= Environment.GetEnvironmentVariable("AccessKeyID", EnvironmentVariableTarget.Machine);
string secretKey= Environment.GetEnvironmentVariable("SecretAccessKey", EnvironmentVariableTarget.Machine);
// 创建ObsClient实例
ObsClient client = new ObsClient(accessKey, secretKey, config);

// URL有效期,3600秒
long exipreSeconds = 3600;

CreateTemporarySignatureRequest request = new CreateTemporarySignatureRequest();
request.BucketName = "bucketname";
request.ObjectKey = "objectkey";         
request.Method = HttpVerb.POST;
request.Expires = exipreSeconds;
request.SubResource = SubResourceEnum.Uploads;

CreateTemporarySignatureResponse response = client.CreateTemporarySignature(request);
Console.WriteLine("Creating mission using temporary signature url:");
Console.WriteLine("\t" + response.SignUrl);

// 使用POST请求创建多段任务
HttpWebRequest webRequest = WebRequest.Create(response.SignUrl) as HttpWebRequest;
webRequest.Method = "POST";


foreach (KeyValuePair<string, string> header in response.ActualSignedRequestHeaders)
{
    if (!header.Key.Equals("host", StringComparison.OrdinalIgnoreCase))
    {
        webRequest.Headers.Add(header.Key, header.Value);
    }
}

HttpWebResponse webResponse = null;
try
{
    webResponse = webRequest.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
    webResponse = ex.Response as HttpWebResponse;
}
Console.WriteLine("Response Status:" + Convert.ToInt32(webResponse.StatusCode));
using (MemoryStream dest = new MemoryStream())
{
    using (Stream stream = webResponse.GetResponseStream())
    {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dest.Write(buffer, 0, bytesRead);
        }

    }
    Console.WriteLine("Response Content:");
    Console.WriteLine(Encoding.UTF8.GetString(dest.ToArray()));
}

HttpVerb是OBS .NET SDK定义的枚举类型,代表请求方法类型。

相关文档