I have a component called login, and I was thinking of the following...
This is my onSubmit function which is executed upon submitting the login form and resolves the response from the server.
onSubmit (e) {
fetch (`http://localhost:3000/api/users/login/${this.state.username}/${this.state.password}/`, {
method: 'POST'
})
.then(res => res.json())
.then(res => {
if (res.success) {
console.log('ok');
}
});
}
Within that if where he is, console.log('ok');
for example, I would like to create a cookie that lasts 1 hour, and then know how I could verify in the other components when the cookie is active or not, thus allowing access to the dashboard or sending it to the login. I don't know if this is the correct way, I read some JWT but it is extremely difficult for someone new to this and the truth is that this site doesn't need too much security. What do you recommend me to do?
Cookies are created on the server and sent to the client, so with each request they are sent implicitly.
Express login example:
Note: you need to install the middleware
cookie-parser
andcookie-session
`.The recommended way is to store the information directly in memory.
Note: you need to install the middleware
cookie-parser
andexpress-session
`.In this way, the session data is stored in memory, not in a cookie as in the previous example. The only thing that is saved in a cookie here is the user's session id.
Once the session middleware is added, when a user logs in and touches the object
session
,request
their session will start.In that case it is enough for you to use cookies. On the other hand, JWT is not difficult, it is actually quite simple, it only consists of creating a token and sending it to the client as with cookies, so in each request this token will be sent to the server.
JWT is an open standard ( RFC 7519 ) that defines a secure way to communicate between two parties. The importance of this standard is that the information shared is digitally signed, which implies an important security plus. In fact, JWT can be signed using the classic algorithm
HMAC
or with a keyRSA
.When JWT is used, the authorization is stored in the client, generally in
localStorage
and in each request made to the server it is sent in the headerAuthorization
with the valueBearer <token>
.The following example simulates a login using
jsonwebtoken
.First we create a function that creates a token:
Second we do the login, if it is successful, the token is generated and sent to the client:
When the user accesses any resource (be it API or whatever), the token that is implicit in the header is decoded
Authorization
and compared. For this we can implement a middleware that does it in each request.When the token expires, the token will not be sent in the request and the middleware will redirect to
/login
.Some advantages of JWT are: