aliyun/credentials-go

GitHub: aliyun/credentials-go

该库为 Go 开发者提供统一的阿里云凭证管理能力,支持多种认证方式并内置默认凭证链自动查找,简化了云服务调用的身份验证流程。

Stars: 20 | Forks: 15

English | [简体中文](README-CN.md) # Alibaba Cloud Credentials for Go [![Latest Stable Version](https://badge.fury.io/gh/aliyun%2Fcredentials-go.svg)](https://badge.fury.io/gh/aliyun%2Fcredentials-go) [![Go](https://static.pigsec.cn/wp-content/uploads/repos/cas/31/31c96a8fe552af584b5983afc39ddf2e71ca6806185aad0eda564c77331e5b3e.svg)](https://github.com/aliyun/credentials-go/actions/workflows/go.yml) [![codecov](https://codecov.io/gh/aliyun/credentials-go/branch/master/graph/badge.svg)](https://codecov.io/gh/aliyun/credentials-go) [![License](https://poser.pugx.org/alibabacloud/credentials/license)](https://packagist.org/packages/alibabacloud/credentials) [![Go Report Card](https://goreportcard.com/badge/github.com/aliyun/credentials-go)](https://goreportcard.com/report/github.com/aliyun/credentials-go) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/aliyun/credentials-go/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/aliyun/credentials-go/?branch=master) ![Alibaba Cloud Logo](https://aliyunsdk-pages.alicdn.com/icons/AlibabaCloud.svg) Alibaba Cloud Credentials for Go 是一个供 Go 开发者管理凭证的工具。 本文档介绍如何获取和使用 Alibaba Cloud Credentials for Go。 ## 环境要求 - 您需要确保您的系统已经安装了 1.12.x 或更高版本的 Go 环境。 ## 安装 使用 `go get` 安装 SDK: ``` go get -u github.com/aliyun/credentials-go ``` ## 快速示例 在开始之前,您需要注册阿里云账号并获取您的[凭证](https://usercenter.console.aliyun.com/#/manage/ak)。 ### 凭证类型 #### 默认凭证提供者链 如果您不指定初始化 Credentials 客户端的方法,则会使用默认凭证提供者链。更多信息,请参阅本文档的默认凭证提供者链部分。 ``` package main import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main() { provider, err := credentials.NewCredential(nil) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessSecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(*accessKeyId, *accessSecret, *securityToken, *credentialType) } ``` #### AccessKey 通过[用户信息管理][ak]设置 access_key 凭证,它拥有该账户的完全控制权,请妥善保管。有时出于安全原因,您可能不想将具有完全访问权限的主账户 AccessKey 交给项目开发者。您可以创建一个子账户 [RAM 子账号][ram],授予其[权限][permissions],并使用 RAM 子账号的 AccessKey。 ``` package main import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main() { config := new(credentials.Config). // Which type of credential you want SetType("access_key"). // AccessKeyId of your account SetAccessKeyId("AccessKeyId"). // AccessKeySecret of your account SetAccessKeySecret("AccessKeySecret") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret credentialType := credential.Type fmt.Println(*accessKeyId, *accessKeySecret, *credentialType) } ``` #### STS 通过安全令牌服务(STS)申请临时安全凭证(TSC)来创建临时安全凭证。 ``` package main import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main() { config := new(credentials.Config). // Which type of credential you want SetType("sts"). // AccessKeyId of your account SetAccessKeyId("AccessKeyId"). // AccessKeySecret of your account SetAccessKeySecret("AccessKeySecret"). // Temporary Security Token SetSecurityToken("SecurityToken") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(*accessKeyId, *accessKeySecret, *securityToken, *credentialType) } ``` #### AssumeRoleWithOIDC 在将 RAM 角色挂载到 Container Service for Kubernetes 的工作节点后,该工作节点上 Pod 中的应用程序可以像 ECS 实例上的应用程序一样,使用元数据服务器获取 STS token。但是,如果工作节点上部署了不受信任的应用程序(例如由您的客户提交且您无法获取其代码的应用程序),您可能不希望该应用程序使用元数据服务器来获取挂载到工作节点的 RAM 角色的 STS token。为了确保云资源的安全并使不受信任的应用程序能够安全地获取所需的 STS token,您可以使用 RAM Roles for Service Accounts (RRSA) 功能向应用程序授予最小必要权限。在这种情况下,ACK 集群会创建一个 service account OpenID Connect (OIDC) token 文件,将该 token 文件与 Pod 关联,然后将相关的环境变量注入到 Pod 中。接着,Credentials 工具会使用这些环境变量调用 STS 的 AssumeRoleWithOIDC 操作,并获取 RAM 角色的 STS token。有关 RRSA 功能的更多信息,请参见[使用 RRSA 授权不同的 Pod 访问不同的云服务](https://www.alibabacloud.com/help/en/ack/ack-managed-and-ack-dedicated/user-guide/use-rrsa-to-authorize-pods-to-access-different-cloud-services#task-2142941)。 ``` package main import ( "fmt" "net/http" "github.com/aliyun/credentials-go/credentials" ) func main() { config := new(credentials.Config). SetType("oidc_role_arn"). // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. SetOIDCProviderArn("OIDCProviderArn"). // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. SetOIDCTokenFilePath("OIDCTokenFilePath"). // Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. SetRoleArn("RoleArn"). // Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. SetRoleSessionName("RoleSessionName"). // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. SetPolicy("Policy"). // Optional. Specify the validity period of the session. SetRoleSessionExpiration(3600). // Optional. The default value is sts.aliyuncs.com. It is recommended to use a regionalized STS domain name. Selecting a region that is geographically closer can ensure network connectivity. For the domain name corresponding to the region, please refer to: https://api.alibabacloud.com/product/Sts SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) } ``` #### RamRoleArn 通过指定 [RAM 角色][RAM Role],凭证将能够自动请求维护 STS Token。如果您想限制 STS Token 的权限([如何制定策略][policy]),您可以为 `Policy` 赋值。 ``` import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main(){ config := new(credentials.Config). // Which type of credential you want SetType("ram_role_arn"). // AccessKeyId of your account SetAccessKeyId("AccessKeyId"). // AccessKeySecret of your account SetAccessKeySecret("AccessKeySecret"). // Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole. SetRoleArn("RoleArn"). // Specify the name of the role session. SetRoleSessionName("RoleSessionName"). // Optional. Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}. SetPolicy("Policy"). // Optional. Specify the expiration of the session SetRoleSessionExpiration(3600). // Optional, role external ID, this parameter is the parameter information provided externally to represent the role, and its main function is to prevent the confused deputy problem. For more information, please refer to: https://www.alibabacloud.com/help/en/ram/use-cases/use-externalid-to-prevent-the-confused-deputy-problem SetExternalId("ExternalId"). // Optional. The default value is sts.aliyuncs.com. It is recommended to use a regionalized STS domain name. Selecting a region that is geographically closer can ensure network connectivity. For the domain name corresponding to the region, please refer to: https://api.alibabacloud.com/product/Sts SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) } ``` #### Credentials URI 通过指定 URI,凭证将能够自动请求维护 STS Token。 ``` import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main(){ config := new(credentials.Config). SetType("credentials_uri"). // Format: http url. `credentialsURI` can be replaced by setting environment variable: ALIBABA_CLOUD_CREDENTIALS_URI SetURL("http://127.0.0.1") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) } ``` #### EcsRamRole Credentials 工具会自动获取挂载到 ECS 实例的 RAM 角色,并使用 ECS 的元数据服务器获取 STS token。然后使用该 STS token 初始化 Credentials 客户端。您也可以将 RAM 角色挂载到弹性容器实例或阿里云 Container Service for Kubernetes (ACK) 集群的工作节点上。 ``` import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main(){ config := new(credentials.Config). // Which type of credential you want SetType("ecs_ram_role"). // Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter. SetRoleName("RoleName"). // `DisableIMDSv1` is optional and is recommended to be turned on. It can be replaced by setting environment variable: ALIBABA_CLOUD_IMDSV1_DISABLED SetDisableIMDSv1(true) provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } accessKeyId := credential.AccessKeyId accessKeySecret := credential.AccessKeySecret securityToken := credential.SecurityToken credentialType := credential.Type fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType) } ``` #### Bearer Token 如果云呼叫中心(CCC)需要凭证,请自行申请维护 Bearer Token。 ``` import ( "fmt" "github.com/aliyun/credentials-go/credentials" ) func main(){ config := new(credentials.Config). // Which type of credential you want SetType("bearer"). // BearerToken of your account SetBearerToken("BearerToken") provider, err := credentials.NewCredential(config) if err != nil { return } credential, err := provider.GetCredential() if err != nil { return } bearerToken := credential.BearerToken credentialType := credential.Type fmt.Println(bearerToken, credentialType) } ``` ### 凭证提供者链 如果您想在应用程序的开发和生产环境中使用不同类型的凭证,通常需要从代码中获取环境信息,并编写代码分支来为开发和生产环境获取不同的凭证。Credentials 工具的默认凭证提供者链允许您根据独立于应用程序的配置,使用相同的代码获取不同环境的凭证。如果您调用 `NewCredential()` 并传入 nil,它将使用提供者链为您获取凭证。 ### 1. 环境凭证 在环境变量中寻找环境凭证。 - 如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID` 和 `ALIBABA_CLOUD_ACCESS_KEY_SECRET` 环境变量且不为空,程序将使用它们创建默认凭证。 - 如果定义了 `ALIBABA_CLOUD_ACCESS_KEY_ID`、`ALIBABA_CLOUD_ACCESS_KEY_SECRET` 和 `ALIBABA_CLOUD_SECURITY_TOKEN` 环境变量且不为空,程序将使用它们创建临时安全凭证(STS)。注意:此 token 具有过期时间,建议在临时环境中使用。 ### 2. OIDC IdP 的 RAM 角色 如果在之前的步骤中没有找到凭证,Credentials 工具会获取以下环境变量的值: `ALIBABA_CLOUD_ROLE_ARN`:RAM 角色的 ARN。 `ALIBABA_CLOUD_OIDC_PROVIDER_ARN`:OIDC IdP 的 ARN。 `ALIBABA_CLOUD_OIDC_TOKEN_FILE`:OIDC token 文件的路径。 如果指定了上述三个环境变量,Credentials 工具将使用这些环境变量调用 STS 的 [AssumeRoleWithOIDC](https://www.alibabacloud.com/help/en/ram/developer-reference/api-sts-2015-04-01-assumerolewithoidc) 操作,以获取 STS token 作为默认凭证。 ### 3. 使用 Aliyun CLI 工具的 config.json 配置文件 如果没有更高优先级的凭证信息,Credentials 工具会首先检查以下位置是否存在 config.json 文件: Linux 系统:`~/.aliyun/config.json` Windows 系统:`C:\Users\USER_NAME\.aliyun\config.json` 如果该文件存在,程序将使用配置文件中 `current` 指定的凭证信息来初始化凭证客户端。当然,您也可以使用环境变量 `ALIBABA_CLOUD_PROFILE` 来指定凭证信息,例如将 `ALIBABA_CLOUD_PROFILE` 的值设置为 `AK`。 在 config.json 配置文件中,每个模块的值代表获取凭证信息的不同方式: - AK:使用用户的 Access Key 作为凭证信息; - RamRoleArn:使用 RAM 角色的 ARN 获取凭证信息; - EcsRamRole:使用绑定到 ECS 的 RAM 角色获取凭证信息; - OIDC:通过 OIDC ARN 和 OIDC Token 获取凭证信息; - ChainableRamRoleArn:通过指定 JSON 文件中的其他凭证,使用角色链方式获取新的凭证信息。 配置示例信息如下: ``` { "current": "AK", "profiles": [ { "name": "AK", "mode": "AK", "access_key_id": "access_key_id", "access_key_secret": "access_key_secret" }, { "name": "RamRoleArn", "mode": "RamRoleArn", "access_key_id": "access_key_id", "access_key_secret": "access_key_secret", "ram_role_arn": "ram_role_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, "sts_region": "cn-hangzhou" }, { "name": "EcsRamRole", "mode": "EcsRamRole", "ram_role_name": "ram_role_name" }, { "name": "OIDC", "mode": "OIDC", "ram_role_arn": "ram_role_arn", "oidc_token_file": "path/to/oidc/file", "oidc_provider_arn": "oidc_provider_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, "sts_region": "cn-hangzhou" }, { "name": "ChainableRamRoleArn", "mode": "ChainableRamRoleArn", "source_profile": "AK", "ram_role_arn": "ram_role_arn", "ram_session_name": "ram_session_name", "expired_seconds": 3600, "sts_region": "cn-hangzhou" } ] } ``` ### 4. 配置文件 配置示例: ``` [default] type = access_key # Authentication method is access_key access_key_id = foo # Key access_key_secret = bar # Secret [project1] type = ecs_ram_role # Authentication method is ecs_ram_role role_name = EcsRamRoleTest # Role name, optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests. [project2] type = ram_role_arn # Authentication method is ram_role_arn access_key_id = foo access_key_secret = bar role_arn = role_arn role_session_name = session_name [project3] type=oidc_role_arn # Authentication method is oidc_role_arn oidc_provider_arn=oidc_provider_arn oidc_token_file_path=oidc_token_file_path role_arn=role_arn role_session_name=session_name ``` ### 5. 实例 RAM 角色 如果定义了环境变量 `ALIBABA_CLOUD_ECS_METADATA` 且不为空,程序会将该环境变量的值作为角色名称,并请求 `http://100.100.100.200/latest/meta-data/ram/security-credentials/` 来获取临时安全凭证作为默认凭证。 ### 6. 使用外部服务凭证 URI 如果没有更高优先级的凭证信息,Credentials 工具将从环境变量中获取 `ALIBABA_CLOUD_CREDENTIALS_URI`。如果存在,程序将请求该 URI 地址以获取临时安全凭证作为默认凭证信息。 外部服务的响应结构应如下所示: ``` { "Code": "Success", "AccessKeyId": "AccessKeyId", "AccessKeySecret": "AccessKeySecret", "SecurityToken": "SecurityToken", "Expiration": "2024-10-26T03:46:38Z" } ``` ## 开源许可 [Apache-2.0](/LICENSE) Copyright (c) 2009-present, Alibaba Cloud All rights reserved.
标签:EVTX分析, Go, Ruby工具, SOC Prime, 云计算, 代码分析, 凭证管理, 开发工具, 日志审计, 规则引擎, 阿里云