I'm new to programming and I'm currently working on a small project.
I'm trying to implement some authorization using JWT.
I've watched a few videos online and found that most people have the "Bearer" + access token in their headers.
I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.
Can I please get some help?
Here are some of my code
Login
if(response){
if(await bcrypt.compare(loginPW, response.password)){
const accessToken = jwt.sign({
email: response.email
},jwtSecret)
res.json({status: 'ok', accessToken: accessToken})
}else{
return res.json({status: 'error', error:'Invalid Credentials'})
}
}
Post request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
just add Authorization header with your token to request
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
one possible way is ....on your Post requst result you can store the accessToken in localStorage
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json()).then(({accessToken})=>{
localStorage.setItem('accessToken', accessToken)
});
then retrieve it in all of your requests
const anotherRequst = await fetch('/anything',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('accessToken')}` // get it from localStorage
},
body: ... /// anything
}).then((res) => res.json());
that's the simplest way
... for more advanced techniques, try to use Axios
and you can simply set the default authorization header in all your requsts
axios.defaults.authorization = localStorage.getItem('accessToken')
then any request you make will have the accessToken in its header
Axios.post(....)
Axios.get(...)
....
You can add 'Authorization' headers within your request just like this
const result = await fetch('/',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({
loginEmail, loginPassword, reqType
})
}).then((res) => res.json());
Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line
axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;
Docs: https://www.npmjs.com/package/axios
Related
I have a problem with using axios in javascript.
I want to access my docuware to get the current Booking status. Docuware uses Cookie Authentication, so I need to get the cookies .DWPLATFORMAUTH, dwingressplatform and DWPLATFORMBROWSERID and send it in the next request.
Here is my code:
const axios = require('axios');
var querystring = require('querystring');
console.log(geta('mysecretuser', 'mysecretpw', mysecretdocid));
function geta(UserName, Password, docId) {
return axios.post('https://myorga.docuware.cloud/Docuware/Platform/Account/LogOn',
querystring.stringify({
UserName: UserName,
Password: Password
}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Connection': 'keep-alive',
}
}).then(response => {
axios.get("https://myorga.docuware.cloud/DocuWare/Platform/FileCabinets/FILECABINETID/Documents/" + docId, { withCredentials: true, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Connection': 'keep-alive',
}}).then(response1 => {
const jsonObject = response1.data;
console.log(jsonObject.VERANSTALTUNG)
console.log(jsonObject.ANMELDUNGEN)
return 0;
})
.catch(error => {
console.log(error);
});
}
).catch(error => {
console.log(error.code)
return -1;
});
}
I have tried to fix this problem with inserting withCredentials: true when creating the second request. It didn't work. Also I have tried to set the Connection header to keep-alive, but it also didn't change.
I would like to connect to REST API that uses a token Bearer.
I try the JS code below :
sessionStorage.setItem('MCToken',
JSON.stringify('123456')
);
let datastructuresAPI = () => {
let token = JSON.parse(sessionStorage.getItem('MCToken'));
let header = new Headers({
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
});
let response = fetch('https://mon_url',{
method: 'POST',
headers: header,
body:JSON.stringify({
"methodName":"connect",
'grant_type': 'client_credentials',
"serviceName":"ConnectionService"
}),
'x-frame': 'same-origin',
mode: 'no-cors'
});
console.log(response)
}
datastructuresAPI();
But I can’t connect, I have these message (the first is the result of the console.log)
Thank you for your help
Fetch function is an async function and you should wait it.
fetch(...)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
For the other result (401) are you sure that your REST API waits token with Bearer {token}? It could be only {token}.
I'm trying to make a request to get an authorization code from the spotify api using fetch but I keep getting a 415 error code. I did not have any errors when i was originally using $.ajax instead of fetch.
let client_id = '8f10fa8af1aa40c6b52073811460bf33'
let client_secret = '27a7c01912444b409a7f9a6d1f700868'
let ah = btoa(client_id + ":" + client_secret)
const getAuthToken = (searchedTerm) => {
fetch( `https://accounts.spotify.com/api/token`,
{
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
'Authorization': `Basic ${ah}`
},
body: {
grant_type: 'client_credentials'
},
json: true,
method : "POST"
}
)
.then(function(response) {
authToken = response.access_token;
spotifySearch(response.access_token, searchedTerm);
})
}
See this answer on a similar post. Note that there they set 'Content-Type':'application/x-www-form-urlencoded', with no hyphen between url and encoded. I think you simply need to change
headers: {
'Content-Type': 'application/x-www-form-url-encoded',
'Authorization': `Basic ${ah}`
},
to
headers: {
'Content-Type': 'application/x-www-form-urlencoded', // no hyphen in urlencoded
'Authorization': `Basic ${ah}`
},
In my application I need to GET some data (for which I provide the native authtoken).
In the same event, however, I also need to POST a second token to be consumed by a few endpoints, for external backend api calls.
How do I POST this second token using my working code below using axios?
Should I extend Authorization bearer or simply POST Spotify Token as string data?
How so?
My code:
getData(event) {
const {token} = this.props.spotifyToken
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data.data)
})
.catch((error) => { console.log(error); });
};
For an async await applied to your code would look something like this.
async getData(event) {
const {token} = this.props.spotifyToken
let getRes = await axios.get(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
let postRes = await axios.post(`${process.env.URL}/endpoint` {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.localStorage.authToken}`
}
}
console.log(getRes.data.data);
console.log(postRes.data.data);
};
In this specific case, where a token is needed to fetch data at backend, I found that passing token at url is more suitable, like so:
#endpoint.route('/endpoint/<select>/<user_id>/<token>', methods=['GET'])
def endpoint(name, user_id, token):
# business logic
and:
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/endpoint/${select}/${userId}/${this.props.spotifyToken}`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
otherwise, backend code would run twice, for POST and GET, which is not desired in my case.
I am trying to make a post request using FETCH in react-native. I am getting a validation error. What am I missing here?
_fetchYelp(){
let data = {
method: 'POST',
body: JSON.stringify({
'client_id': 'id',
'client_secret': 'secret',
'grant_type': 'client_credentials'
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return fetch('https://api.yelp.com/oauth2/token', data)
.then(response => response.json());
}
Error
status 400
timeout 0
response {"error":{"code":"VALIDATION_ERROR",
"description":"client_id or client_secret parameters not found. Make sure to provide client_id and client_secret in the body with the application/x-www-form-urlencoded content-type"}}
response_url https://api.yelp.com/oauth2/token
Thank you.
getAccessToken() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials')
formData.append('client_id', 'yourID')
formData.append('client_secret', 'yourSecret')
let headers = new Headers();
return fetch('https://yourBaseUrl/oauth2/token/', {
method: 'POST',
headers: headers,
body: formData,
})
.then((response) => response.json())
}