Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions?

    //authenticate users by username
router.route('/authentication').post(function(req, res) {
    User.findOne({username : req.body.username}, function(err, user){
        if (err) throw err;
        if (!user) {
            res.json({ success: false, message: 'Authentication failed. User not found.' });
        } else if (user) {

            // check if password matches
            if (user.password != req.body.password) {
                res.json({ success: false, message: 'Authentication failed. Wrong password.' });
            } else {

                // if user is found and password is right
                // create a token
                var token = jwt.sign({usern : user.username}, app.get('superSecret'), {
                //expiresInMinutes: 1440 // expires in 24 hours
                });
                res.cookie('auth',token);
                // return the information including token as JSON
                res.setHeader('token', token);
                res.json({
                success: true,
                message: 'Enjoy your token!',
                token: token
                });
            }   
        }
    });
})

app.use('/api', router);

Answer №1

One of the great advantages of using tokens is that they do not have to be stored on the server. Instead, you simply need to verify them by checking if they are signed by you and if they have expired.

nJwt.verify(token, secretKey, function(err, jwt){
  if (err) {
    // handle errors
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transferring node_modules or bower_components to the static/public directory in a website application

In my setup with a Node.js Express web server, I've noticed that some developers use Grunt or Gulp scripts to transfer the bower_components directory contents to the /public directory in order for those assets to be accessible. Is there a more efficie ...

I attempted to implement a login feature using a prompt within a React application, but I encountered a situation where the browser asked me for the same details twice. How can I resolve

I've been working on adding a login feature to my webpage where the content is only rendered if users input valid credentials. However, I've encountered a problem where the browser prompts for credentials twice instead of just once. This behavior ...

Ensuring that a group of items adhere to a specific guideline using JavaScript promises

I need to search through a series of titles that follow the format: <div class='items'> * Some | Text * </div> or <div class='items'> * Some more | Text * </div> There are multiple blocks on the page wit ...

Using Chart.js to display JSON data in a graphical format

I am facing an issue and need some help. I have gone through various tutorials and questions, but none of them seem to address my specific problem. When making an ajax request to my PHP file, I receive a JSON response like this (as seen in the console log) ...

What is the best way to execute a SQL query within a JavaScript loop or map function?

I have a task at hand: Iterate through an array of objects using the map function Execute multiple SQL queries based on each object Append the query results to the respective objects The array I'm looping through contains offers, which are objects w ...

Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click. <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button> <select id="quantity1" class="ml- ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

stop the leakage of CSS and JS from the subtree to the document through the inverse shadow DOM mechanism

My page contains dynamic HTML content that I want to incorporate. The dynamic content consists of only HTML and CSS, without any JavaScript. However, I have some custom global CSS styles and JS logic that need to be implemented along with this dynamic con ...

Transform a div's style when hovering over another div using absolute positioning without repetition

I am facing an issue with multiple divs positioned absolutely on top of a primary div with relative positioning. I want one specific div to change its background-color when hovering over another div within the same parent div. Though I know about ad ...

React ESLint issue detected at a phantom line

When attempting to build in nextjs using next build, an error occurs with references to line 19 (an empty line) and line 33 (which does not exist). Despite updating the version of eslint-plugin-react in my package-lock.json file to ">=7.29.4", ...

What is the best way to display the current scroll percentage value?

I'm trying to update this code snippet import React from 'react' const App = () => { function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight ...

Conceal header and footer bar in Jquery Datatable theme

I need assistance in removing the header/footer bar from this table Here is a visual representation of what I am looking to remove: The jQuery code for this table: $(document).ready(function() { var oTable = $('#tableSmooth').dataTable({ ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Encountering a problem while trying to install Ionic using 'npm install -g ionic cordova' command on a Windows

I encountered an error while attempting to install Ionic, which returned the following message: 95376 warn optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7b6e786b7873696e5d2c332d332c28" ...

The checkbox generated from the JSON is failing to display the alert when it is clicked

I have been trying to pass checkbox input from JSON into HTML. When I click on the checkbox, an alert should pop up, but it's not working. Here is my code: $aroundCheck='<div id="content">'; foreach ($checkLocation as $checkLocation) ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

Error encountered with the OffsetWidth in the Jq.carousel program

I am encountering an issue that I cannot seem to figure out. Unexpected error: Cannot read property 'offsetWidth' of undefined To view the code in question, click on this link - http://jsfiddle.net/2EFsd/1/ var $carousel = $(' #carouse& ...

Can a single repository effectively utilize just one .env file?

In the project I'm currently working on, there are multiple node-modules located in subfolders. The issue I'm facing is that dotenv seems unable to find the .env file in the main root directory. As a result, the process.env variables are showing ...

Tips for modifying the function of an Electron application using an external JavaScript file

This is the project structure I envision. https://i.stack.imgur.com/ocRp9.jpg kareljs folder houses an Electron app, and upon running npm start within that directory, a window appears and executes the run method of karel.js when the button Run Karel is ...