文档首页> 对象存储服务 OBS> Go> 其他接口(Go SDK)> 生成带授权信息的URL(Go SDK)
更新时间:2024-02-01 GMT+08:00

生成带授权信息的URL(Go SDK)

功能说明

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

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

接口约束

  • OBS支持的Region与Endpoint的对应关系,详细信息请参见地区与终端节点
  • 如果遇到跨域报错、签名不匹配问题,请参考以下步骤排查问题:
    1. 未配置跨域,需要在控制台配置CORS规则,请参考配置桶允许跨域请求
    2. 签名计算问题,请参考URL中携带签名排查签名参数是否正确;比如上传对象功能,后端将Content-Type参与计算签名生成授权URL,但是前端使用授权URL时没有设置Content-Type字段或者传入错误的值,此时会出现跨域错误。解决方案为:Content-Type字段前后端保持一致。

方法定义

func (obsClient ObsClient) CreateSignedUrl(input *CreateSignedUrlInput) (output *CreateSignedUrlOutput, err error)

请求参数说明

表1 请求参数列表

参数名称

参数类型

是否必选

描述

input

*CreateSignedUrlInput

必选

参数解释:

生成带授权信息的URL请求参数,详情参见CreateSignedUrlInput

表2 CreateSignedUrlInput

参数名称

参数类型

是否必选

描述

Method

HttpMethodType

必选

参数解释:

HTTP方法类型,详情参见HttpMethodType

Bucket

string

可选

参数解释

桶名。

约束限制:

  • 桶的名字需全局唯一,不能与已有的任何桶名称重复,包括其他用户创建的桶。
  • 桶命名规则如下:
    • 3~63个字符,数字或字母开头,支持小写字母、数字、“-”、“.”。
    • 禁止使用IP地址。
    • 禁止以“-”或“.”开头及结尾。
    • 禁止两个“.”相邻(如:“my..bucket”)。
    • 禁止“.”和“-”相邻(如:“my-.bucket”和“my.-bucket”)。
  • 同一用户在同一个区域多次创建同名桶不会报错,创建的桶属性以第一次请求为准。

默认取值:

Key

string

可选

参数解释:

对象名。对象名是对象在存储桶中的唯一标识。对象名是对象在桶中的完整路径,路径中不包含桶名。

例如,您对象的访问地址为examplebucket.obs. ap-southeast-1.myhuaweicloud.com/folder/test.txt 中,对象名为folder/test.txt。

取值范围:

长度大于0且不超过1024的字符串。

默认取值:

SubResource

SubResourceType

可选

参数解释:

要访问的子资源,详情参见SubResourceType

Expires

int

可选

参数解释:

带授权信息的URL的过期时间。

取值范围:

0~(231-1),单位:秒。

默认取值:

300

Headers

map[string]string

可选

参数解释:

请求中携带的头域。

默认取值:

QueryParams

map[string]string

可选

参数解释:

请求中携带的查询参数。

默认取值:

表3 HttpMethodType

常量名

原始值

说明

HttpMethodGet

GET

HTTP GET请求。

HttpMethodPut

POST

HTTP POST请求。

HttpMethodPost

PUT

HTTP PUT请求。

HttpMethodDelete

DELETE

HTTP DELETE请求。

HttpMethodHead

HEAD

HTTP HEAD请求。

HttpMethodOptions

OPTIONS

HTTP OPTIONS请求。

表4 SubResourceType

常量名

原始值

适用接口

SubResourceStoragePolicy

storagePolicy

设置/获取桶存储类型。

SubResourceQuota

quota

设置/获取桶配额。

SubResourceStorageInfo

storageinfo

获取桶存量信息。

SubResourceLocation

location

获取桶区域位置。

SubResourceAcl

acl

设置/获取桶ACL、设置/获取对象ACL。

SubResourcePolicy

policy

设置/获取/删除桶策略。

SubResourceCors

cors

设置/获取/删除桶CORS配置。

SubResourceVersioning

versioning

设置/获取桶多版本状态。

SubResourceWebsite

website

设置/获取/删除桶Website配置。

SubResourceLogging

logging

设置/获取桶日志管理配置。

SubResourceLifecycle

lifecycle

设置/获取/删除桶生命周期配置。

SubResourceNotification

notification

设置/获取桶时间通知配置。

SubResourceTagging

tagging

设置/获取/删除桶标签。

SubResourceDelete

delete

批量删除对象。

SubResourceVersions

versions

列举桶内多版本对象。

SubResourceUploads

uploads

列举桶内分段上传任务、初始化分段上传任务。

SubResourceRestore

restore

恢复归档存储对象。

返回结果说明

表5 返回结果

参数名称

参数类型

描述

output

*CreateSignedUrlOutput

参数解释:

接口返回信息,详情参见CreateSignedUrlOutput

err

error

参数解释:

接口返回错误信息。

表6 CreateSignedUrlOutput

参数名称

参数类型

描述

SignedUrl

string

参数解释:

带授权信息的URL。

默认取值:

ActualSignedRequestHeaders

http.Header

参数解释:

通过带授权信息的URL发起请求时实际应携带的头域。

默认取值:

代码样例

本示例用于生成上传对象的带授权信息的URL
 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
package main
import (
    "fmt"
    "net/http"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    //推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
    //您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html。
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。
    // securityToken := os.Getenv("SecurityToken")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // 创建obsClient实例
    // 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过obs.WithSecurityToken方法指定securityToken值。
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    putObjectInput := &obs.CreateSignedUrlInput{}
    putObjectInput.Method = obs.HttpMethodPut
    putObjectInput.Bucket = "examplebucket"
    putObjectInput.Key = "example/objectname"
    putObjectInput.Expires = 3600
    // 生成上传对象的带授权信息的URL
    putObjectOutput, err := obsClient.CreateSignedUrl(putObjectInput)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("SignedUrl:%s\n", putObjectOutput.SignedUrl)
    fmt.Printf("ActualSignedRequestHeaders:%v\n", putObjectOutput.ActualSignedRequestHeaders)
    // 调用授权URl
    payload := strings.NewReader("hello OBS!")
    req, err := http.NewRequest("PUT", putObjectOutput.SignedUrl, payload)
    req.Header = putObjectOutput.ActualSignedRequestHeaders
    if err != nil {
        fmt.Printf("Create request error, errMsg: %s", err.Error())
        return
    }
    response, err := http.DefaultClient.Do(req)
    if err == nil {
        fmt.Printf("Use signed-url successful!\n")
        fmt.Printf("Status:%s,Etag:%s\n", response.Status, response.Header.Get("Etag"))
        return
    }
    fmt.Printf("Use signed-url successful!\n")
    fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
    fmt.Println(err)
}
本示例用于生成下载对象的带授权信息的URL
 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
63
64
65
package main
import (
    "fmt"
    "net/http"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
    // 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。
    // securityToken := os.Getenv("SecurityToken")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // 创建obsClient实例
    // 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过obs.WithSecurityToken方法指定securityToken值。
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    getObjectInput := &obs.CreateSignedUrlInput{}
    getObjectInput.Method = obs.HttpMethodGet
    getObjectInput.Bucket = "examplebucket"
    getObjectInput.Key = "example/objectname"
    getObjectInput.Expires = 3600
    // 生成下载对象的带授权信息的URL
    getObjectOutput, err := obsClient.CreateSignedUrl(getObjectInput)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("SignedUrl:%s\n", getObjectOutput.SignedUrl)
    fmt.Printf("ActualSignedRequestHeaders:%v\n", getObjectOutput.ActualSignedRequestHeaders)
    // 调用授权URl
    req, err := http.NewRequest("GET", getObjectOutput.SignedUrl, nil)
    req.Header = getObjectOutput.ActualSignedRequestHeaders
    if err != nil {
        fmt.Printf("Create request error, errMsg: %s", err.Error())
        return
    }
    response, err := http.DefaultClient.Do(req)
    if err == nil {
        fmt.Printf("Use signed-url successful!\n")
        fmt.Printf("Status:%s,Etag:%s\n", response.Status, response.Header.Get("Etag"))
        p := make([]byte, 1024)
        var readErr error
        var readCount int
        // 读取对象内容
        for {
            readCount, readErr = response.Body.Read(p)
            if readCount > 0 {
                fmt.Printf("%s", p[:readCount])
            }
            if readErr != nil {
                break
            }
        }
        return
    }
    fmt.Printf("Use signed-url successful!\n")
    fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
    fmt.Println(err)
}

本示例用于生成删除对象的带授权信息的URL

 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
package main
import (
    "fmt"
    "net/http"
    "os"
    obs "github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
func main() {
    // 您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险。
    // 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html
    ak := os.Getenv("AccessKeyID")
    sk := os.Getenv("SecretAccessKey")
    // 【可选】如果使用临时AK/SK和SecurityToken访问OBS,同样建议您尽量避免使用硬编码,以降低信息泄露风险。您可以通过环境变量获取访问密钥AK/SK,也可以使用其他外部引入方式传入。
    // securityToken := os.Getenv("SecurityToken")
    // endpoint填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
    endPoint := "https://obs.ap-southeast-1.myhuaweicloud.com"
    // 创建obsClient实例
    // 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过obs.WithSecurityToken方法指定securityToken值。
    obsClient, err := obs.New(ak, sk, endPoint/*, obs.WithSecurityToken(securityToken)*/)
    if err != nil {
        fmt.Printf("Create obsClient error, errMsg: %s", err.Error())
    }
    // 生成删除对象的带授权信息的URL
    deleteObjectInput := &obs.CreateSignedUrlInput{}
    deleteObjectInput.Method = obs.HttpMethodDelete
    deleteObjectInput.Bucket = "examplebucket"
    deleteObjectInput.Key = "example/objectname"
    deleteObjectInput.Expires = 3600
    deleteObjectOutput, err := obsClient.CreateSignedUrl(deleteObjectInput)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("SignedUrl:%s\n", deleteObjectOutput.SignedUrl)
    fmt.Printf("ActualSignedRequestHeaders:%v\n", deleteObjectOutput.ActualSignedRequestHeaders)
    // 调用授权URl
    req, err := http.NewRequest("DELETE", deleteObjectOutput.SignedUrl, nil)
    req.Header = deleteObjectOutput.ActualSignedRequestHeaders
    if err != nil {
        fmt.Printf("Create request error, errMsg: %s", err.Error())
        return
    }
    response, err := http.DefaultClient.Do(req)
    if err == nil {
        fmt.Printf("Use signed-url successful!\n")
        fmt.Printf("Status:%s\n", response.Status)
        return
    }
    fmt.Printf("Use signed-url successful!\n")
    fmt.Println("An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
    fmt.Println(err)
}