Reputation: 730
Hello I have a query regarding JWT and authentication. In authentication, does the server have to store the JWT as well and have it related to the client?
When the client log in, it receives the JWT token and store it in localStorae with the "auth" key:
For example, this is a client's basic code
const user{
email:user_email,
password:user_password
//other field
}
axios
.post("http://localhost:4000/api/login", user)
.then(function (response) {
if (response.data.success === false) {
// password or user does not exist!
} else {
localStorage.setItem("auth", response.data.token);
setTimeout(() => {
history.push("/");
}, 3000);
}
})
.catch(function (error) {
console.log(error);
});
};
Then in our Routes, we can check if there is a token and if so, we can access certain urls that are only accessible when logged in:
const PrivateRoute = (props) => {
const token = localStorage.getItem("auth");
return <>{token ? <Route {...props} /> : <Redirect to="/login" />}</>;
};
But my question comes from: when the client sends a new request (once logged in) doing a POST, GET, DELETE, does the HTTPS packet data need to be in JSON format with the corresponding token? But if so, the server must have the JWT stored to confirm that the user is registered and is who they say they are. So what is the difference with a session?
How do you check if the server doesn't have the JWT stored in its database that the client is who it claims to be?
For example, in django, must there be a field that is jwt?
class User(models.Model):
email = models.EmailField(max_length=254)
token = models.BigIntegerField(default=None)
#Otros campos
Upvotes: 0
Views: 288
Reputation: 17382
A jwt typically contains a set of so called claims, one if them oftentimes is the sub
claim which denotes the subject
for whom this token was issued. Depending on the particular issuer, this claim may also be named differently. Another typically claim is exp
which denotes a timestamp, when this token expires.
Furthermore a JWT should be signed by a trusted party (the issuer). This can be your own server or any other trusted party (for instance sign-in with Google or something like that). If you are able to verify that signature, you are safe to assume the token wasn't tampered with.
So if you find a sub
claim in a token whichs signature you can verify, you can easily identify the user. If you furthermore check the expiration, you can reject tokens which are not valid anymore.
But if you don't store the token at the backend, you won't be able to revoke such a token prematurely and it will be valid until it expires. That may, or may be not, a problem, depending on your usecase.
Upvotes: 1