//Send put request with given params
func SendPostRequest(url string, param map[string]interface{}, authToken string) string{
//to disable security check
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
//Parse to json
jsonValue, _ := json.Marshal(param)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("AuthToken", authToken)
client := &http.Client{}
resp, err := client.Do(req)
}
Here is the JSON file
{"credentials":{"display_name":"win10Test","is_default":"","password":"","username":""},
"defaultschedule":true,"host_info":{"ip":"*.*.*.*"},
"install_agent":false,"is_auth_enabled":false,"is_enabled":true,"is_encrypted":false,
"is_synchable":false,"name":"win10","os_type":"Windows","priority":300,"use_ssl":false}
When I run the code, I am getting the following error
response Status: 403 Forbidden
403 is Forbidden request - https://en.wikipedia.org/wiki/HTTP_403
I think you send wrong authToken
Check it more carefully.
Related
need help in formatting a graphql mutation in java code. In postman it looks like this->.postman
and what I have tried is-> my code and the error I am getting is--> error I am getting. Thanks in advance :-)
Escaping will be language dependent and so I have provided a few examples below based on the sample you provided.
Postman provides a code snippet that exports in various formats
cURL
curl --location --request GET '' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation{\n Create(\n request: \"Xboxx\",\n GoalAmount: 123,\n GoalTargetData: \"15/09/2021\",\n ImagerRef:\"etst ref\"\n ){\n Id\n Name\n GoalAmount\n GoalTargetDate\n ImageRef\n }\n}","variables":{}}'
java
Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.get("")
.header("Content-Type", "application/json")
.body("{\"query\":\"mutation{\\n Create(\\n request: \\\"Xboxx\\\",\\n GoalAmount: 123,\\n GoalTargetData: \\\"15/09/2021\\\",\\n ImagerRef:\\\"etst ref\\\"\\n ){\\n Id\\n Name\\n GoalAmount\\n GoalTargetDate\\n ImageRef\\n }\\n}\",\"variables\":{}}")
.asString();
javascript
//javascript - fetch
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var graphql = JSON.stringify({
query: "mutation{\n Create(\n request: \"Xboxx\",\n GoalAmount: 123,\n GoalTargetData: \"15/09/2021\",\n ImagerRef:\"etst ref\"\n ){\n Id\n Name\n GoalAmount\n GoalTargetDate\n ImageRef\n }\n}",
variables: {}
})
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: graphql,
redirect: 'follow'
};
fetch("", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Go
package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := ""
method := "GET"
payload := strings.NewReader("{\"query\":\"mutation{\\n Create(\\n request: \\\"Xboxx\\\",\\n GoalAmount: 123,\\n GoalTargetData: \\\"15/09/2021\\\",\\n ImagerRef:\\\"etst ref\\\"\\n ){\\n Id\\n Name\\n GoalAmount\\n GoalTargetDate\\n ImageRef\\n }\\n}\",\"variables\":{}}")
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
I am using package "github.com/dgrijalva/jwt-go" in golang to authenticate api hits.
The code for creating a jwt token is:
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.MapClaims{
"email": "test#example.com",
"exp": time.Now().Add(time.Hour * 8760).Unix(),
"role": "customer",
"name": "John Doe",
"ip": 0.0.0.0,
"user_agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0"
"id": 1,
})
tokenString, err := token.SignedString([]byte(config.SignKey))
Following are the steps to use this token:
First login api hits and we call above method to generate token and return this token in the api response.
After that another api hits which contains this token in its headers with "Bearer " string. We decode this token and authenticate it through following code:
bearer := strings.Split(c.Request.Header["Authorization"][0], "Bearer")
bearerToken := strings.TrimSpace(bearer[1])
token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {return config.SignKey, nil})
if err != nil {
c.JSON(200, gin.H{"response": "{error: "err", msg: Session Expired. Please log out and back in to continue2.}",})
c.Abort()
return
}
Now suppose the token was decoded for url: http://SOMEDOMAIN.COM/api/v1/SOMEAPI
from this api I issued another curl command in the format:
"curl --header 'Ip: " + ip + "' --header 'User-Agent: " + userAgent + "' --header 'Authorization: " + token + "' 'http://SOMEDOMAIN.COM/api/v2/ANOTHERAPI'"
This command hits another different api but using the same credentials like token is same what was created from login api.
Both apis with different urls are hosted over same server but different golang project folder.
Now at this time this package does not authenticate the token and gives following error:
{"response":{"code":400,"api_status":10,"message":"Session Expired. Please log out and back in to continue2.","data":{"Inner":{},"Errors":4}}}
I was looking for meaning of error code 4 in this case.
Can anyone please explain what is the meaning of Error: 4 and why it is behaving like this on different api urls?
When I investigated your code,
There is an misuse about your config.SignKey , It seems it was casting []byte while signing token.
But while parsing your token;
{return config.SignKey, nil}
You used default type and didn't cast []byte.
{return []byte(config.SignKey), nil}
I think it is the issue.
I'm getting this error {"ok":false,"error":"no_file_data"} when I try to call the slack API to upload. I already have the specified file in ./log.
robot.respond /upload (.*)/i, (res) ->
app_name = res.match[1]
request = require("request")
fs = require("fs")
channel_name = res.message.room
data = {
channels: channel_name,
filename: "#{app_name}.txt",
file: fs.createReadStream("./log/#{app_name}.txt"),
}
robot.http("https://slack.com/api/files.upload")
.headers(Authorization: 'Bearer slack-token', 'Content-Type': 'application/json')
.post(data) (err, httpRes, body) ->
if err
res.send "#{err}"
return
res.send "#{body}"
This does not work, because the API method files.upload does not support the content type application/json posts.
For your case you need to post as multipart/form-data, with one part containing the file data and one part containing the API parameters including the token.
This code works:
func handleFacebookCallback(w http.ResponseWriter, r *http.Request) {
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
////////////////////////////////////////////////////
Url, err := url.Parse(oauthConf.Endpoint.TokenURL)
if err != nil {
log.Fatal("Parse: ", err)
}
parameters := url.Values{}
parameters.Add("client_id", oauthConf.ClientID)
parameters.Add("client_secret", oauthConf.ClientSecret)
parameters.Add("redirect_uri", "http://localhost:9090/oauth2callback")
parameters.Add("code", code)
Url.RawQuery = parameters.Encode()
resp, err := http.Get(Url.String())
if err != nil {
fmt.Printf("Get: %s\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
defer resp.Body.Close()
But when I replace the part below the marker //////... with:
token, err := oauthConf.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
I get:
oauthConf.Exchange() failed with 'oauth2: cannot fetch token: 400 Bad
Request Response: {"error":{"message":"Missing redirect_uri
parameter.","type":"OAuthException","code":191,"fbtrace_id":"XXXX"}}'
Is the package golang.org/x/oauth2 unable to exchange a code for a token?
I found out what was missing. I apparently need to add the RedirectURLfield in the oauthConfig struct to get Exchange() to work properly. This is not the case for Slack or GitHub but apparently FB is slightly more picky.
var oauthConf = &oauth2.Config{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
RedirectURL: "http://localhost:9090/oauth2callback", /* Fixed! */
Scopes: []string{"public_profile"},
Endpoint: facebook.Endpoint,
}
Having never worked with coffescript before, I'm trying to update the hubot script for jenkins integration. In a nutshell I want to call jenkins, get a result from that call and use it in a subsequent call. Based on the existing code in the hubot script I've added the following function:
jenkinsCrumb = (msg) ->
url = process.env.HUBOT_JENKINS_URL
path = "#{url}/crumbIssuer/api/json"
req = msg.http(path)
if process.env.HUBOT_JENKINS_AUTH
auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
req.headers Authorization: "Basic #{auth}"
req.get() (err, res, body) ->
if err
msg.reply "Jenkins says: #{err}"
else if 200 <= res.statusCode < 400 # Or, not an error code.
msg.reply "#{body}"
body
else if 404 == res.statusCode
msg.reply "Unable to fetch crumb from Jenkins..."
else
msg.reply "Jenkins says: Status #{res.statusCode} #{body}"
When this function is called, the value I want is reported in the variable body. The call to msg.reply properly displays the value in the hubot chat window.
What I would like to do, but can't figure out, is how to have this function return the value of body? I've tried explicitly returning the value of req.get() but it seems that it's returning the full request object.
You can do that by simply adding return body or just body (because of CoffeeScript) to the end of your anonymous function:
jenkinsCrumb = (msg, callback) ->
url = process.env.HUBOT_JENKINS_URL
path = "#{url}/crumbIssuer/api/json"
req = msg.http(path)
if process.env.HUBOT_JENKINS_AUTH
auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
req.headers Authorization: "Basic #{auth}"
req.get() (err, res, body) ->
if err
msg.reply "Jenkins says: #{err}"
else if 200 <= res.statusCode < 400 # Or, not an error code.
msg.reply "#{body}"
body
else if 404 == res.statusCode
msg.reply "Unable to fetch crumb from Jenkins..."
else
msg.reply "Jenkins says: Status #{res.statusCode} #{body}"
# critical part
callback(body)