How to pass JsonWebToken(JWT) through AngularJS - angularjs

I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.
I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman:
my JWT token authentication script is here:
// Uses http.get() to load data from a single API endpoint
list() {
return this.http.get('api/', this.getHttpOptions());
}
// helper function to build the HTTP headers
getHttpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
})
};
}
I tried using http.get() here. Thanks in advance!
the error will be like:
401 (Unauthorized)

Try this:
list() {
return this.http.get('api/', { this.getHttpOptions() });
}
getHttpOptions() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
});
return headers;
}

Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.
this.http.get('api/', { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token,
'Authenticationtoken': 'JWT ' + this._userService.token
}) });

Thanks guys,
I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend.
https://www.youtube.com/watch?v=OIbndrrUYiY

Related

PostMan vs Axios on Including authorization Header while Making requests

Making a postman request to an endpoint with some Header
when I run the below code
function authenticateToken(req,res,next){
const bearerHeader = req.headers["authorization"]
console.log(req.headers)
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}
else{
console.log('hihihi')
res.sendStatus(403);
}
}//a middleware function used for JWT
it's returning everything as I expected like below
but the problem is, I need to connect it with my react. So I am making Axios request but it's not working
I tried giving headers using interceptors like below
axios.interceptors.request.use(
config=>{
config.headers.authorization = `Bearer ${token}`
return config
},
error =>{
return Promise.reject(error)
return error
}
)
axios.post("http://localhost:3000/stockdata/post",{
// some data
})
I also tried giving like below
axios.post(url,{data},{headers:{
'authorization': "Bearer "+ token,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
i also tried with 'Authorization': "Bearer "+ token and without quotes Authorization: "Bearer "+token and also tried one time by removing Accept and content-type . but this is what am getting
The problem is only with the Axios request, not any other thing. what's going wrong in it?
I think when you tried with axios, there will be two requests as it has CORS issue. This issue comes if the client host is different from server host.
The first request is type OPTIONS to know whether to allow the POST or not and second request is actual POST.
What you are seeing might be of request type OPTIONS. This you can verify by checking network tab in the browser. This won't happen in POSTMAN. You could add CORS plugin to your server to resolve this issue.
The attached screenshot shows POSTMAN sending request to http://localhost:3000/stockdata/post
However, the axios request is being sent to http://localhost:3000/stockdata
Adjusting the request end-point may help resolve the issue.
After adjusting the target URL, the following code example may be tried to get the axios response:
import axios from 'axios'
let url = "http://localhost:3000/stockdata/post"
let data = {}
let token = "xyz"
let config = {"headers": {
"Authorization": "Bearer " + token,
"content-type": "application/json"
}
}
axios.post(url, data, config)
.then((response) => {
console.log(response)
}, (error) => {
console.log(error)
}
)
More information:
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

Auth header not being set with Axios PUT request

I am trying to set the header in an Axios PUT request with my Auth token, but when I view the call on the server (running my UI app from localhost) the header is null. I've used this same pattern with Axios and GET, POST, and DELETE calls without issue. Is there anything different with respect to a PUT call and the header?
Below is the code:
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})
In order to add headers in POST or PUT, you need a third argument which will contain headers keys
axios.put(url, data, config)
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{}, // post/put body
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})

React native - FETCH - Authorization header not working

I made a server query via an app developed using react-native. I used fetch API and it turns out any query with authorization header not working. POST and GET method REQUESTS that don't expect Authorization headers at the server side works well. Some Queries at the server side are protected with authorization and when I make such queries including authorization header, I always get '401:unauthorized' error.
But such queries works well with POSTMAN. Any suggestions here would be of great help.
getThingsApi() {
let uri = "https://example.com/things/";
let req = {
method: "GET",
credentials: "include",
//mode: "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//'Access-Control-Request-Method': 'GET',
//'Access-Control-Request-Headers': 'origin, x-requested-with',
'Origin': '',
'Host':'example.com',
'authorization': 'Basic '+Base64.btoa('aaa:bbb'),
'Cache-Control': 'no-cache'
}
};
fetch(uri, req)
.then(response => response.json())
.then(responseJson => {
console.log("ResponseAxis::" + JSON.stringify(responseJson));
console.log("ResponseAxis::" + JSON.stringify(responseJson));
alert("ResponseAxis::" +JSON.stringify(responseJson));
})
.catch(error => {
console.log("Error::" + JSON.stringify(error));
});
}
Issue is fixed. We used Fetch API and fetch Api converts all headers into lower-case(eg: authorization) and the server side expects upper-case starting letter(eg: Authorization). After changing the server side code to be case-insensitive, everything works fine.

react fetch header not set

I am facing a problem. And the solutions that are accepted by the others, those don't work for me./
I have:
return await fetch(url, {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
},
body: JSON.stringify(bodyObject)
});
But, it seems like no header is set at all.
Cors-header is set, adding mode:'cors' makes no difference.
Am I missing something?
the request:
Accept is empty and Content-Type nor x-test are nowhere to be found.
..
Edit
..
If i need to create new question, do tell me.
New request
So I see that the header is set - thanks to liminal18!-. However, now i want to authorize to an AD.
so now I got:
async callUrl(url, httpMethod, bodyObject) {
try {
var requestObj = {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
'Authorization': 'Basic Uk11bGxlc....'
}
};
if (bodyObject !== undefined){
requestObj.body = JSON.stringify(bodyObject);
}
return await fetch(url, requestObj);
} catch(error){
console.error(error);
}
}
But still get an 401.
I know this is not the clean solution for logging in, but just testing..
Are you sure the request you captured is the correct request?
if you're using CORS there is an OPTIONS post to get the cors allowed methods before react will post/put which might be what you are looking at and not the actual post or put you intended. Where are the CORS headers set?

Meteor Jira POST call

I'm trying to adjust the transition (the status) of an issue in Jira with a POST call. I'm running a Meteor application with a Meteor Backend and a Angular frontend.
Meteor.methods({
performPostCall: function(id, status){
var transitionObject = {
"transition": {
"id": "11"
}
};
var result = HTTP.call('POST', 'https://privateurl/rest/api/2/issue/' + id + '/transitions',
{data: transitionObject},
{headers :{
'Access-Control-Allow-Origin': '*',
'Authorization': 'Basic ******',
'Content-Type': 'application/json',
'Accept': 'application/json'
}});
return result;
}
});
In my frontend, I call the meteor method and handle the callback like this:
Meteor.call('performPostCall', id, status, function(error, success){
if(error){
alert(error);
} else {
alert(success);
}
});
When I press the button that fires the meteor method call, it will this strange and lovely error:
XMLHttpRequest cannot load https://ddp--0266-remoteserverurl/sockjs/info?cb=4bxmv_smgg. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'remoteserverurl' is therefore not allowed access. The response had HTTP status code 503.
But I declared this 'Access-Control-Allow-Origin' in the header, so I don't understand why it is complaining. Can somebody tell me what I do wrong?
According to documentation third parameter should be an object with fields required to make a call, in your code data and headers are different objects.
Proper syntax would be :
HTTP.call('POST', 'https://privateurl/rest/api/2/issue/' + id + '/transitions', {
data: transitionObject,
headers :{
'Access-Control-Allow-Origin': '*',
'Authorization': 'Basic ******',
'Content-Type': 'application/json',
'Accept': 'application/json'
}});
Also, result variable is most likely undefined since you try to do it in synchronous fashion, POST call is asynchronous, make use of fourth parameter (callback) to pass data to client, like:
HTTP.call('POST', 'https://privateurl/rest/api/2/issue/' + id + '/transitions', {
data: transitionObject,
headers :{
'Access-Control-Allow-Origin': '*',
'Authorization': 'Basic ******',
'Content-Type': 'application/json',
'Accept': 'application/json'
}}, function (error, result) {
if (!error) {
return result;
}
});

Resources