node
const LocalStorage = require ('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./localStorage');
localStorage.setItem('username', user.name);
localStorage.setItem('token', user.token)
react
const author = localStorage.getItem('username')
const token = localStorage.getItem('token')
In react console.log(localStorage) // {}
P.S: maybe need send from react to node GET request?
fetch('/api', {
method: 'GET'
I Assume that you are trying to make request along with the token that you have saved in locastorage. for that you have to add Authorization headers. like
const token = localStorage.getItem('token')
fetch('https://example.com/endpoint', {
method: 'GET',
headers: {
'Authorization': token
}
})
to get the token create a specific route like
first you need to import
import jwt from 'jwt-simple';
Then
app.post('/login',function(req,res,next){
res.send({token:jwt.encode({sub:user.id,iat:timpestamp},SecretKey)});
});
where SecretKey is the key defined to encryption and here the userId with time is taken to generate the token
Related
When I try to login to my react app it returns as success and saves it in sessionStorage but when I try to access the page which requires Bearer token to fetch data via axios it returns http 401 error.
But when I reload the page, then the result is as required.
import axios from "axios";
let token = JSON.parse(window.sessionStorage.getItem("token"));
let AxiosInstance= axios.create({
baseURL: "https://myurl.com/backend/api/",
timeout: 5000,
headers: { Authorization: "Bearer " + token },
});
export default AxiosInstance;
Your token is being initialized onload so you have to call token in config.headers["Authorization"] on every request through interceptor so you don't need to reload page.
Interceptor:
Axios interceptors are functions that are called before a request is sent and after a response is received
import axios from "axios";
let AxiosInstance = axios.create({
baseURL: "https://myurl.com/backend/api/",
timeout: 5000,
});
AxiosInstance.interceptors.request.use(function (config) {
let token = JSON.parse(window.sessionStorage.getItem("sessionData"));
config.headers["Authorization"] = "Bearer " + token;
return config;
});
export default AxiosInstance;
UPDATE: You can learn more here about Axios interceptors
I'll guess it is because you're creating the axios instance outside any of React's lifecycle
when you run your app and enter your login screen, it makes a Axios instance
import axios from "axios";
let token = JSON.parse(window.sessionStorage.getItem("token"));
let AxiosInstance = axios.create({
baseURL: "https://myurl.com/backend/api/",
timeout: 5000,
headers: { Authorization: "Bearer " + token }, // on the first go token is null
});
export default AxiosInstance;
After you login, your axios instance still has a nulll token, you see, this code is executed once and never more, that's why when you refresh the page, it works, because when this piece of code is executed once again, there's a token in localstorage.
There's a couple things you can do but the easiest i guess it's to use Axios interceptors
AxiosInstace.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
That way every time you do a request your headers will be updated (not sure if this is the best approach but it works)
I'm trying to use the fetch API in vanilla JavaScript to generate a token provided by Django OAuth Toolkit. The application I've created in DOT uses the "Resource owner password-based" authorization grant type. My code looks like this (grant_type, username and password are provided through request.formData()):
const data = await request.formData();
const oauth = await fetch(`${API_ROOT}/o/token`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Basic ${Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')}`
},
body: data
});
This request imitates a successful GET request I've created using Insomnia (with Multipart Form data for grant_type, username and password + CLIENT_ID and CLIENT_SECRET as the username and password in Basic Auth). In other words, I don't understand why the JavaScript fetch request does not work even though it is supposed to be identical to the Insomnia request. The JavaScript fetch request returns a 400 error. When I remove the Content-Type header, I get a 500 error. What am I doing wrong?
EDIT: It may be worth noting that I am making this fetch call within a SvelteKit application.
As it turns out, in this particular case I DID need to set Content-Type. I found this answer: Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery
My code works as follows:
const data = await request.formData();
const oauth = await fetch(`${API_ROOT}/oauth/token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
Authorization: `Basic ${Buffer.from(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')}`,
},
body: formDataToUrlEncoded(data)
});
The formDataToUrlEncoded function roughly ressembles the one posted in the above post:
export function formDataToUrlEncoded(formData) {
var url_encoded = '';
for (var pair of formData) {
if (url_encoded != '') {
url_encoded += '&';
}
url_encoded += encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]);
}
return url_encoded;
}
I saw many tutorials on jwt authentication but every video maker uses Postman to show what's happening and they pass on the header in the headers section while requesting a URL in Postman. I tried to do it with JavaScript but I was not able to do it.
I want to do jwt authentication but after token generation, I send it to client side to use it for further requests but I failed to do so after trying it a few times. I also tried to set req.headers in server side but it didn't do what I wanted to..
I want to set request headers for authentication of the form "Bearer {token}" for every request after token generation. How to do it with JS??
What I am most concerned about is that every tutorial does it with postman but they didn't show how they implemented it in their own app. I hope my question is clear.
You can easily add header on your http request like that
it has been solved here Node.JS: How to send headers with form data using request module
In vanilla nodejs:
const uri = "http://example.com";
const options = {
headers: {
"Authorization": "Bearer ...."
}
}
// require http/https lib
let req = require("http").request(uri, options, (res) => {
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.once("end", () => {
// concat body chunks
let body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.on("error", (err) => {
console.log(err);
});
req.end();
https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_options_callback
Something like that:
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("custom_header", "value");
},
success: function(data) {
}
});
First install jwt and express framework using npm then make a middleware file which will check if the tokek is set or not.
Middleware.js :
let jwt = require('jsonwebtoken');
const config = require('./config.js');
let checkToken = (req, res, next) => {
let token = req.headers['authorization']; // Express headers are auto converted to lowercase
if (token) {
if (token.startsWith('Bearer ')) { // Checks if it contains Bearer
// Remove Bearer from string
token = token.slice(7, token.length); //Separate Bearer and get token
}
jwt.verify(token, config.secret, (err, decoded) => { //Inser the token and verify it.
if (err) {
return res.json({
status: false,
message: 'Token is not valid'
});
} else {
req.decoded = decoded;
next();
}
});
} else {
return res.json({
status: false,
message: 'Access denied! No token provided.'
});
}
};
Next, create a config file which will contain the secrets.
Config js:
module.exports = {
secret: 'worldisfullofdevelopers'
};
Finally, create a token route which will create your token and after that the rest of the calls will be authenticated for that token.
Index.js :
const middleware = require('./middleware');
const jwt = require("jsonwebtoken");
const config = require('./config.js');
//Call token Route
app.use('/token', (req, res, next) => {
//Generate Token
let token = jwt.sign({ username: "test" },
config.secret,
{
expiresIn: '1h' // expires in 1 hours
}
);
//Send Token
res.json({
success: true,
message: 'Authentication successful!',
token: token
});
});
//Add Authentication to all routes
app.use(middleware.checkToken);
//===> All the routes after middleware will be checked for token
app.use('/getUser', (req, res, next) => {;
console.log('do something')
});
If I understand correctly, you want to set the HTTP header on the client, in order to pass an authentication token to the server. I would recommend that you use a library like **axios*.
Using axios, once you receive the toke, set the header for every outgoing communication with the following line of code:
axios.defaults.headers.common['Authorization'] = "Bearer " + token;
This will set the authentication http header to the form you need.
I would like to connect with the Stripe API using a https call using the https library.
var https = require('https');
I have gotten the secret key and publishable key and put it inside a object:
var stripe = {
secret_key: 'secret_key_given_in_the_dashboard',
publishable_key: 'publishable_key_given_in_the_dashboard'
}
I am now in the part of creating the requestDetail object:
var requestDetails = {
'protocol' : 'https:',
'hostname' : 'api.stripe.com',
'method' : 'POST', //WHICH OF POST GET PUT DELETE SHOULD I USE?
'path' : '???????????????????????',// WHICH ENDPOINT SHOULD I USE?
'auth' : '???????????????????????',// SHOULD I USE THE SECRET AND PUBLISHABLE KEY HERE?
'headers' : {
'Content-Type' : 'application/x-www-form-urlencoded',
'Content-Length' : Buffer.byteLength(stringPayload)
}
};
I plan to make use of the requestDetails object in the call using https:
var req = https.request(requestDetails, function(res){
// Grab the status of the sent request
var status = res.statusCode;
//Callback successfully if the request went through
if(status == 200 || status == 201) {
callback(false);
} else {
callback('Status code returned was ' + status);
}
});
Where and how should I use the secret key and publishable key in order to make a call to the stripe API?
Which endpoint?
Which method (POST, GET, PUT,or DELETE)?
I would like to eventually create a order and pay through the STRIPE api.
But for now just any authenticated call through the stripe api will do as I need a sample format that works....
I'm not too sure where to add the secret key and publishable key....
You should install official stripe package (source: https://github.com/stripe/stripe-node), require the package and authenticate it using your secret key ( example from the github docs):
const stripe = require('stripe')('your_stripe_secret_key');
stripe.customers.create({
email: 'customer#example.com',
})
.then(customer => console.log(customer.id))
.catch(error => console.error(error));
The package is an abstraction to make the API requests for you.
More docs: https://stripe.com/docs/api?lang=node
However, if you want to use the https directly for Stripe API requests, which is not recommended, you can check the docs and examples for using the cURL, since it shows the endpoints for each example.
https://stripe.com/docs/api/authentication?lang=curl
try using fetch, 'Authorization': 'Bearer ' + sk.
My working example of retrieving a customer based on the customer_id:
const url = `https://api.stripe.com/v1/customers/${stripe_customer_id}`;
return await fetch(url, {
method: "get",
headers: {
"Content-Type": "application/json",
'Authorization': 'Bearer ' + sk,
}
})
.then(function(response) {
return response.json();
})
.then(function(response) {
// console.log(response);
return response;
});
};
I'm developing the application with react js and redux. For backend i used java to create api's. So far i have created three services, login, signup, listing. I have used jwt token for listing service to secure the incformation. I have set jwt token expiration time is 10 mins in backend. Each 10 mins the jwt token will get expired and for new token i need to login again. This is what i have done in backend.
I have integrated those services in my react with redux concept. The problem which i'm getting is, each i need to go login screen for new token. I want this to be happen in background. How to do with redux?
export function handleResponse(response) {
if (response.ok) {
return response.json();
}
// If invalid jwt token the page will get redirect to login.
if (response.status === 401) {
localStorage.clear();
alert('Session expired!');
location.href = '/login';
}
}
export function loginAction(data) {
const resObject = {
username: data.username,
password: data.password,
};
return dispatch =>
fetch(`/login`, {
method: 'post',
body: JSON.stringify(resObject),
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${basicAuth.authSecret}`,
},
})
.then(handleResponse)
.then(res => dispatch(loginUser(res)));
}