本文整理汇总了Golang中github.com/aws/aws-sdk-go/aws/credentials.NewCredentials函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCredentials函数的具体用法?Golang NewCredentials怎么用?Golang NewCredentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCredentials函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestPreResignRequestExpiredCreds
func TestPreResignRequestExpiredCreds(t *testing.T) {
provider := &credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: "AKID",
SecretAccessKey: "SECRET",
SessionToken: "SESSION",
}}
creds := credentials.NewCredentials(provider)
svc := awstesting.NewClient(&aws.Config{Credentials: creds})
r := svc.NewRequest(
&request.Operation{
Name: "BatchGetItem",
HTTPMethod: "POST",
HTTPPath: "/",
},
nil,
nil,
)
r.ExpireTime = time.Minute * 10
Sign(r)
querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature")
creds.Expire()
r.Time = time.Now().Add(time.Hour * 48)
Sign(r)
assert.NotEqual(t, querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature"))
}
示例2: GetSession
// GetSessions returns the current session from the SessionProvider.
func (dsp *ConfigurableSessionProvider) GetSession() *session.Session {
dsp.sessionMutex.Lock()
defer dsp.sessionMutex.Unlock()
if dsp._session != nil {
return dsp._session
}
cfgs := []*aws.Config{
aws.NewConfig().WithRegion(dsp.ConfigRegion),
}
if dsp.ConfigAccessKey != "" {
cfgs = append(cfgs, aws.NewConfig().WithCredentials(credentials.NewStaticCredentials(
dsp.ConfigAccessKey,
dsp.ConfigSecretKey,
dsp.ConfigSessionToken,
)))
} else if !dsp.ConfigDisableENVCredentials {
// NOTE: We may want to init all credential providers in one config, as they might overwrite each other
cfgs = append(cfgs, aws.NewConfig().WithCredentials(credentials.NewCredentials(&credentials.EnvProvider{})))
} else {
panic("no valid configuration parameters for aws credentials found.")
}
dsp._session = session.New(cfgs...)
return dsp._session
}
示例3: TestAfterRetryRefreshCreds
func TestAfterRetryRefreshCreds(t *testing.T) {
os.Clearenv()
credProvider := &mockCredsProvider{}
svc := awstesting.NewClient(&aws.Config{
Credentials: credentials.NewCredentials(credProvider),
MaxRetries: aws.Int(1),
})
svc.Handlers.Clear()
svc.Handlers.ValidateResponse.PushBack(func(r *request.Request) {
r.Error = awserr.New("UnknownError", "", nil)
r.HTTPResponse = &http.Response{StatusCode: 400, Body: ioutil.NopCloser(bytes.NewBuffer([]byte{}))}
})
svc.Handlers.UnmarshalError.PushBack(func(r *request.Request) {
r.Error = awserr.New("ExpiredTokenException", "", nil)
})
svc.Handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler)
assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
assert.False(t, credProvider.retrieveCalled)
req := svc.NewRequest(&request.Operation{Name: "Operation"}, nil, nil)
req.Send()
assert.True(t, svc.Config.Credentials.IsExpired())
assert.False(t, credProvider.retrieveCalled)
_, err := svc.Config.Credentials.Get()
assert.NoError(t, err)
assert.True(t, credProvider.retrieveCalled)
}
示例4: assumeRole
// assumeRole uses IAM credentials to assume a role
func (p *VaultProvider) assumeRole(creds credentials.Value, roleArn string) (sts.Credentials, error) {
client := sts.New(session.New(&aws.Config{
Credentials: credentials.NewCredentials(&credentials.StaticProvider{Value: creds}),
}))
input := &sts.AssumeRoleInput{
RoleArn: aws.String(roleArn),
RoleSessionName: aws.String(p.roleSessionName()),
DurationSeconds: aws.Int64(int64(p.AssumeRoleDuration.Seconds())),
}
// if we don't have a session, we need to include MFA token in the AssumeRole call
if mfa, ok := p.profiles[p.profile]["mfa_serial"]; ok {
input.SerialNumber = aws.String(mfa)
if p.MfaToken == "" {
token, err := p.MfaPrompt(fmt.Sprintf("Enter token for %s: ", mfa))
if err != nil {
return sts.Credentials{}, err
}
input.TokenCode = aws.String(token)
} else {
input.TokenCode = aws.String(p.MfaToken)
}
}
log.Printf("Assuming role %s with iam credentials", roleArn)
resp, err := client.AssumeRole(input)
if err != nil {
return sts.Credentials{}, err
}
return *resp.Credentials, nil
}
示例5: GetAWSCreds
// GetAWSCreds returns the appropriate value as the need arises.
//
// evaluated in the following order
// 1. input variable
// 2. Environment variable
// 3. IAM Role
//
// "/.aws/credentials" necessary item increased about that, so it isn't used.
func (c *Config) GetAWSCreds() (*credentials.Credentials, error) {
var creds *credentials.Credentials
var err error
err = nil
// 1. input variable used
if c.Aws.Accesskey != "" && c.Aws.SecretKey != "" {
creds = credentials.NewStaticCredentials(c.Aws.Accesskey, c.Aws.SecretKey, "")
creds.Expire()
_, err = creds.Get()
}
if err != nil {
// 2. Environment variable used
creds = credentials.NewEnvCredentials()
creds.Expire()
_, err = creds.Get()
if err != nil {
// 3. IAM Role used
creds = credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{})
creds.Expire()
_, err = creds.Get()
}
}
return creds, err
}
示例6: getSessionToken
func (p *VaultProvider) getSessionToken(creds *credentials.Value) (sts.Credentials, error) {
params := &sts.GetSessionTokenInput{
DurationSeconds: aws.Int64(int64(p.SessionDuration.Seconds())),
}
if mfa, ok := p.profiles[p.profile]["mfa_serial"]; ok {
params.SerialNumber = aws.String(mfa)
if p.MfaToken == "" {
token, err := p.MfaPrompt(fmt.Sprintf("Enter token for %s: ", mfa))
if err != nil {
return sts.Credentials{}, err
}
params.TokenCode = aws.String(token)
} else {
params.TokenCode = aws.String(p.MfaToken)
}
}
client := sts.New(session.New(&aws.Config{
Credentials: credentials.NewCredentials(&credentials.StaticProvider{
Value: *creds,
}),
}))
log.Printf("Getting new session token for profile %s", sourceProfile(p.profile, p.profiles))
resp, err := client.GetSessionToken(params)
if err != nil {
return sts.Credentials{}, err
}
return *resp.Credentials, nil
}
示例7: TestAfterRetryRefreshCreds
func TestAfterRetryRefreshCreds(t *testing.T) {
os.Clearenv()
credProvider := &mockCredsProvider{}
svc := NewService(&Config{Credentials: credentials.NewCredentials(credProvider), MaxRetries: 1})
svc.Handlers.Clear()
svc.Handlers.ValidateResponse.PushBack(func(r *Request) {
r.Error = apierr.New("UnknownError", "", nil)
r.HTTPResponse = &http.Response{StatusCode: 400}
})
svc.Handlers.UnmarshalError.PushBack(func(r *Request) {
r.Error = apierr.New("ExpiredTokenException", "", nil)
})
svc.Handlers.AfterRetry.PushBack(func(r *Request) {
AfterRetryHandler(r)
})
assert.True(t, svc.Config.Credentials.IsExpired(), "Expect to start out expired")
assert.False(t, credProvider.retreiveCalled)
req := NewRequest(svc, &Operation{Name: "Operation"}, nil, nil)
req.Send()
assert.True(t, svc.Config.Credentials.IsExpired())
assert.False(t, credProvider.retreiveCalled)
_, err := svc.Config.Credentials.Get()
assert.NoError(t, err)
assert.True(t, credProvider.retreiveCalled)
}
示例8: NewCredentials
// NewCredentials returns a pointer to a new Credentials object wrapping the
// AssumeRoleProvider. The credentials will expire every 15 minutes and the
// role will be named after a nanosecond timestamp of this operation.
//
// The sts and roleARN parameters are used for building the "AssumeRole" call.
// Pass nil as sts to use the default client.
//
// Window is the expiry window that will be subtracted from the expiry returned
// by the role credential request. This is done so that the credentials will
// expire sooner than their actual lifespan.
func NewCredentials(client AssumeRoler, roleARN string, window time.Duration) *credentials.Credentials {
return credentials.NewCredentials(&AssumeRoleProvider{
Client: client,
RoleARN: roleARN,
ExpiryWindow: window,
})
}
示例9: mergeConfigSrcs
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) {
// Merge in user provided configuration
cfg.MergeIn(userCfg)
// Region if not already set by user
if len(aws.StringValue(cfg.Region)) == 0 {
if len(envCfg.Region) > 0 {
cfg.WithRegion(envCfg.Region)
} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
cfg.WithRegion(sharedCfg.Region)
}
}
// Configure credentials if not already set
if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
if len(envCfg.Creds.AccessKeyID) > 0 {
cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
envCfg.Creds,
)
} else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
cfgCp := *cfg
cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
sharedCfg.AssumeRoleSource.Creds,
)
cfg.Credentials = stscreds.NewCredentials(
&Session{
Config: &cfgCp,
Handlers: handlers.Copy(),
},
sharedCfg.AssumeRole.RoleARN,
func(opt *stscreds.AssumeRoleProvider) {
opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName
if len(sharedCfg.AssumeRole.ExternalID) > 0 {
opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
}
// MFA not supported
},
)
} else if len(sharedCfg.Creds.AccessKeyID) > 0 {
cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
sharedCfg.Creds,
)
} else {
// Fallback to default credentials provider, include mock errors
// for the credential chain so user can identify why credentials
// failed to be retrieved.
cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
Providers: []credentials.Provider{
&credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
&credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
defaults.RemoteCredProvider(*cfg, handlers),
},
})
}
}
}
示例10: KMS
func (c *KMSCredential) KMS() security.KMS {
config := aws.NewConfig().WithCredentials(credentials.NewCredentials(c)).WithRegion(c.Region)
session := session.New(config)
return &KMS{
kms: kms.New(session),
keyID: c.KeyID,
}
}
示例11: NewVaultCredentials
func NewVaultCredentials(k keyring.Keyring, profile string, opts VaultOptions) (*VaultCredentials, error) {
provider, err := NewVaultProvider(k, profile, opts)
if err != nil {
return nil, err
}
return &VaultCredentials{credentials.NewCredentials(provider), provider}, nil
}
示例12: connect
func connect(profile string) *route53.Route53 {
return route53.New(&aws.Config{
Region: aws.String("eu-west-1"),
Credentials: credentials.NewCredentials(&credentials.SharedCredentialsProvider{
Profile: profile,
}),
})
}
示例13: Get
func (dynamoDBSource *DynamoDBSource) Get() (map[string]interface{}, error) {
config := defaults.Config()
if dynamoDBSource.AccessKey != "" {
config = config.WithCredentials(credentials.NewCredentials(&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: dynamoDBSource.AccessKey,
SecretAccessKey: dynamoDBSource.SecretKey,
},
}))
}
if dynamoDBSource.Endpoint != "" {
config = config.WithEndpoint(dynamoDBSource.Endpoint)
}
if dynamoDBSource.Region != "" {
config = config.WithRegion(dynamoDBSource.Region)
} else {
config = config.WithRegion("us-west-1")
}
client := dynamodb.New(session.New(config))
tableName := aws.String(dynamoDBSource.Table)
describeTableInput := &dynamodb.DescribeTableInput{TableName: tableName}
if _, err := client.DescribeTable(describeTableInput); err != nil {
return nil, err
}
if err := client.WaitUntilTableExists(describeTableInput); err != nil {
return nil, err
}
key := dynamoDBSource.Key
response, err := client.GetItem(&dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"key": {S: aws.String(key)},
},
TableName: tableName,
ConsistentRead: aws.Bool(true),
})
if err != nil {
return nil, err
}
result := make(map[string]interface{})
err = dynamodbattribute.ConvertFromMap(response.Item, &result)
delete(result, key)
return result, err
}
示例14: newScheduler
func newScheduler(t testing.TB) *ecs.Scheduler {
creds := &credentials.EnvProvider{}
if _, err := creds.Retrieve(); err != nil {
t.Skip("Skipping ECS test because AWS_ environment variables are not present.")
}
config := defaults.DefaultConfig.WithCredentials(credentials.NewCredentials(creds))
return ecs.NewScheduler(config)
}
示例15: CredChain
// CredChain returns the default credential chain.
//
// Generally you shouldn't need to use this method directly, but
// is available if you need to reset the credentials of an
// existing service client or session's Config.
func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials {
return credentials.NewCredentials(&credentials.ChainProvider{
VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
Providers: []credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
RemoteCredProvider(*cfg, handlers),
},
})
}