我正在尝试按照 https://learn.microsoft.com/en-us/azure/cosmos-db/table/how-to-use-go?tabs=bash 上的教程和凭据进行操作我从
azidentity.NewDefaultAzureCredential
得到能够创建一个表,因此它有足够的角色,但是当它调用 client.AddEntity
时,我收到 403 错误。
我使用
az login
登录我的根级别帐户,它具有全局管理员角色,并且具有足够的权限来添加表,但没有足够的权限来添加实体。我需要在表或存储帐户上进行不同的配置吗?
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(err)
}
serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountname, tablename)
client, err := aztables.NewClient(serviceURL, cred, nil)
if err != nil {
panic(err)
}
_, err := client.CreateTable(context.TODO(), nil)
if err != nil {
panic(err)
}
myEntity := InventoryEntity{
Entity: aztables.Entity{
PartitionKey: "pk001",
RowKey: "rk001",
},
Price: 3.99,
Inventory: 20,
ProductName: "Markers",
OnSale: false,
}
marshalled, err := json.Marshal(myEntity)
if err != nil {
panic(err)
}
_, err = client.AddEntity(context.TODO(), marshalled, nil)
if err != nil {
panic(err)
}
最后一行是失败的,尽管在此之前我能够连接并创建表。同一帐户随后也可以删除该表。
我在我的环境中尝试并得到以下结果:
最初,我尝试使用相同的代码并得到类似的错误:
RESPONSE493: 493 禁止错误代码:AuthorizationPermissionMismatch “odata.error”™:{ “code”: “AuthorizationPermissionMismatch”, i okcs-y-|1 “lang”: “en-US”, “value”: “此请求不是授权使用此权限执行此操作。 请求ID:fb@70c8d-4902-@0e2-1bed-db23 97000000 时间:2023-08-30T@6:44:4xxx" goroutine 1 [运行]:
当您的用户可能没有向表添加实体的必要权限时,就会出现上述错误。
您需要将
Storage table data contributor role
分配给您的用户。
您可以使用下面的代码使用 Golang 创建表并添加实体。
代码:
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
)
type InventoryEntity struct {
aztables.Entity
Price float64 `json:"Price"`
Inventory int `json:"Inventory"`
ProductName string `json:"ProductName"`
OnSale bool `json:"OnSale"`
}
func main() {
accountName := "venkat123"
tableName := "table1"
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(err)
}
serviceURL := fmt.Sprintf("https://%s.table.core.windows.net/%s", accountName, tableName)
client, err := aztables.NewClient(serviceURL, cred, nil)
if err != nil {
panic(err)
}
// Create the table
_, err = client.CreateTable(context.Background(), nil)
if err != nil {
panic(err)
}
// Add an entity to the table
myEntity := InventoryEntity{
Entity: aztables.Entity{
PartitionKey: "pk001",
RowKey: "rk001",
},
Price: 3.99,
Inventory: 20,
ProductName: "Markers",
OnSale: false,
}
marshalled, err := json.Marshal(myEntity)
if err != nil {
panic(err)
}
_, err = client.AddEntity(context.Background(), marshalled, nil)
if err != nil {
panic(err)
}
}
传送门:
参考: