Search code examples
node.jsjwt

How to handle(Send) the jwt token and user data after the login


I made an app but im beginner and i didint know that i need to add an auth method .Im trying to use jwt but i dont understand how i must send back the user data .

For start i just put the user data and send them as

 const response = {
            status: 200,
            userId: results[0].id, 
            email : results[0].email,
            username : results[0].username,
 };      
           return res.status(200).json(response);

after the login i have found 3 ways to do it but i dont know which of them is the "best way" ,more secure and more optimize:

1)The user token with userId only

const token = jwt.sign(results[0].id, SECRET_KEY, { expiresIn: '1h'});
const response = token;
return res.status(200).json(response);

2)The user token ecrypted with some user info data

const response = {
            status: 200,
            userId: results[0].id, 
            email : results[0].email,
            username : results[0].username,
};
const token = jwt.sign(response, SECRET_KEY, { expiresIn: '1h' });
return res.status(200).json(token);

3)The token asseperate data with user data

const token = jwt.sign(results[0].id, SECRET_KEY, { expiresIn: '1h'});
const response = {
            status: 200,
            token : token,
            userId: results[0].id, 
            email : results[0].email,
            username : results[0].username,
};
return res.status(200).json(response);

When the user logs in i pass the data to a provider in order to use them for some of my screens-pages .

So how i handle this situation and how the user make changes his username-password if he likes ?

He send back the token to the server and the server decrypts it or it send the token with the userId(like this :

const response = {
            token: token,
            userId: results[0].id, 
            username : newUsername
 };     

) for example and the new username-password?

Thank you for your time .


Solution

  • So how i handle this situation and how the user make changes his username-password if he likes ?

    You have almost got the answer

    1. User logins into the server then server response with a jwt token
    2. User must send this token in following request header (Authoriztion)
    3. Server must validate the jwt to authorise the user is a actual user

    So the jwt must signed with user.id, it's enough to identify a user.

    Let's imagine a scenario as you mentioned about user password change, so user had login into app and got the token then this happens

    front-end (I'm using js)

    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    // HERE I'm sending the token
    myHeaders.append("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c");
    
    const urlencoded = new URLSearchParams();
    urlencoded.append("username", "\"newUserName\"");
    
    const requestOptions = {
      method: "POST",
      headers: myHeaders,
      body: urlencoded,
      redirect: "follow"
    };
    
    fetch("YOUR_API/change-name", requestOptions)
      .then((response) => response.text())
      .then((result) => console.log(result))
      .catch((error) => console.error(error));
    

    Back-end

    app.post('/change-name', function(req,res){
        const  header = req.header('authorization');
        if(!header){
            res.status(400).json({
                error:{
                    code: 400,
                    message:"No auth headers found"
                }
            })
        } 
        
        const authorization = header.split(' ');
        const token = authorization.length == 2 ? authorization[1] : authorization[0];
        const { id: userId } = jwt.verify(
            token,
            process.env.APP_SECRET
        );
        if(!userId){
            res.status(401).json({
                error:{
                    code: 401,
                    message:"Unauthorized access"
                }
            })
        }
    
        // user name change logic
    })
    

    Also you can create a middleware for token validation

    Use this to create token

    const token = jwt.sign(
        {
          id: userId
        },
        process.env.APP_SECRET,
        {
            algorithm:"HS512",
            expiresIn: expires,
            issuer: process.env.APP_NAME,
            jwtid: crypto.randomUUID()
        }
    )