Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request.

My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET '/api/user/').

Is there a way to accomplish this?

Below is the relevant code snippet:

app.js

// app.js

app.use('/api/userauth', require('./Controllers/api/userauth.js'))
app.use(require('./Middleware/Authenticate.js'));
app.use('/api/user', require('./Controllers/Api/User.js'));
app.use('/api/item', require('./Controllers/Api/Item.js'));

authenticate.js

//authenticate.js middleware

var token = req.body.token || req.query.token || req.headers['x-access-token'];

if (token) {
    jwt.verify(token, secretKey.secretKey, function(err, decoded){
        if (err) {
            return res.json({
                success : false,
                message : "failed to auth token."
            })
        } else {
            console.log(decoded);
            req.decoded = decoded;
            next();
        }
    })
} else {
    res.status(403).send({
        success:false,
        message:'no token provided'
    })
}
}

api/user.js

router.route('/')

.get(function(req,res){
    models.User.findAll({
    }).then(function(users){
        res.json(users);
    })
})

.post(function(req,res){
    models.User.create({
        username : req.body.username,
        password : req.body.password,
        firstname : req.body.firstname,
        lastname : req.body.lastname
    }).then(function(user){
        res.json({
            "Message" : "Succesfully created user: ",
            "User: " : user
        });
    });
});
module.exports = router;

Answer №1

Here's a solution for an old issue:

Instead of using a blank

app.use(require('./Middleware/Authenticate.js'));

for all routes, you can implement this in your sub routers like so:

api/user.js

var authMiddleware = require('./Middleware/Authenticate.js')
router.route('/')

.get(function(req,res){
    models.User.findAll({
    }).then(function(users){
        res.json(users);
    })
})

.post(authMiddleware, function(req,res){
    models.User.create({
        username : req.body.username,
        password : req.body.password,
        firstname : req.body.firstname,
        lastname : req.body.lastname
    }).then(function(user){
        res.json({
            "Message" : "Succesfully created user: ",
            "User: " : user
        });
    });
});
module.exports = router;

This way, only the specified route will have the Authenticate Middleware applied, not the get one!

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

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

Is there a way to keep a label in a Material-UI TextField from getting obscured by an adornment when the input is not in focus?

Here is the code for my custom TextField component: <TextField fullWidth: true, classes, helperText: errorText, FormHelperTextProps: getInputProps({ error }), InputProps: getInputProps({ error, endAdornment: error ? <Warning ...

What are the similarities between using the map function in AngularJS and the $map function in jQuery?

I am currently in the process of migrating jQuery code to AngularJS. I have encountered some instances where the map function is used in jQuery, and I need to replicate the same functionality in AngularJS. Below is the code snippet that demonstrates this. ...

I'm encountering an issue with numbers that contain comma decimal separators

My current script is designed to calculate the amount of water saved by a shower column. However, I have encountered issues with its functionality in Firefox and Edge when switching between using "," and "." for values interchangeably. I have attempted va ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

In what way can a container impact the appearance of a child placed in the default slots?

Visiting the vue playground. The main goal is for the container component to have control over an unspecified number of child components in the default slot. In order to achieve this, it's assumed that each child component must either hold a propert ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

A comprehensive guide on extracting attachments and inline images from EML files and transforming them into HTML format

Our challenge is parsing .EML files to display full emails with inline images and attachments on a webpage. We have successfully extracted the HTML body using MimeKIT for .net, but we are unsure of how to distinguish between inline images and regular email ...

Personalized configurations from the environment in the config.json file

I need to dynamically populate a setting object in my config.json file based on environment variables. The settings should vary depending on the environment. "somesetting": { "setting1": "%S1%", "setting2": "%S2%" } I am currently working on Wind ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Tips for transferring date values in an ajax request to a web application handler

I am currently working on plotting a graph between two dates using Google Charts. My goal is to send date values to the controller, which is implemented with webapp2. However, I am facing difficulties in figuring out how to send date values to the controll ...

When making a GET request with Angular and NodeJS that includes parameters, only the response object is returned without any associated

Let's say I have a URL like 'localhost:3000/verify/a5d5sd', which I send to a user via email. When the user clicks on this link, I use the parameter (a5d5sd) in the link to check some conditions on the server and in my MongoDB database. The ...

Angular form array inputs

Currently delving into the world of Angular.js, I have encountered a simple problem that has left me baffled. My objective is to generate form inputs with the value of "connectedTeams" in HTML: <input type="text" name="connectedTeam[]"> <input ...

The sequence of event handler executions in JavaScript

When multiple event handlers are attached to the same event on the same elements, how does the system determine the order in which they are executed? Although I came across this thread that focuses on click events, another discussion at this page points o ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

Using Vue.js to filter a list based on index matches

I need help with synchronizing two lists. The first list is displayed in a carousel format, and the second list contains details corresponding to each card in the carousel. I have successfully implemented logic to track the current index of the displayed c ...

Encountering an issue where I am unable to access properties of undefined (specifically 'up') within Material UI styling

I encountered an error message Uncaught TypeError: Cannot read properties of undefined (reading 'up') while executing the code snippet below: I am having trouble with compiling my react js Code Snippet from Index.js import React from 'react ...