Verify the front-end application and authenticate the backend REST API

My project involves developing a REST API and application logic on the client-side, keeping them separate and independent of each other. Now I am looking to implement an authentication system that will automatically authenticate users both on the client-side and the REST API after they log in.

For example, once a user logs in on the client-side, they should be able to access pages like photo/add and api/photo/add seamlessly.

I am considering using cookies for authentication, but I am also intrigued by the possibilities of JWT. However, most resources I have found so far only address authentication on either the client-side or the front-end where the application logic is tightly coupled with database calls, or focus solely on the REST API itself without considering both at the same time.

In essence, my question is: how can I authenticate both views (such as pages) and the REST API simultaneously?

Answer №1

To establish communication between your client and API, you have the option to utilize AJAX, using either

the fetch API

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {  
    if (!response.ok) {
      // error handling
      throw new Error('HTTP error, status = ' + response.status);
    }
    return response.json();
  })
  .then(json => console.log(json))

or XMLHttpRequest

let xhttp = new XMLHttpRequest()
xhttp.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', false); 
xhttp.onreadystatechange = function(event) {
    // XMLHttpRequest.DONE === 4
    if (this.readyState === XMLHttpRequest.DONE) {
        if (this.status === 200) {
            // worked
            console.log(this.responseText);
        } else {
            // error
            console.log("Status de la réponse: %d (%s)", this.status, this.statusText);
        }
    }
};
xhttp.send(null);


Maintaining the connection can be achieved using cookies or session storage

The primary distinction is that cookies are sent as HTTP headers for each request, while localstorage is only accessible within your client's JavaScript

cookie can be accessed in JavaScript using document.cookie, which returns a string resembling

name=oeschger; favorite_food=tripe; test1=Hello; test2=World

localStorage can be accessed with window.localStorage, providing a Storage object featuring 5 methods:

  • Storage.key() When given a number n, this method will return the name of the nth key in the storage.

  • Storage.getItem() When given a key name, it will return that key's value.

  • Storage.setItem() When given a key name and value, it will add that key to the storage or update its value if it already exists.

  • Storage.removeItem() When given a key name, it will remove that key from the storage.

  • Storage.clear() When called, it will clear all keys from the storage.

The method for keeping someone logged in

For auto-login purposes, the process is as follows:

  • Check if there is an auth token (random unique string) stored
  • If yes, attempt to log in using the token
    • If the server accepts, everything is good
    • If the server rejects, proceed to the else statement
  • Else
    • The user logs in normally with their account
    • The server responds with an auth token
    • Store the token as needed

Auth tokens should have a limited lifespan (it's illegal for cookies to last longer than a year in Europe)

One token per account at most; a new token invalidates the previous one

For more information on the process, visit

Answer №2

I am looking to set up a seamless authentication system where users are automatically authenticated on both the client-side and the REST API side after logging in.

The solution lies in implementing the RFC 7519 standard method known as JWT, which stands for JSON Web Tokens. By integrating libraries like passport and passport-jwt into your packages, you can create a middleware that checks for tokens in request headers or query parameters. This middleware will handle token verification, expiration, and user roles, allowing for automatic access to requested resources.

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

Guide on implementing a filter on an image using P5 in a React application

Seeking clarity on a specific issue, I'm using a react-P5-wrapper to create my P5 canvas in React, and I want to apply a filter to an image. Typically, in P5, this would be done with image.filter(GRAY). However, when P5 is an instance in React, I can& ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...

Is there a method for executing ng-serve alongside expressjs?

I am currently following an Angular6/Express tutorial. In the tutorial, they utilize the following scripts: "scripts": { "ng": "ng", "start": "ng build && node ./bin/www", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e ...

Generate a specified quantity of elements using jQuery and an integer

I am working with a json file that contains an items category listing various items through an array. This list of items gets updated every few hours. For example: { "items": [ { "name": "Blueberry", "img": "website.com/blueberry.png" } ...

Is Heroku compatible with Express version 3.0?

While attempting to upload my node.js app to Heroku, I encountered an issue: Trying to install dependencies with npm npm ERR! Error: No suitable version available: express@'>=3.0.0' Is it possible for Heroku to accommodate express 3.0 ...

The value entered is being displayed twice every time the onChange event occurs in ReactJS

I recently implemented useReducer in my React project and encountered a strange issue where the values I type are being printed double and twice, as shown in the screenshot below. https://i.sstatic.net/KCkSy.png I'm unsure why this is happening. Here ...

Amazon Banner Integration for Angular Version 4

Having some trouble getting an Amazon banner to display inside an angular material 2 card. The div appears empty and the banner is not rendering. Any idea what could be causing this issue? Below is the code snippet showcasing my attempts: <md-card clas ...

Steps for accessing req.session in nextServerInit before rendering:1. Start by importing the

Currently, I am in the process of setting up a website using nuxt+express by running 'vue init nuxt-community/express-template' command. The specific feature I am focusing on is "auth". My goal is to maintain the user's information stored co ...

Using CDN to load the STLLoader in Three.js

After deciding to have some fun by creating an STL loader, I've hit a roadblock. Despite trying various solutions found online, I'm still facing issues, mainly due to CDN errors. Currently, I'm following the tutorial on the Three.js site and ...

My code using puppeteer in nodejs/express has successfully detected the desired elements within the HTML file

I am currently working with nodejs/puppeeteer and have set up a small API route. My goal is to detect when the puppeteer scripts have finished running so that I can display a message on my HTML page. I'm unsure about what changes need to be made in th ...

Issue with D3: Events not triggering transitions

I am currently working on creating a bar chart using D3 in Angular4. // Enter Phase this.chart.selectAll('.bar') .data(this.barData) .enter() .append('rect') .attr('class', 'bar'); // Update Phase let bars ...

Having trouble with the jQuery toggle functionality not working as expected

I'm implementing a function where a div should increase in height and opacity when clicked, and then revert back to its original state when clicked again. I used the toggle function for this purpose, but the issue is that the button disappears when th ...

Activating the mousewheel effect exclusively on specific div sections, rather than the entire page

After researching mousewheel events in jQuery, I realize that my lack of knowledge may be hindering my ability to find useful answers. I am looking to create a mousewheel effect that is only triggered within a specific div called #scroller. Currently, I am ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...

The issue with MVC4 and Ajax requests for converting image ByteArrays appears to be problematic

I am attempting to change an image in my View with a click event. However, when the controller returns a byte array, the original image is replaced with an empty one. Below is the code from my Controller: [HttpPost] public byte[] GetSelectedI ...

Combining JWT authentication with access control lists: a comprehensive guide

I have successfully integrated passport with a JWT strategy, and it is functioning well. My jwt-protected routes are structured like this... app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thing ...

Backbone.js experiencing synchronization issues exclusively in Internet Explorer

Can anyone confirm if they have encountered this issue before? I'm unsure how to elaborate further as it seems to be the only symptom. Additionally, it does not sync correctly in Internet Explorer. ...