Making POST request in Go with formdata and authentication - go

I'm currently trying to interface with an OAuth api with the example curl command curl -u {client_id}:{client_secret} -d grant_type=client_credentials https://us.battle.net/oauth/token. My current go file is:
package main
import (
"bytes"
"fmt"
"mime/multipart"
"net/http"
)
func checkErr(err error) bool {
if err != nil {
panic(err)
}
return true
}
func authcode(id string, secret string, cli http.Client) string {
//un(trace("authcode"))
var form bytes.Buffer
w := multipart.NewWriter(&form)
_, err := w.CreateFormField("grant_type=client_credentials")
checkErr(err)
req, err := http.NewRequest("POST", "https://us.battle.net/oauth/token", &form)
checkErr(err)
req.SetBasicAuth(id, secret)
resp, err := cli.Do(req)
checkErr(err)
defer resp.Body.Close()
json := make([]byte, 1024)
_, err = resp.Body.Read(json)
checkErr(err)
return string(json)
}
func main() {
//un(trace("main"))
const apiID string = "user"
const apiSecret string = "password"
apiClient := &http.Client{}
auth := authcode(apiID, apiSecret, *apiClient)
fmt.Printf("%s", auth)
}
When I run this I get a response of {"error":"invalid_request","error_description":"Missing grant type"}
For reference, the api flow states:
"To request access tokens, an application must make a POST request with the following multipart form data to the token URI: grant_type=client_credentials
The application must pass basic HTTP auth credentials using the client_id as the user and client_secret as the password."
and the expected response is a json string containing an access token, token type, expiration in seconds, and the scope of functions available with said token

From curl manual we have:
-d, --data <data>
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and
presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to
-F, --form.
Note the content-type application/x-www-form-urlencoded part.
as opposed to:
-F, --form <name=content>
(HTTP SMTP IMAP) For HTTP protocol family, this lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to
POST data using the Content-Type multipart/form-data according to RFC 2388.
Therefore based on your curl, mime/multipart is probably not what you're looking for and you should be using Client.PostForm, from the manual of which we have:
The Content-Type header is set to application/x-www-form-urlencoded. To set other headers, use NewRequest and Client.Do.

Related

Golang google client api, how to get the user information with `Userinfo` struct

I am currently building a backend Rest API with Golang to handle HTTP requests from a mobile application. One of the features that I am now implementing is a signup/login by using an external provider, e.g., Google, Apple, etc.
For Google, I've read this article on how to authenticate with a backend server. The main idea is to send a token id to the backend via a POST endpoint and validate the content of the Token. Once the Token is validated, I can retrieve the user information from the backend and create an account (if it does not exist).
So far, with the oath2 Golang package, I can validate the Token like so:
func verifyIdToken(idToken string) error {
ctx := context.Background()
oauth2Service, err := oauth2.NewService(ctx, option.WithoutAuthentication())
if err != nil {
return err
}
tokenInfoCall := oauth2Service.Tokeninfo()
tokenInfoCall.IdToken(idToken)
tokenInfo, err := tokenInfoCall.Do()
if err != nil {
e, _ := err.(*googleapi.Error)
return e
}
fmt.Println(tokenInfo.Email)
return nil
}
PLEASE NOTE: To obtain the token Id, I am using the Oauth playground, and I set these scopes:
https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
opened
After searching on oauth2, I noticed a type UserInfo containing all the info I need. However, the tokenInfo object does not return all the information from the user, such as first name and last name. But, I'm having some difficulty on how to get UserInfo.
In short, I created a function called getUserInfo like so:
func getUserInfo(service *oauth2.Service) (*oauth2.Userinfo, error) {
userInfoService := oauth2.NewUserinfoV2MeService(service)
userInfo, err := userInfoService.Get().Do()
if err != nil {
e, _ := err.(*googleapi.Error)
fmt.Println(e.Message)
return nil, e
}
return userInfo, nil
}
NOTE: I called the getUserInfo within the verifyIdToken
userInfo, err := getUserInfo(oauth2Service)
However, I'm always getting this 401 error:
googleapi: Error 401: Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie or other valid authentication credential.
See https://developers.google.com/identity/sign-in/web/devconsole-project.,
unauthorized
With that, I'm not sure what to do.
I think you have found the answer to your question for a long time, but I still leave my solution here.
The UserinfoService doesn't actually pass a token inside. To do this, you can use code like this:
import "google.golang.org/api/googleapi"
token := "ya29.a0Aa4xrXMAp..."
userInfo, err := userInfoService.Get().Do(googleapi.QueryParameter("access_token", token))
if err != nil {
e, _ := err.(*googleapi.Error)
fmt.Println(e.Message)
return nil, e
}

Golang: Getting the response-redirect URL from an HTTP response

I'm trying to make a HTTP request using http.Get(url) in Go and I want to open the response in a browser. I'm using browser.OpenURL() to launch the system browser, but I cannot figure out how to obtain the response url.
In Python, using the requests library, it is an attribute of the response object.
I can obtain and open it in a browser (using the browser library) like so:
response = requests.get(endpoint)
browser.open(response.url)
How can I accomplish this using http/net library in Go? The response object is a struct that doesn't contain that attribute.
I am trying to call the Spotify API to authenticate an app, and this requires opening a browser window for user input. So far I've got this:
func getAuth(endpoint *url.Url) {
request, _ := http.NewRequest("GET", endpoint.string(), nil)
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
panic(err)
}
headers := resp.Header
page, _ := ioutil.ReadAll(resp.Body)
Where can I obtain the response URL or how can I handle the response so that it opens it in a browser?
Go will update the Request struct on the response if there is a redirect.
resp.Request.URL is what you are looking for.
// Request is the request that was sent to obtain this Response.
// Request's Body is nil (having already been consumed).
// This is only populated for Client requests.
Request *Request
Just get the redirect URL from response header.
redirectURL := resp.Header.Get("Location")

How to make a post request to urlscanio using Go?

What I'm doing is trying to submit a URL to scan to urlscan.io. I can do a search but have issues with submissions, particularly correctly sending the right headers/encoded data.
from their site on how to submit a url:
curl -X POST "https://urlscan.io/api/v1/scan/" \
-H "Content-Type: application/json" \
-H "API-Key: $apikey" \
-d "{\"url\": \"$url\", \"public\": \"on\"}"
This works to satisfy the Api key header requirement but
req.Header.Add("API-Key", authtoken)
This is my attempt that fails
data := make(url.Values)
data.Add("url", myurltoscan)
The URL property I have struggled with tremendously.
This is my error:
"message": "Missing URL properties",
"description": "The URL supplied was not OK, please specify it including the protocol, host and path (e.g. http://example.com/bar)",
"status": 400
url.Value is a map[string][]string containing values used in query parameters or POST form. You would need it if you were trying to do something like:
curl -X GET https://urlscan.io/api/v1/scan?url=<urltoscan>
or
curl -X POST -F 'url=<urltoscan>' https://urlscan.io/api/v1/scan
See documentation https://golang.org/pkg/net/url/#Values.
To send a regular POST request with JSON data, you can encode the JSON as bytes and send with http.Post:
var payload = []byte(`{"url":"<your-url>","public":"on"}`)
req, err := http.NewRequest("POST", url,
bytes.NewBuffer(payload))
req.Header.Set("API-Key", authtoken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()

Google Calendar API invalid_grant getting token (Golang)

I'm trying to retrieve an access token, in order to authenticate users using Oauth2. I'm using mostly code found on google's HOW-TO page for using the Calendar API with golang. The problem is that whenever I try to obtain a token, google sends back this:
Response: {
"error" : "invalid_grant"
}
With the error oauth2: cannot fetch token: 400 Bad Request
As I said, I'm using some code got from google's howto, just slightly modified to fit my needs.
//Somewhere...
authURL = config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
//Somewhere else...
func getClient(ctx context.Context, config *oauth2.Config, code string) *http.Client {
cacheFile := tokenCacheFile()
tok, err := tokenFromFile(cacheFile)
if err != nil {
log.Printf("Google auth code not cached. Obtaining from the web...")
tok, err = getTokenFromWeb(code) //This returns an error
if err == nil {
log.Printf("Got token!")
saveToken("calendar-go-quickstart.json", tok)
} else { //Prevent saving token when error
log.Printf("Couldn't get OAUTH2 token! %s", err)
}
}
return config.Client(ctx, tok)
}
The error occurs at "getTokenFromWeb(code)" (if I understood correctly, code must be some random string, no matter its value, it just needs to be the same during the whole process).
This is the problematic code:
func getTokenFromWeb(code string) (*oauth2.Token, error) {
tok, err := config.Exchange(context.Background(), code)
return tok, err
}
After executing, what I see is that error. I even get the exact same error when trying to copy-paste google's own example code!
Any idea? I really can't find a solution online.
Extra details: using IRIS web framework; using the latest version of google calendar api; using the latest version of Golang; I've created a client ID for OAuth2 on Google Cloud Console; The website has got a trusted SSL cert; it listens on port 80 (HTTP) and 4433 (HTTPS);
Here is Google's example:
// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}
...
}
code is an authorization code given to the user after visiting the displayed link. fmt.Scan() is going to scan the input from the user.
If you're going to be acting on a different user's behalf, you will have to do something similar to this example.
If you're only acting as yourself, you should be able to authenticate as yourself without the code.
Either way, code cannot be a random string.

Not able to pass Bearer token in headers of a GET request in Golang

I am using oauth2 to access a third party API. I can get the access token alright, but when I try to call the API by passing the bearer token in the request headers it gives me 401 (Unauthorized) error. Although it works well when I try to do it via POSTMAN by passing headers as (Authorization: Bearer ). But it does not work using go.
Here is the code sample.
url := "http://api.kounta.com/v1/companies/me.json"
var bearer = "Bearer " + <ACCESS TOKEN HERE>
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("authorization", bearer)
client := urlfetch.Client(context)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
writer.Write([]byte(body)) // Gives 401 Unauthorized error, though same works using POSTMAN
I was able to solve the problem. Actually the problem was two way.
1) The API end point was doing a redirect (302), which was causing a 302 response and then the other API was being called.
2) GO by default does not forward the headers, thus my bearer token was being lost in the middle.
FIX:
I had to override the client's CheckRedirect function and manually pass the headers to the new request.
client.CheckRedirect = checkRedirectFunc
Here is how I forwarded the headers manually.
func checkRedirectFunc(req *http.Request, via []*http.Request) error {
req.Header.Add("Authorization", via[0].Header.Get("Authorization"))
return nil
}

Resources