How to store jwt token in localStorage and send it back to the server with header in express? - express

I have read many articles in stackoverflow and have seen lots of youtube videos, but failed to find the example code which is demonstrating about the flow of saving jwt to localstorage - send back to server with authorization header for verifying.
Here is what I want to do.
When the client logs in to the server, server gives token and saves it to the client localStorage (or sessionStorage).
Whenever the client calls an api which can be accessed only with the token,
client retrieves the token back from the localStorage, and send that token with the authorization header (req.headers.[x-access-token] or req.headers.[authorization]) to the server.
But all of the articles I've been read is explaining this issue with the Postman which does not show how to store it to the localStorage and put it in the authorization header.
Do I have to use localStorage.setItem when the server gives the token to the client, and use and localStorage.getItem and new Headers() with append() or axios before sending that token back to the server?
Examples don't have to be for the express user, but I'd like to get the glimpse of ideas.

You can store your jwt token in localstorage and when ever you make a API call you can add the token to headers as token. if you are using axios you can attach you token to headers like this. Here the token is stored in localstorage with the key 'jwtToken'
axios.post('http://yourendpoint',data,{ headers: { Authorization:localStorage.getItem('jwtToken') } })
.then(response=> console.log(response))
.catch(error => console.log(error));
};

it's easy just Follow me
First of all you have to save the Token(or access token) to the local storage,
in the login component when you are sending request for login do the below:
signin:function() {
axios.post('http://Somthing/log-in/',{
username: this.username,
password: this.password,
})
.then( (response) => {
let token = response.data.access;
localStorage.setItem("SavedToken", 'Bearer ' + token);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
(this.$router.push({name:'HomePage'}));
})
So now the problem is whenever you refresh the Homepage you got 401 error and the solution is : just add this :
{ headers: { Authorization:localStorage.getItem('SavedToken') }}
to the end of each request that need the Token in its header, like below:
axios.get('http://Something/', { headers: { Authorization:localStorage.getItem('SavedToken') }})
.then(response =>{
//something
})
Notice that the token that i used in this explanation was SIMPLEJWT , if you are using somthing else maybe you have to change 'Bearer' to somthing else.

First you have to create or Generate Token through Jwt (jsonWebTokens) then either store it in local Storage or through Cookie or through Session. I generally prefer local storage because it is easier to store token in local storage through SET and retrieve it using GET method. and after retrieving it through get you can verify it through jwt and also authenticate it with bearer authentication..
And for headers add Authorization
fetch("/users", {
method: "Get",
headers: {
"content-type": "application/json",
Authorization: "Bearer" + localStorage.getItem("token")
}

JWTs should never be stored in your localStorage
In fact, they shouldn't even be stored in your cookies, unless you are able to implement very strict CSRF protection
Checkout this for motivation
JWT as an id_token is like your user credentials
JWT as an access_token is like your session token
One option is in-memory. Checkout this for a deep dive

Related

Sync Token in Postman

A fresher to postman, currently working on API project where I need to delivery to the API and Token the client to integrate with them system, good is I successfully configure the Authorization as OAuth Type as Password Credentials and receiving perfect response as 200.
The issue/confusion is Token is getting expire every hour, I need to Get new Access Token every time.
So, the question is, is it anyway I can overcome this issue?
that no need to get new/refresh token.
can provide the one fix token to client.
You can do it like here. You can get the token in the pre-request field of the collection or request.
https://stackoverflow.com/a/73911458/10126763
EDIT
We can adapt it like this:
Take this and paste it in the "pre-request" field of the collection or the request you will use directly. Create an "environment" value named "accessToken". When each request is run, this method will run first and send the token value to the value in the environment.
// Set refresh and access tokens
const loginRequest = {
url: "exampleurl.com/etc/etc", //YOUR URL
method: 'GET',
header: {
'content-type': 'application/json',
'Accept': "*/*"
} //Since you will be using GET, I deleted the body. If you are sending value you can get the body field from the other example in the link.
};
pm.sendRequest(loginRequest, function (err, res) {
pm.environment.set("accessToken", res.json().accessToken); //The token returned in the response and the environment value to which the value will be sent
});

Setting a JWT token in header from localStorage for redirect

I am using JWT tokens to authenticate users and protect certain routes.
My app is set up with a login function that receives a username and password from the front end, authenticates the user and passes back a token.
I am able to store my token in localStorage like this.
localStorage.setItem("Token", token);
Any ajax call going forward should be able to use
$.ajax({
type: 'GET',
url: '/protected_route,
headers: {
"Accept": "application/json",
"Token" : localStorage.getItem(Token),
success: (data) => {
// do something with the data
}}
This should work as long as the token is still set in localStorage and not expired. My question is, if I want to redirect right after login to a protected path, how would I do that?
window.location = '/my_profile
does not let me set headers.
I am surprised that I could not find anything regarding this issue. Seems like very common use case when using JWT.
Thanks!!

How to check expiry of access token and send refresh token

I am making an app without login i have successfully fetched access token and used it for authentication of another api. But now i want to check expiry of the access token and if the access token is expired how to send refresh token
i found refreshableFetch but i do not know should i use it or not because it not uses refresh token
fetch('URL', {
method: 'GET',
headers: {
etc...
})
.then((response) => response.json())
.then((responseData) => {
this.setState({data: responseData})
})
I am fetching the data as regular. Please suggest me methods to check expiry of access token and to use refresh token
I can suggest you the flow of how you can achieve your desire goal
fetch access token
send access token with every request after that.
check on server end for expiry of each incoming request token.
if token has expired (I assume you have a date in your db) send { status: false , message: "token expired" } else { status: true,
data: "YOUR DATA", message: "" }
check for status on client end, if status is false && message is token expire call refresh token api
In refresh token api, update new token on server
I tried to explain you the flow as I am unaware of your backend logic and code. Hope you can modify the code accordingly as you get the gist :)

Implementation JWT based authentication without Oauth and custom token scheme

I am working on a Web API where I implemented JWT based authentication. I am not using neither PasswordJS middlware nor Oauth protocol. Its basically JWT npm which I use to sign and verify tokens.
The whole concept of token are pretty clear, but I very much confused with the term 'token scheme' and cannot understand what it is used for.
What I would like to understand is: do I need to use some sort or custom 'JWT' scheme and validate it when token is send back to server for further requests, or this concept is used only by Oauth, and what I need is only send the plain token?
var accessToken = jwt.sign({
userID: user.id,
isAdmin: user.isAdmin
}, config.userSecret, {
expiresIn: 600
});
res.json({
success: true,
user: {
id: user._id,
name: user.name,
username: user.username,
accessToken: 'JWT ' + accessToken,
}
});
jwt.verify(accessToken, secret, function(err, token){...}); //throws error when token is passed with the custom scheme
Exactly what scheme you are using isn't that important in this case, because you are parsing the content of the Authorization header manually anyway.
Basically, the token is sent from the client to the server on an HTTP header called Authorization. In front of the token you put the name of the scheme. So the Authorization header might look something like this:
Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
(The list of allowed names is here. For JWT it's usually Bearer. You are technically not following the OAuth 2.0 bearer scheme according to RFC6749, but it's usually called Bearer anyway.)
You have to manually take the token (ey...) and verify it with jwt.verify() to get its payload.
const headerExists = req.headers.authorization
if (headerExists) {
let token = req.headers.authorization.split(' ')[1];
jwt.verify(token, auth.secretjwtkey, function (err, decoded) {
if (err) {
res.status(HttpStatus.UNAUTHORIZED).json('Unauthorized');
} else if (decoded.role === 'admin') {
next();
} else {
res.status(HttpStatus.UNAUTHORIZED).json('Unauthorized');
}
})
} else {
res.status(HttpStatus.FORBIDDEN).json('No token');
}
You can see from the example middleware above that I don't care about the Bearer string on the Authorization header, only the token itself. You could, of course, check that it actually was Bearer and not something else though.
So the moral of the story is that:
You send the token from client to the server on the Authorization header. You have to set up the front-end so that happens.
You prepend Bearer in front of the token (or one of the other in the allowed list, but bearer is recommended).
You decode the token by reading the second part of the string that is on the Authorization header and then feed it to jwt.verify().
See here for more details.

react-native - Bearer Token auth - httpReqest

I'm new to react native and I need some help.
I'm writing an app for android with react native.
I had already implemented the login Screen and all screens that should be shown when the loggin process completed successfully.
I don't know to to make a http request with bearer auth to my localhost website.The Request Method is GET. In my app i have to enter username and password and send it to the https:/localhost/.../login.
This is working so far: I get the tipped user and password from the TextInput of the loginscreen and send both to my function called httpRequest.
function httpRequest(name, password) {
var httpResponse = null;
// not implemented yet
}
I don't know know how to start ... should i start with a fetch-Get mehtod that i can find on react-native docs ? But how should i do it with bearer token (auth)
This is a common issue newcomers face when dealing with authentication.
I recommend you to give this a good read https://auth0.com/blog/adding-authentication-to-react-native-using-jwt/
You need a bit of advanced knowledge to implement it but you will learn with it, anyways.
You'll have to send your username and password to your backend with a POST request NOT a GET. So you can attach the name and password data to the body of the request. Also you'll want to use fetch to make the request.
You can do it like this:
function httpRequest(name, password) {
const user = {
name,
password,
};
fetch('https://mywebsite.com/endpoint/', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(data => {
console.log(data);
// data should contain a JWT token from your backend
// which you can save in localStorage or a cookie
})
.catch(err => console.log(err));
}
Also check out my answer on this question about a fetch helper function for easily generating headers. It includes a piece in there for easily adding a JWT token to your requests.
How to post a json array in react native