i was trying to set up dropbox oauth in my app, the following is the handler for grantapi, the grant api redirects the user to dropbox authentication page its address is localhost:8089/api/grant
func DropboxGrantCodeHandler(w http.ResponseWriter, r *http.Request) {
queryParams := url.Values{}
queryParams.Set("client_id", "myclientid")
queryParams.Set("token_access_type", "offline")
queryParams.Set("response_type", "code")
queryParams.Set("redirect_uri", "http://localhost:8089/api/callback")
url := &url.URL{
Scheme: "https",
Host: "www.dropbox.com",
Path: "/oauth2/authorize",
RawQuery: queryParams.Encode(),
}
http.Redirect(w, r, url.String(), http.StatusSeeOther)
}
it redirects to dropbox oauthpage , i registered my callback api http://localhost:8089/api/callback as my redirect_uri in my dropbox app console.
here in the code i hardcoded clientid . but i can modify my code and recieve clientid in the request, but consider the following scenario, follwing is the my call back api
func DropboxCallBackTokenHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("entered to call back api")
code := r.URL.Query().Get("code")
data := url.Values{}
data.Set("code", code)
data.Set("grant_type", "authorization_code")
data.Set("redirect_uri", "http://localhost:8089/api/callback")
data.Set("client_id", "myclientid")
data.Set("client_secret", "myclientsecret")
url := &url.URL{
Scheme: "https",
Host: "api.dropboxapi.com",
Path: "/oauth2/token",
}
client := &http.Client{}
tokenRequest, err := http.NewRequest(http.MethodPost, url.String(), strings.NewReader(data.Encode())) // URL-encoded payload
if err != nil {
http.Error(w, "error during constructing New Request,error is "+err.Error(), http.StatusInternalServerError)
}
//r.Header.Add("Authorization", "auth_token="XXXXXXX"")
tokenRequest.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(tokenRequest)
if err != nil {
http.Error(w, "error during constructing New Request,error is "+err.Error(), http.StatusInternalServerError)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, "error during reading response,error is "+err.Error(), http.StatusInternalServerError)
}
if resp.StatusCode != http.StatusOK {
http.Error(w, "error response,error is "+string(body), http.StatusInternalServerError)
return
}
var tokenResponse TokenResponse
// Decode the response body into the response variable
if err := json.Unmarshal(body, &tokenResponse); err != nil {
// return response, fmt.Errorf("error decoding response: %v, body: %s", err, string(body))
http.Error(w, "error in unmarshalling,error is "+err.Error(), http.StatusInternalServerError)
}
json.NewEncoder(w).Encode(tokenResponse)
}
actually what my requirement is when dropbox redirects my callback api , i also want to get my clientid and client secret, not as i hardcoded, because i have many dropbox account and i want to get access token of the account which user request.