简体   繁体   中英

User authentification in express.js / Node.Js

I have a problem with user authentification in my app that runs on Node.Js / Express.Js

Basically, when the user logs in the main interface (html), they are shown a graph, which is obtained through an API path (/api/data/json), which also requires authentification through

exports.auth = express.basicAuth(User.authenticate);

in routes/api.js

I tried "telling" routes/api.js that the user is already authorized through passing it one of the res.locals.user parameters, but it didn't help...

So my question: is there any way in Node.Js to store user's login details in a session variable (like you can do in PHP for example), so that it's passed on to all the components when authorization is needed, to avoid users having to re-authorize when they access another part of the app?

Thank you!

The basicAuth middleware populates req.user with the username when authentication has succeeded. To check if user is authenticated at any middleware that comes afterwards eg in your routes/api.js , all you have to do is check if req.user is defined:

if (req.user) {
    // User is already auth'ed; provide secret data
} else {
    // Proceed to next middleware to provide a standard error message
    next();
}

Alternatively you can also redirect to another route with res.redirect('/goToOtherpage') or you can respond with an HTTP error with res.send(401) to signal Unauthorized to the caller.

Not sure if this will be of any use but you could hook into the HTML5 session storage. Here is an article going into it a bit more.

http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

Here is an example taken from the article on how to use it.

//save a value
sessionStorage.setItem("name", "Nicholas");

//retrieve item
var name = sessionStorage.getItem("name");

//get the key name for the first item
var key = sessionStorage.key(0);

//remove the key
sessionStorage.removeItem(key);

//check how many key-value pairs are present
var count = sessionStorage.length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM