How can I send authentication token in header of a POST request from Django Template - django-templates

I have an API call working fine on:
curl -H "Content-Type: application/json" -H "Authorization: Token d070b44498fd12728d1e1cfbc9aa5f195600d21e" http://localhost:8000/api/subscribers/
It gives me the list of all subscribers. I want to create a Django template to send the request to subscribers. I am not able to send:
-H "Authorization: Token d070b44498fd12728d1e1cfbc9aa5f195600d21e"
from my template.

import requests
headers={'Content-Type':'application/json', 'Authorization':'Token d070b44498fd12728d1e1cfbc9aa5f195600d21e'}
r = requests.get('http://localhost:8000/api/subscribers/', headers=headers)

Why don't you use AJAX to send this? Call the JS function whenever you want to make the request.
$.ajax({
type: "POST",
url: url,
headers: {
'Token': 'your_token_here'
},
data: {
'body': 'value'
}
}).done(function (data) {
console.log("API call successfull : ", data);
});

Ajax is one of the simple ways to do an API call from django template.
See the example below.
$.ajax({
type: 'GET',
url: 'http://localhost:8000/api/subscribers/',
headers: {'Authorization': 'Token d070b44498fd12728d1e1cfbc9aa5f195600d21e'},
success:function(response) {
// on success
},
error: function() {
// on error
}
});
In angularJs we can call API using $http. See the example below,
$http.get("http://localhost:8000/api/subscribers/",
{headers: {'Authorization': 'Token d070b44498fd12728d1e1cfbc9aa5f195600d21e',
'Content-Type':'application/json'}
}).then(function(response) {
// on success
},
function(data) {
// on error
});

Related

Issue sending in method to UrlFetchApp.fetch in GAS

Stupid question here, but I am pulling my hair out (i'm bald) as to what I could possibly be doing wrong. I am doing a UrlFetchApp.fetch in google app scripts:
var result = UrlFetchApp.fetch(url, { headers: headers });
When using this as my headers, it works:
var headers = {
Authorization: 'Bearer ' + getAccessToken()
}
Now I need to pass in 'method' as 'PUT' instead of the default of 'GET' (above), and and trying like this:
var headers = {
method : 'put',
headers : {
Authorization: 'Bearer ' + getAccessToken()
}
}
When I try sending this, it is not finding the token:
Exception: Request failed for https://api.spotify.com returned code 401. Truncated server response: {
"error": {
"status": 401,
"message": "No token provided"
}
How can I format the headers so that I can pass in the Authorization with token and also pass in 'method' as 'PUT'?
I see in the URLFetchApp.Fetch documentation for Google, that this is passed into options:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
headers Object a JavaScript key/value map of HTTP headers for the request
method String the HTTP method for the request: get, delete, patch, post, or put. The default is get.
Thank you so much for any help!
phi
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script. Ref And, from I know the call works with a simple GET method, your access token is valid.
curl --request PUT \
--url https://api.spotify.com/v1/me/player/play \
--header 'Authorization: ' \
--header 'Content-Type: application/json' \
--data '{
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
}'
In this case, how about the following sample script?
Sample script:
Please modify data for your actual situation.
var data = {
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
};
var options = {
method: 'put',
headers: { "Authorization": 'Bearer ' + getAccessToken() },
contentType: "application/json",
payload: JSON.stringify(data)
};
var url = "https://api.spotify.com/v1/me/player/play";
var res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
Note:
I think that this request is the same as the curl command. But if an error occurs, please check the access token and the values in data, again.
References:
Start/Resume Playback
fetch(url, params)

Axios post request results in 400 - Bad request

I test an API with Postman and want to write a request with axios. This is what it looks like in Postman and it works fine.
This is my code in javascript:
axios.post('http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token', null,
{ params: {
grant_type : "password",
username: "test",
password: "password",
client_id: "admin-cli"
},
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})
This results in the following error:
POST http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token?grant_type=password&username=test&password=password&client_id=admin-cli 400 (Bad Request)
I also tried to use curl, which also works:
curl -X POST http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token -H 'Content-Type: application/x-www-form-urlencoded' -d 'grant_type=password&username=test&password=password&client_id=admin-cli'
I guess there might be an error in my axios code, but I donĀ“t know what might have gone wrong :-(
In your axios request you've send your data as parameters instead of form data.
Have a look at this thread to see how to send form data: axios post request to send form data
You gotta send in the second param exactly what you're sending into params;
So the new request would be something like this:
const data = {
grant_type: "password",
username: "test",
password: "password",
client_id: "admin-cli"
}
const url = 'http://127.0.0.1:8080/auth/realms/master/protocol/openid-connect/token'
axios.post(
url,
data, // data in the second param
{
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
}).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
})

VueJs axios unauthorized POST request with Authorization header

I want to send POST with authorization to my REST api, but keep getting unauthorized. Everything works in postman, I have CORS enabled on the server.
axios
.post("/api/listings", {
headers: {
'Authorization': 'Bearer ' + this.token,
}
The header seems to appear to request payload in chrome debuggin tools.
I get the token from localStorage and it is definitely there.
My issue was that the header was being sent as an object in request body and not as a header.
Fixed the issue using this code:
axios
.request({
url: "api/listings",
method: "POST",
headers: {
Authorization: "Bearer " + this.token,
},
data:{
ListingName: this.name
}
})
.then((response) => {
console.log(response);
});
}

Cypress: Where does the authentication token go for an API request?

I am trying to request data through an API that requires authentification. I have the token and I know how to implement it using a manual tool such as postman...
How do I format the authentication using Cypress?
it('GET - read', () => {
cy.request({
method: 'GET',
url: 'https://mailtrap.io/api/v1/inboxes/123/messages?page=1&last_id=&useremail',
headers: {
Key: 'Api-Token',
Value: '1234'
}
})
})
})
Response:
The response we got was:
Status: 401 - Unauthorized
As per the Mailtrap documentation, sending an header Api-Token: {api_token} should send authenticated requests. You can write:
cy.request({
method: 'GET',
url: 'https://mailtrap.io/api/v1/inboxes/123/messages?page=1&last_id=&useremail',
headers: {
'Api-Token': 'Your Token value' //Replace with real token
},
failOnStatusCode: false
}).then((res) => {
expect(res.status).to.equal(200) //Replace with releveant 2xx response code
})

Authorization Header - Javascript Vuejs

I have a backend that performs BASIC authentication. I am passing the username/password encoded in curl as follows
curl -D- -X GET -H "Authorization: Basic cmFtcmFtOnBhc3N3b3Jk" -H "Content-Type: application/json" "http://localhost:9000/users/login"
and It works fine
Whereas in vue.js using vue-resource I am trying to do the same using
var options = {
url: 'http://localhost:9000/users/login',
method: 'GET',
headers:
{
'Authorization': 'Basic cmFtcmFtOnBhc3N3b3Jk'
}
}
context.$http(options).then(res => {
if (res.ok) {
cb({ authenticated: true })
} else {
cb({ authenticated: false })
}
})
But it is not getting authenticated. The request information i got from devtools is as follows
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en;q=0.8,fr;q=0.6,en-US;q=0.4
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Connection:keep-alive
DNT:1
Host:localhost:9000
Origin:http://evil.com/
Referer:http://localhost:8080/Login
I do not see the authorization information being passed to the server. Am i doing something wrong ? Note : Both server and client are on localhost.
Thanks
vue-resource is retired so I don't think you should use it anymore. Instead, how about you use fetch instead as suggested and see if it works:
fetch('http://localhost:9000/users/login', {
method: 'POST',
headers: new Headers({
'Authorization: Basic cmFtcmFtOnBhc3N3b3Jk',
'Content-Type': 'application/json'
}),
body: JSON.stringify(req.body.payload)
})