您的位置 首页 golang

golang对接阿里云私有Bucket上传图片、授权访问图片

1、为什么要设置私有bucket

  • 公共读写 :互联网上任何用户都可以对该 Bucket 内的文件进行访问,并且向该 Bucket 写入数据。这有可能造成您数据的外泄以及费用激增,若被人恶意写入违法信息还可能会侵害您的合法权益
  • 私有 :只有该存储空间的拥有者可以对该存储空间内的文件进行读写操作,其他人无法访问该存储空间内的文件

鉴于以上,公司要求将bucket设置为私有,只有授权的用户才能访问

2、准备

2.1 创建RAM账户

开通OSS后账户,创建RAM账户,使用STS临时访问凭证访问OSS,具体参考阿里云文档

提示:在步骤四创建角色要将RAM角色赋予 AliyunOSSFullAccess 权限
因为此处没设置oss最高权限,我找了一天问题,大家
谨记 ,写这篇博客也是记录一下我的填坑之路

2.2 设置Bucket

  • 在对象存储中,Bucket列表创建私有Bucket
  • 然后在此Bucket授权刚才创建OSS账号id,授权操作为完全控制

3、上菜

3.1 常量及其结构体

  • 根据自己阿里云信息去配置
 const (
AccessKeyId     = "**"//oss账户AK
AccessKeySecret = "**"//oss账户ST
stsEndpoint     = "**"//sts.阿里云对象存储地址
RoleArn         = "**"//创建角色用到的
RoleSessionName = "**"//创建角色用到的
BucketName      = "**" //填写Bucket名称,例如examplebucket
Endpoint        = "**"//阿里云对象存储地址
UploadOssUrl    = "**" //返回给前端oss上传地址
)
type StsTokenInfo struct {
StatusCode      int    `json:"StatusCode"`
AccessKeyId     string `json:"AccessKeyId"`
AccessKeySecret string `json:"AccessKeySecret"`
SecurityToken   string `json:"SecurityToken"`
Expiration      string `json:"Expiration"`
}

type StsErrorInfo struct {
StatusCode   int    `json:"StatusCode"`
ErrorCode    string `json:"ErrorCode"`
ErrorMessage string `json:"ErrorMessage"`
}
  

3.2 获取STS临时用户信息

 package aliyun

import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/client"
sts "github.com/alibabacloud-go/sts-20150401/client"
"github.com/alibabacloud-go/tea/tea"
log "github.com/sirupsen/logrus"
)
//
//  GetAliyunStsInfo
//  @Description: 获取STS临时用户信息
//  @param isReturnAll
//  @return *sts.AssumeRoleResponseBody
//
func GetAliyunStsInfo() *sts.AssumeRoleResponseBody {
return generateStsInfo()
}

/**
 * 生成STS临时用户信息
 */func generateStsInfo() *sts.AssumeRoleResponseBody {
client, _err := createClient(tea.String(AccessKeyId), tea.String(AccessKeySecret))
if _err != nil {
fmt.Print(_err.Error())
}
assumeRoleRequest := &sts.AssumeRoleRequest{
RoleArn:         tea.String(RoleArn),
RoleSessionName: tea.String(RoleSessionName),
}
resp, err := client.AssumeRole(assumeRoleRequest)
if err != nil {
fmt.Print(err.Error())
}
fmt.Printf("获取STS临时用户信息:%v", resp)
log.Info("获取STS临时用户信息:", resp)
return (*resp).Body
}

/**
 * 使用AK&SK初始化账号Client
 * @param accessKeyId
 * @param accessKeySecret
 * @return Client
 * @throws Exception
 */func createClient(accessKeyId *string, accessKeySecret *string) (_result *sts.Client, _err error) {
config := &openapi.Config{
AccessKeyId:     accessKeyId,
AccessKeySecret: accessKeySecret,
}
// 访问的域名
config.Endpoint = tea.String(stsEndpoint)
_result = &sts.Client{}
_result, _err = sts.NewClient(config)
return _result, _err
}
  
  • 我是使用新版的SDK阿里云demo中,修改了一下,具体参考文档
  • 获取STS临时用户信息方法多个地方需要用到,所以我抽取出来供其他接口调用(比如授权访问就需要STS临时用户信息去生成signUrl)

3.3 接口调用

3.3.1不包含签名的STS临时用户信息

  • 我这里用的gin框架, 这个接口是不包含前端需要的签名(policy和Signature)的 ,需要前端使用oss插件(全部信息返回的写在另一个接口)
 /**
接口:获取sts用户
前端需要加载oss插件
不需要则去调用policy文件中AppAliyunPolicy
*/func AppAliyunSts(c *gin.Context) {
response := GetAliyunStsInfo()
c.JSON(http.StatusOK, gin.H{
"code": 1,
"data": response,
})
return
}
  
  • API调用,返回的信息

3.3.2含签名的STS临时用户信息

  • 此接口好处就在前端不需要额外加载多余的包
 package aliyun

import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"hash"
"io"
"net/http"
"time"
)
/**
签名直传服务
用于小程序上传图片不用加载库
*/// 用户上传文件时指定的前缀。
//var upload_dir string = "user-dir/"

//过期时间3000秒
var expire_time int64 = 3000

type ConfigStruct struct {
Expiration string     `json:"expiration"`
Conditions [][]string `json:"conditions"`
}
type PolicyToken struct {
StsTokenInfo
Expire       int64  `json:"expire"`
Signature    string `json:"signature"`
Policy       string `json:"policy"`
Directory    string `json:"dir"`
UploadOssUrl string `json:"uploadOssUrl"`
}

func AppAliyunPolicy(c *gin.Context) {
uploadDir := c.DefaultQuery("dir", "user-dir/")
//获取token2中的accessKeyId,accessKeySecret
resp := GetAliyunStsInfo()
log.Info(resp)

now := time.Now().Unix()
expire_end := now + expire_time
var tokenExpire = getGmtIso8601(expire_end)

//create post policy json
var config ConfigStruct
config.Expiration = tokenExpire
var condition []string
condition = append(condition, "starts-with")
condition = append(condition, "$key")
condition = append(condition, uploadDir)
config.Conditions = append(config.Conditions, condition)

//calucate signature
result, err := json.Marshal(config)
debyte := base64.StdEncoding.EncodeToString(result)
h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(*resp.Credentials.AccessKeySecret))
io.WriteString(h, debyte)
signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))

policyToken := &PolicyToken{}
policyToken.AccessKeyId = *resp.Credentials.AccessKeyId
policyToken.AccessKeySecret = *resp.Credentials.AccessKeySecret
policyToken.SecurityToken = *resp.Credentials.SecurityToken
policyToken.Expiration = *resp.Credentials.Expiration
policyToken.Expire = expire_end
policyToken.Signature = string(signedStr)
policyToken.Directory = uploadDir
policyToken.Policy = string(debyte)
policyToken.UploadOssUrl = UploadOssUrl
if err != nil {
fmt.Println("json err:", err)
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"data": policyToken,
})
return
}

func getGmtIso8601(expireEnd int64) string {
var tokenExpire = time.Unix(expireEnd, 0).UTC().Format("2006-01-02T15:04:05Z")
return tokenExpire
}
  
  • Get接口携带参数dir,指定放在哪个文件夹
  • 接口调用,返回信息

3.4 授权访问

3.4.1接口调用

  • 阿里云提供了两种授权方式, URL授权 header头授权 ,我这里是图片授权所以选择了URL,图片需要授权携带签名参数才能请求到具体参考文档
 package aliyun

import (
"fmt"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/gin-gonic/gin"
"net/http"
)

/**
图片授权访问
返回签名后的URL
*/func GetSignURL(c *gin.Context) {
accessKeyId := c.DefaultQuery("accessKeyId", "")
accessKeySecret := c.DefaultQuery("accessKeySecret", "")
securityToken := c.DefaultQuery("securityToken", "")
fullImgPath := c.DefaultQuery("fullImgPath", "") //图片全路径
//如果为空则去请求sts临时用户信息
if accessKeyId == "" || accessKeySecret == "" || securityToken == "" {
stsTokenInfo := GetAliyunStsInfo()
accessKeyId = *stsTokenInfo.Credentials.AccessKeyId
accessKeySecret = *stsTokenInfo.Credentials.AccessKeySecret
securityToken = *stsTokenInfo.Credentials.SecurityToken
}

// 获取STS临时凭证后,您可以通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。
client, err := oss.New(Endpoint, accessKeyId, accessKeySecret, oss.SecurityToken(securityToken))
if err != nil {
fmt.Print(err.Error())
}
// 填写文件完整路径,例如exampledir/exampleobject.txt。文件完整路径中不能包含Bucket名称。
objectName := fullImgPath
// 获取存储空间。
bucket, err := client.Bucket(BucketName)
if err != nil {
fmt.Print(err.Error())
}

// 签名直传。
signedURL, err := bucket.SignURL(objectName, oss.HTTPGet, 6000)
if err != nil {
fmt.Print(err.Error())
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"data": signedURL,
})
}

  
  • 这里有四个参数,前上个参数是请求STS临时用户获取到,前端传递过来的(此场景适用于 上传图片后回显图片 ,就需要带签名的图片URL),如果前端没有传这三个参数,我们需要自己再去调用之前GetAliyunStsInfo()去生成,
  • fullImgPath参数就是图片保存的全路径,填写文件完整路径,例如exampledir/exampleobject.txt。文件完整路径中 不能包含Bucket名称

3.4.2 API调用,返回信息

  • 如果没有授权,则会提示

我碰到这个问题是因为没有给RAM角色设置OSS最高权限, 谨记

  • 如果过了有效期,则会提示
 <Error>
<Code>AccessDenied</Code>
<Message>Request has expired.</Message>
<RequestId>***</RequestId>
<HostId>****</HostId>
<Expires>2022-04-02T08:42:47.000Z</Expires>
<ServerTime>2022-04-03T03:56:52.000Z</ServerTime>
</Error>
  

好了,以上接口经本人测试调通,耗时一天半,代码没什么,问题全出在配置权限上了,用来记录我的填坑之路

文章来自

文章来源:智云一二三科技

文章标题:golang对接阿里云私有Bucket上传图片、授权访问图片

文章地址:https://www.zhihuclub.com/98586.shtml

关于作者: 智云科技

热门文章

网站地图