github.com/aavshr/aws-sdk-go@v1.41.3/service/rds/rdsutils/connect.go (about) 1 package rdsutils 2 3 import ( 4 "net/http" 5 "strings" 6 "time" 7 8 "github.com/aavshr/aws-sdk-go/aws/credentials" 9 "github.com/aavshr/aws-sdk-go/aws/signer/v4" 10 ) 11 12 // BuildAuthToken will return an authorization token used as the password for a DB 13 // connection. 14 // 15 // * endpoint - Endpoint consists of the port needed to connect to the DB. <host>:<port> 16 // * region - Region is the location of where the DB is 17 // * dbUser - User account within the database to sign in with 18 // * creds - Credentials to be signed with 19 // 20 // The following example shows how to use BuildAuthToken to create an authentication 21 // token for connecting to a MySQL database in RDS. 22 // 23 // authToken, err := BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds) 24 // 25 // // Create the MySQL DNS string for the DB connection 26 // // user:password@protocol(endpoint)/dbname?<params> 27 // connectStr = fmt.Sprintf("%s:%s@tcp(%s)/%s?allowCleartextPasswords=true&tls=rds", 28 // dbUser, authToken, dbEndpoint, dbName, 29 // ) 30 // 31 // // Use db to perform SQL operations on database 32 // db, err := sql.Open("mysql", connectStr) 33 // 34 // See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html 35 // for more information on using IAM database authentication with RDS. 36 func BuildAuthToken(endpoint, region, dbUser string, creds *credentials.Credentials) (string, error) { 37 // the scheme is arbitrary and is only needed because validation of the URL requires one. 38 if !(strings.HasPrefix(endpoint, "http://") || strings.HasPrefix(endpoint, "https://")) { 39 endpoint = "https://" + endpoint 40 } 41 42 req, err := http.NewRequest("GET", endpoint, nil) 43 if err != nil { 44 return "", err 45 } 46 values := req.URL.Query() 47 values.Set("Action", "connect") 48 values.Set("DBUser", dbUser) 49 req.URL.RawQuery = values.Encode() 50 51 signer := v4.Signer{ 52 Credentials: creds, 53 } 54 _, err = signer.Presign(req, nil, "rds-db", region, 15*time.Minute, time.Now()) 55 if err != nil { 56 return "", err 57 } 58 59 url := req.URL.String() 60 if strings.HasPrefix(url, "http://") { 61 url = url[len("http://"):] 62 } else if strings.HasPrefix(url, "https://") { 63 url = url[len("https://"):] 64 } 65 66 return url, nil 67 }