InvalidClientTokenId: The security token included in the request is invalid - go

I make project Go gin
I make send an SMS message for user phone number
When the implementation of the code is completed and the program is executed, the following error occurs
InvalidClientTokenId: The security token included in the request is invalid.
I think the error course missing token.
but I don`t know get how to get token
this below my code
func PushSms(phoneNumber, code string) error {
fmt.Println("create session")
AccessKey := os.Getenv("AWS_ACCESS_KEY")
SecretAccessKey := os.Getenv("AWS_SECRET_ACCESS_KEY")
sess, err := session.NewSession(&aws.Config{
Region: aws.String("ap-northeast-1"),
Credentials: credentials.NewStaticCredentials(AccessKey, SecretAccessKey, ""),
})
if err != nil {
log.Fatalln(err)
}
svc := sns.New(sess)
input := &sns.PublishInput{
Message: aws.String("test" + code),
PhoneNumber: aws.String(phoneNumber),
}
result, err := svc.Publish(input)
if err != nil {
log.Println(err)
}
fmt.Println(result)
return nil
}
thanks

this issue change part of session.NewSession change code
sess, err := session.NewSession(&aws.Config{
Region: aws.String("ap-northeast-1"),
Credentials: credentials.NewStaticCredentials(AccessKey, SecretAccessKey, ""),
})
to
.env
AWS_ACCESS_KEY=access_key
AWS_SECRET_ACCESS_KEY=secret_access_key
AWS_REGION=ap-northeast-1
sess, err := session.NewSession()
thanks

Related

Go googleapis/google-api-go-client gmail, blank response on some requests?

func Callback(w http.ResponseWriter, r *http.Request){
ctx := context.Background()
state := r.FormValue("state")
code := r.FormValue("code")
client := getClient(state, code)
srv, err := gmail.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
user := "me"
result, err := srv.Users.Messages.List(user).Do()
// result, err := srv.Users.GetProfile(user).Do() // This part works
if err != nil {
log.Fatalf("Unable to retrieve labels: %v", err)
}
// fmt.Fprintf(w, "Labels: %s", result.EmailAddress) // This part works
snippet := result.Messages[0].Snippet
fmt.Fprint(w, string(snippet)) // For some reason give a blank output
}
Gmail API Go Client
Some parts like the snippet and the body do print out an output.
But the profile and listing of labels works.
I'm not sure what I'm doing incorrectly :(

How to send a message with discord oAuth API

I have a go api, and we are trying to send a message on a channel thanks to oAuth2.
So far, we retrieved the token and we can display some user information (email, username etc...)
we are trying to retrieve some message, but we have an "unauthorized" error.
I read some documentation about permissions, i think i have to do somethings with header, but i'm totally new to golang.
can you help me? :)
this is the code :
func HelloDiscord(w http.ResponseWriter, r *http.Request){
conf := &oauth2.Config{
RedirectURL: "http://localhost:8080/auth/discord",
ClientID: "clientid",
ClientSecret: "clientsecret",
Scopes: []string{discord.ScopeIdentify},
Endpoint: discord.Endpoint,
}
token, _ := conf.Exchange(context.Background(), r.FormValue("code"))
fmt.Println(token)
message, err := conf.Client(context.Background(), token).Get("https://discord.com/api/channels/1021410887191507004/messages")
fmt.Println("message;")
fmt.Println(message)
if err != nil || message.StatusCode != 200 {
w.WriteHeader(http.StatusInternalServerError)
if err != nil {
w.Write([]byte(err.Error()))
} else {
w.Write([]byte(message.Status))
}
return
}
defer message.Body.Close()
body, err := ioutil.ReadAll(message.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Write(body)
}
thanks a lot

go jwt token fromJson invalid memory address or nil pointer dereference

I am trying to access google sheet via service account using google.JWTConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets) by a reading a service account json file.
Here's how I am trying to access
b, err := ioutil.ReadFile("keys.json")
if err != nil {
log.Error()
}
config, err := google.JWTConfigFromJSON(b, "https://www.googleapis.com/auth/spreadsheets")
if err != nil {
log.Error()
}
client := config.Client(oauth2.NoContext)
sheetClient, err := sheets.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Error()
}
But on running the above code getting, any idea where I am making wrong.
"error": "runtime error: invalid memory address or nil pointer dereference"
But when I try with jwt.Config method it's working fine
conf := &jwt.Config{
Email: "x#y.com",
PrivateKey: []byte("-----BEGIN PRIVATE KEY-----\nxxxxx\n-----END PRIVATE KEY-----\n"),
PrivateKeyID: "xxxxxxxxxx",
TokenURL: "https://oauth2.googleapis.com/token",
Scopes: []string{
"https://www.googleapis.com/auth/spreadsheets",
},
}
client := conf.Client(oauth2.NoContext)
sheetClient, err := sheets.New(client)

googleapi: Error 403: Request had insufficient authentication scopes. More details: Reason: insufficientPermissions, Message: Insufficient Permission

I am trying to send an email with Gmail API. But I get this error
googleapi: Error 403: Request had insufficient authentication scopes.
More details:
Reason: insufficientPermissions, Message: Insufficient Permission
I think it might bee related to config, I also followed google's quickstart for Go
here is the getClient func:
func getClient(config *oauth2.Config) *http.Client {
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
here is the code send:
case "pass":
templateData := struct {
VerPass string
}{
VerPass: cont1,
}
emailBody, err := parseTemplate("ver.html", templateData)
if err != nil {
fmt.Println("Parse Err")
return false, err
}
var message gmail.Message
emailTo := "To: " + to + "\r\n"
subject := "Subject: " + sub + "\n"
mime := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
msg := []byte(emailTo + subject + mime + "\n" + emailBody)
message.Raw = base64.URLEncoding.EncodeToString(msg)
// Send the message
fmt.Println("OOOOOYYYYY")
//here is the problem
b, err := ioutil.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
// If modifying these scopes, delete your previously saved token.json.
config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
srv, err := gmail.New(client)
if err != nil {
log.Fatalf("Unable to retrieve Gmail client: %v", err)
}
//GmailService
res, err := srv.Users.Messages.Send("me", &message).Do() // change me
if err != nil {
fmt.Println("Res Err")
fmt.Println(err)
return false, err
}
fmt.Println(res)
I tried for config, err := google.ConfigFromJSON(b, gmail.MailGoogleComScope), I tried using GmailReadonlyScope and gmail.GmailSendScope, but I got the same error.
Request had insufficient authentication scopes.
Means that the user who has authorized your application to access their data has not granted your application enough permissions in order to do what you are trying to do.
You apear to be using the user.message.send method. If you check the documentation you will find that that method requires that the user be authorized with one of the following scopes.
If you did follow Googles quick start for go then you used gmail.GmailReadonlyScope as a scope which will only give you read only access.
However your code now apears to contain the mail.MailGoogleComScope scope which should work however i am guessing you neglected to reauthorize the application. And didn't see the comment in the tutorial
// If modifying these scopes, delete your previously saved token.json.
I suggest you deleted token.json and then the application will require that you authorize it again and your code should work with the elevated permissions.

How to pull image from custom docker registry with golang?

Using docker sources how to pull image from custom registry? As a result of using such code
// Prepare auth registry for usage
func (app *App) PrepareRegistry() error {
app.AuthConfig = types.AuthConfig{
Username: Username,
Password: Password,
ServerAddress: DefaultServer,
}
resp, err := app.Client.RegistryLogin(context.Background(), app.AuthConfig)
if err != nil {
panic(err)
}
fmt.Println(resp.Status)
if resp.IdentityToken != "" {
app.AuthConfig.IdentityToken = resp.IdentityToken
}
app.AuthConfigEncoded, err = command.EncodeAuthToBase64(app.AuthConfig)
return err
}
func (app *App) ImagePull() error {
opts := types.ImagePullOptions{
All: true,
RegistryAuth: app.AuthConfigEncoded,
PrivilegeFunc: registryAuthentication(app.Name),
}
responseBody, err := app.Client.ImagePull(context.Background(), app.Name, opts)
defer responseBody.Close()
if err != nil {
return err
}
return nil
}
I am still getting the error
Login Succeeded
panic: Error response from daemon: Get https://registry-1.docker.io/v2/shalakhin/blender/tags/list: unauthorized: incorrect username or password
While ServerAddress is registry.gitlab.com, not registry-1.docker.io
Did you check identity token? That might cause an authentication problem.
A suggestion:
Docker client
This works fine, as I can see you did not specify the endpoint. I think you should add this info.
authConfig := types.AuthConfig{
Username: "username",
Password: "password",
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
panic(err)
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
out, err := cli.ImagePull(ctx, "alpine", types.ImagePullOptions{RegistryAuth: authStr})
if err != nil {
panic(err)
}

Resources