Git Product home page Git Product logo

credentials-go's Introduction

English | 简体中文

Alibaba Cloud Credentials for Go

Latest Stable Version Go Report Card codecov License GoAppveyor Build Status Scrutinizer Code Quality

Alibaba Cloud Credentials for Go is a tool for Go developers to manage credentials.

This document introduces how to obtain and use Alibaba Cloud Credentials for Go.

Requirements

  • It's necessary for you to make sure your system have installed a Go environment which is new than 1.10.x.

Installation

Use go get to install SDK:

$ go get -u github.com/aliyun/credentials-go

If you use dep to manage your dependence, you can use the following command:

$ dep ensure -add  github.com/aliyun/credentials-go

Quick Examples

Before you begin, you need to sign up for an Alibaba Cloud account and retrieve your Credentials.

Credential Type

AccessKey

Setup access_key credential through User Information Management, it have full authority over the account, please keep it safe. Sometimes for security reasons, you cannot hand over a primary account AccessKey with full access to the developer of a project. You may create a sub-account RAM Sub-account , grant its authorization,and use the AccessKey of RAM Sub-account.

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")

	akCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}
	credential, err := cred.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	credentialType := credential.Type
	fmt.Println(accessKeyId, accessSecret, credentialType)
}

STS

Create a temporary security credential by applying Temporary Security Credentials (TSC) through the Security Token Service (STS).

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")

	stsCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := stsCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type
	fmt.Println(accessKeyId, accessSecret, securityToken, credentialType)
}

AssumeRoleWithOIDC

When executing oidc role SSO, obtain the temporary identity credential (STS token) playing the RAM role by calling the AssumeRoleWithOIDC api.

package main

import (
	"fmt"
	"net/http"

	"github.com/aliyun/credentials-go/credentials"
)

func main() {
	config := new(credentials.Config).
		SetType("oidc_role_arn").
		SetOIDCProviderArn("OIDCProviderArn").
		SetOIDCTokenFilePath("OIDCTokenFilePath").
		SetRoleSessionName("RoleSessionName").
		SetPolicy("Policy").
		SetRoleArn("RoleArn").
		SetSessionExpiration(3600)
	oidcCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := oidcCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type

	fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType)
}

RamRoleArn

By specifying RAM Role, the credential will be able to automatically request maintenance of STS Token. If you want to limit the permissions(How to make a policy) of STS Token, you can assign value for 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").
		// Format: acs:ram::USER_Id:role/ROLE_NAME
		SetRoleArn("RoleArn").
		// Role Session Name
		SetRoleSessionName("RoleSessionName").
		// Not required, limit the permissions of STS Token
		SetPolicy("Policy").
		// Not required, limit the Valid time of STS Token
		SetRoleSessionExpiration(3600)

	arnCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}
	credential, err := arnCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type

	fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType)
}

uriCredential

import (
	"fmt"

	"github.com/aliyun/credentials-go/credentials"
)

func main(){
	config := new(credentials.Config).SetType("credentials_uri").SetURL("http://127.0.0.1")
	uriCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := uriCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type

	fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType)
}

EcsRamRole

By specifying the role name, the credential will be able to automatically request maintenance of STS Token.

import (
	"fmt"

	"github.com/aliyun/credentials-go/credentials"
)

func main(){
	config := new(credentials.Config).
		// Which type of credential you want
		SetType("ecs_ram_role").
		// `roleName` is optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests
		SetRoleName("RoleName")

	ecsCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := ecsCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type

	fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType)
}

RsaKeyPair

By specifying the public key Id and the private key file, the credential will be able to automatically request maintenance of the AccessKey before sending the request. Only Japan station is supported.

import (
	"fmt"

	"github.com/aliyun/credentials-go/credentials"
)

func main(){
	config := new(credentials.Config).
		// Which type of credential you want
		SetType("rsa_key_pair").
		// The file path to store the PrivateKey
		SetPrivateKeyFile("PrivateKeyFile").
		// PublicKeyId of your account
		SetPublicKeyId("PublicKeyId")

	rsaCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := rsaCredential.GetCredential()
	accessKeyId := credential.AccessKeyId
	accessSecret := credential.AccessKeySecret
	securityToken := credential.SecurityToken
	credentialType := credential.Type

	fmt.Println(accessKeyId, accessKeySecret, securityToken, credentialType)
}

Bearer Token

If credential is required by the Cloud Call Centre (CCC), please apply for Bearer Token maintenance by yourself.

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").

	bearerCredential, err := credentials.NewCredential(config)
	if err != nil {
		return
	}

	credential, err := bearerCredential.GetCredential()

	bearerToken := credential.BearerToken
	credentialType := credential.Type
	fmt.Println(bearerToken, credentialType)
}

Credential Provider Chain

If you call NewCredential() with nil, it will use provider chain to get credential for you.

1. Environment Credentials

The program first looks for environment credentials in the environment variable. If the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are defined and are not empty, the program will use them to create the default credential. If not, the program loads and looks for the client in the configuration file.

2. Config File

If there is ~/.alibabacloud/credentials default file (Windows shows C:\Users\USER_NAME\.alibabacloud\credentials), the program will automatically create credential with the name of 'default'. The default file may not exist, but a parse error throws an exception. The specified files can also be loaded indefinitely: AlibabaCloud::load('/data/credentials', 'vfs://AlibabaCloud/credentials', ...); This configuration file can be shared between different projects and between different tools. Because it is outside the project and will not be accidentally committed to the version control. Environment variables can be used on Windows to refer to the home directory %UserProfile%. Unix-like systems can use the environment variable $HOME or ~ (tilde). The path to the default file can be modified by defining the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable.

[default]                          # Default credential
type = access_key                  # Certification type: access_key
access_key_id = foo                # access key id
access_key_secret = bar            # access key secret

3. Instance RAM Role

If the environment variable ALIBABA_CLOUD_ECS_METADATA is defined and not empty, the program will take the value of the environment variable as the role name and request http://100.100.100.200/latest/meta-data/ram/security-credentials/ to get the temporary Security credential.

License

Apache-2.0

Copyright (c) 2009-present, Alibaba Cloud All rights reserved.

credentials-go's People

Contributors

alibaba-oss avatar aliguyong avatar dependabot[bot] avatar jacksontian avatar jerry-yz avatar mozillazg avatar tsinghuadream avatar wenzuochao avatar yndu13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

credentials-go's Issues

可扩展的ProviderChain

您的功能请求是否与问题有关? 请描述一下。
请描述您要解决的问题。

在项目中,我们希望获取默认ProviderChain的灵活性,并额外提供自己的凭据获取方式。然而在改仓库中所有provider相关内容都未导出。或者希望自定义需要使用哪些内置provider,及其顺序。

描述你想要的解决方案
请描述所需的行为。

导出providerEnv,providerProfile,providerInstance及其resolve函数,与老版本SDK对齐。

描述您考虑过的替代方案
请描述您考虑的替代解决方案或功能。

继续使用老版本SDK

环境变量名称错误

README 中给出的环境变量名称是 ALICLOUD_ACCESS_KEYALICLOUD_SECRET_KEY

代码中使用的是 ALIBABA_CLOUD_ACCESS_KEY_IdALIBABA_CLOUD_ACCESS_KEY_SECRET

const (
// EnvVarAccessKeyId is a name of ALIBABA_CLOUD_ACCESS_KEY_Id
EnvVarAccessKeyId = "ALIBABA_CLOUD_ACCESS_KEY_Id"
// EnvVarAccessKeySecret is a name of ALIBABA_CLOUD_ACCESS_KEY_SECRET
EnvVarAccessKeySecret = "ALIBABA_CLOUD_ACCESS_KEY_SECRET"
)

代码和文档不匹配。

另外 Id 这个大小写非常奇葩。Linux 系统下环境变量大小写敏感,容易造成问题,建议统一使用大写字母。

读取profile出现问题

软件版本    
    go1.16
github.com/alibabacloud-go/darabonba-openapi v0.1.5
github.com/alibabacloud-go/ecs-20140526 v1.2.0 // indirect
github.com/alibabacloud-go/ecs-20140526/v2 v2.0.2
github.com/alibabacloud-go/tea v1.1.16
github.com/aliyun/alibaba-cloud-sdk-go v1.61.1181
github.com/aliyun/credentials-go v1.1.2 // indirect

问题如下:
在alibaba-cloud-sdk-go版本中,可以指定profile读取配置文件的profile

      pp := provider.NewProfileProvider(profile)
      client, err := ecs.NewClientWithProvider(regionId, pp)
      if err != nil {
      log.Printf("NewClient %v", err)
      return nil, err
      }

在新版credentials-go中我尝试写上面的功能

    os.Setenv("ALIBABA_CLOUD_CREDENTIALS_FILE", "这里得绝对路径/.alibabacloud/credentials")
    // 不指定时config只能读到default
 akCredential, err := credentials.NewCredential(nil)
 if err != nil {
	log.Println("DescribeInstances1", err)
return nil, err
 }
 accessKeyId, err2 := akCredential.GetAccessKeyId()
 if err2 != nil {
	log.Println("DescribeInstances2", err2)
	return nil, err
  }

读了下源码,偿试向里传profile,结果都是私有的
// env := newEnvProvider()
// pp := newProfileProvider()
// instanceP := newInstanceCredentialsProvider()
// pc := newProviderChain([]Provider{env, pp, instanceP})
且在NewCredential,并无入口可设置
func NewCredential(config *Config) (credential Credential, err error) {
if config == nil {
config, err = defaultChain.resolve()
if err != nil {
return
}
return NewCredential(config)
}
请问我该用什么方法能做到这个功能

AccessKeyId的key和文档不一致

文档中描述

Credentials工具优先在环境变量中获取凭据信息。如果系统环境变量ALIBABA_CLOUD_ACCESS_KEY_ID(密钥Key) 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET(密钥Value) 不为空,Credentials工具会优先使用它们作为默认凭据。

文档中的变量ALIBABA_CLOUD_ACCESS_KEY_ID
实际代码中

EnvVarAccessKeyId = "ALIBABA_CLOUD_ACCESS_KEY_Id"

未区分大小写,实际使用ALIBABA_CLOUD_ACCESS_KEY_ID会导致无法获取到ACCESS_KEY_ID

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.