When user login , it should redirects to homepage and gets posts.
I make api call in react but it returns 401 unauthorized . If I do with same auth header on postman it returns proper data.
const getPosts = async () => {
await axios
.get("/api/post", {
headers: { authorization: "Bearer" + localStorage.getItem("token") },
})
.then((res) => setPosts(res.data));};
useEffect(() => {getPosts();},[]);
Server Side
router.get("/api/post", authToken, async (req: Request, res: Response) => {
const posts = await Post.find({ relations: ["user"] });
return res.json(posts);
});
middleware
const authToken = (req: Request, res: Response, next: NextFunction) => {
const token = req.headers.authorization?.split(" ")[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, "SECRET", (err, decode) => {
if (err) return res.sendStatus(403);
res.locals = { ...res.locals, token: decode };
next();
});
};
You are missing the whitespace in your headers:
headers: { authorization: "Bearer " + localStorage.getItem("token") }
Related
I can get the entire response log using console.log(res) but can't retrieve access_token from it. The response containing access_token looks like this:
accept: [Array],
'content-length': [Array]
}
},
text: '{"access_token":"eyJhbGciOiJS....
I've tried the following:
.end( function (res, err, access_token, refresh_token) {
if (err) console.error(err);
else {
console.log(res)
expect(res).to.have.status(200);
//console.log(res.body)
const token = JSON.stringify.access_token;
// token = res.access_token;
console.log(token)
// let accessToken = await auth.getAccessToken();
// console.log(accessToken);
// assert(accessToken != null, 'token is null');
//var token = body.access_token
//console.log(token + "see on token");
// console.log(`options.access_token: ${options.access_token}`);
This is what I'm getting
UPDATE: By using the below code, parsing and using stringify I'm able to log out the token, but I'm still not able to use the parsed in the next request as header, getting undefined
chai.request(uaaUrl)
.post('/oauth/token')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Accept', '*/*',)
.send(Authuser)
.end(function(err, res, body) {
const eurotoken = JSON.parse(JSON.stringify(res.body.access_token));
console.log('parsedd token', eurotoken);
expect(res).to.have.status(200)
done();
})
it('./health', (done) => {
let eurotoken;
chai.request(euro_url)
.get('/request-statuses')
.set('Content-Type', 'application/x-www-form-urlencoded')
.set('Accept', '*/*',)
.set('Authorization', `Bearer ${eurotoken}` )
.end( function (res, err, body) {
if (err) console.error(err);
else {
expect(res).to.have.status(200)
done();
}
done();
})
});
I am fetching IGDB api on server because I need to go through CORS. I am using async await connected to client side. Everything works fine but I need to pass query like '/?fields=cover.*,name;limit=50;' to https://api.igdb.com/v4/games from client side, not from server. When I am adding a query to client side, it's still showing the query only from server. How I can pass this query from client side? This is my code:
api/example.js
import Cors from "cors";
import initMiddleware from "../../components/init-middleware";
const cors = initMiddleware(
Cors({
methods: ['GET', 'POST', 'OPTIONS'],
})
)
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
}
const remoteServerUrl = 'https://api.igdb.com/v4/games'
export default async function handler(req, res) {
await cors(req, res)
const response = await fetch(remoteServerUrl, settings);
const data = await response.json()
res.json(data)
}
client side
const settings = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Client-ID': 'my_client-id',
'Authorization': 'Bearer my_authorization',
},
const fetchData = async () => {
let query = '/api/example/'
const response = await fetch(query + HERE I WANT TO ADD QUERY, settings);
const data = await response.json();
}
Edit:
Status Code: 308 Permanent Redirect
initMiddleware
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
export default function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
Below is my react code snippet. I have verified that the token is correct using postman. Does anyone have ideas what might be missing here ?
export async function getData() {
const url = buildUri();
const auth = "Bearer " + await getAccessToken(); // api call to get access token
console.log("Using auth: ", auth);
var res = fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Content-Type": "application/json",
"Authorization": auth
}
}).then(response => {
return response.json();
}).catch((error) => {
console.log("Error getting data: ", error);
});
console.log('got res: ', res);
}
By sending a request to the server through the postman everything works:
When trying to send the same request through the client, the req.body on the server is equal to an empty object:
const img = ev.target.files[0];
const body = new FormData();
body.append('image', img);
body.append('user', localStorage.getItem('user'));
const data = await (await fetch(`${root}/api/upload/profile`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data;'
},
body
})).json();
/profile route:
router.post('/profile',
cors(corsOptions),
async(req, res) => {
upload(req, res, async err => {
try {
console.log(req.body) // {}
} catch (err) {
console.log(err.stack)
}
});
}
);
I wanted to make a request to ADP with autho1.0a
I was able to make successful requests as I wanted in postman but not through my application.
postman screenshot
npm module used
similar post
Code I tried
Part:1 Signature generation
const crypto = require('crypto')
const OAuth = require('oauth-1.0a')
const oauthObj = {};
function hash_function_sha1(base_string, key) {
return crypto
.createHmac('sha1', key)
.update(base_string)
.digest('base64')
}
oauthObj.getSignature = async payload => {
const { consumerKey,consumerSecret,apiUrl,method} = payload;
const oauth = OAuth({
consumer: { key: `${consumerKey}`, secret: `${consumerSecret}` },
signature_method: 'HMAC-SHA1',
hash_function: hash_function_sha1,
});
const request_data = {
url: `${apiUrl}`,
method: `${method}`
}
const token = {}
// return oauth.toHeader(oauth.authorize(request_data, token));
console.log('header string-----',oauth.toHeader(oauth.authorize(request_data, token)));
return oauth.authorize(request_data, token);
}
module.exports = oauthObj;
Part 2 : Axios Call
let oauthData=`oauth_consumer_key=${consumerKey}&oauth_signature_method=HMAC-SHA1&oauth_timestamp=${oauthTimestamp}&oauth_nonce=${oauthNonce}&oauth_version=1.0&oauth_signature=${oauthSignature}= HTTP/1.1`;
const eventData = await axios({
url:`${apiUrl}?${oauthData}`,
// url:`${apiUrl}?${oauthHeader.Authorization}`,
method:'GET',
headers:{
// ...oauthHeader,
'Authorization':'OAuth',
'Accept': 'application/json',
// "Authorization": `'OAuth oauth_consumer_key="${consumerKey}", oauth_nonce="${oauthNonce}", oauth_signature="${oauthSignature}", oauth_signature_method="HMAC-SHA1", oauth_timestamp="${oauthTimestamp}", oauth_version="1.0"`
}
});
Expected Result:
{
"code": "Gone",
"message": "Event with token 954c183f-26e0-4f9e-b452-c089aaf9842f has already been consumed."
}
Receiving error:
response: {
status: 401,
statusText: 'Unauthorized',
headers: {
What might have gone wrong ?
Try using request node package oauth option
request.get(`${apiUrl}?${oauthData}`, {
oauth: {
consumer_key: '..',
consumer_secret: '..',
},
headers: {
Accept: 'application/json'
},
}, function (err, res, body) {
console.log(body);
})