Authentication: sessions, JWT, or something else? - node.js

I have a web server that serves a website to users. Through this website they can sign in using oauth, which I currently store in a session on the server. The session basically just tells me what user this is and if they are signed in or not (which is all I want from it).
I then have an API-server which is only used to query for information which might be protected (ie, only signed in users can see it). The API-server is only accessible through the main server, which just proxies everything through. The API-server has access to the same backing store which means it can read the sessions and process the requests requiring authentication checks. A nit to this approach is: since the session only lives in memory until saved, I need to save it every time a request is going to be proxied to the server to ensure the API-server has fresh data.
But thats not the true issue, the true issue is when a user visits say /account, I want to prefetch all the data they need and build the entire site on the server before sending them it (so they don't have to wait for the http-request and render the entire site again). This is problematic, because when the server tries to access an area only authenticated users can see, it gets denied. To work around this I would need to inject the session id in the request and re-work a lot of code which intuitively feels like the wrong approach. If I use JWT, I could perhaps create a "super user token" that the server would generate which would allow it access to any part of the authenticated area, but that also feels risky.
What do you guys think?
Some additional information that might be relevant:
I'm using react and doing server side rendering
I am using redux (which is the state I try to prefill)
I am using Node
Thanks in advance!

Use a middle ware before controller in every secure route/endpoint
in this middle ware check your jwt token if token is valid then call next middleware.
router.route('/post')
.post(isAdmin,postCntr.addPost);
function isAdmin (req, res, next) {
var token = req.headers['authentication'] || req.body.token || req.params.token;
if (token) {
// verifies secret and checks exp
jwt.verify(token, app.get('superSecret'), function(err, decoded) {
if (err) {
return res.json({
err: err,
success: false,
message: 'Failed to authenticate token.'
});
} else {
next();
}
});
} else {
// if there is no token
// return an error
return res.status(403).send({
success: false,
message: 'No token provided.'
});
}
}

Related

Spotify JWT Flow

Tech stack: NodeJS backend Angular10 front end
I am implementing the Spotify API into my application. I'm having some issues with the flow.
To start off I have no issues authenticating or retrieving a token, but I am having an issue figuring out what to do with it. Assuming we understand the Spotify flow and are on the same page there is an issue presented for client-side rendered apps and that is how to get our JWT into the storage.
The reason this is an issue is because of the flow Spotify constrains us to, it requires a callback where the token is passed in as a query param.
This callback is on my backend NodeJS server, the endpoint is functioning fine but this issue starts here - I cannot pass in my user_id or any other user information it simply returns a JWT at this point the only thing I can do is send a template to the client but it's of a different domain.
Option (1)
Somehow use the Iframe hack to set a storage item in my other tab that's running my front end; I do not like this cause it's hacky and does not feel the right way to handle this.
Option (2)
Perform some kind of hack that maps user ids from the initial request and maps the correct user id to the correct token and then sending it to the client somehow ( database then GET ) I also don't like this it's hacky
What we don't want is to keep the client secret and other credentials on the front end like some examples I have seen, this is fine for personal stuff but not real apps for very obvious reasons.. All client secrets and passwords should be on the backend never sent to the client only their user JWT
So the issue here summarized, How do I return the JWT to the client without doing something hacky? the code below returns this to the client but brings us to option (1) above and obviously returns a template style which is undesirable cause I have a client-side rendered app!; I want something clean and professional, thank you.
router.get('/musicAuthCallback', function (req, res) {
const spotifyCode: string = req.query.code;
if (production.ROUTE_LOGGING) {
routeLogger.info('Spotify endpoint callback hit');
}
const _spotifyService = new SpotifyService();
_spotifyService.tradeSpotifyAuthToken(spotifyCode)
.then((jwt: any) => {
if (jwt === false) {
res.send({ "message": "Unable to get JWT for Spotify", "status": REQUEST_FAILED, "title": "Authentication Error" });
} else {
const template = `<h1> Success! </h1> <script>
var main=window.open("http://localhost:4200/");
main.setItem('spotify_jwt', ${jwt});
</script>`
res.send(template)
}
})
.catch((error) => {
logger.error(error);
res.send({ "message": "Something went really wrong..", "status": REQUEST_FAILED, "title": "Please Try Again.." });
});
})
This is silly but kind of illusive until you poke around the docs more.. the docs didnt make it clear to me I could use "state" as a query param.. in this i was able to pass the users ID into here so &state=600 and this is passed into the users callback URL which makes it possible to attach a user to a specific JWT given by Spotify
https://accounts.spotify.com/authorize?client_id=5fe01282e94241328a84e7c5cc169164&redirect_uri=http:%2F%2Fexample.com%2Fcallback&scope=user-read-private%20user-read-email&response_type=token&**state=123** <- this can be what you want! and can retrieve it in your callback URL sitting on your NodeJS server like this..
const spotifyCode: string = req.query.code; // jwt
const userID: string = req.query.state; // value you passed in

Redirecting in a direct way, is it a good practice? Express, Node.js

I have two questions about express. From a user login page, I call the below API function.
Is there a reason for me to have res.send(token) in the below code, I have commented it out. Is this needed for testing Postman?
When this is being called, then is it a good practice to redirect to the site I want after it like return res.redirect('http://127.0.0.1:8081/en/UserSite/profile.html');? Or do I need to think about extra settings, but for now, I can leave this as it is...
router.post('/', async (req, res) => {
//validates the request.
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({email: req.body.email});
if (!user) return res.status(400).send('Invalid Email or Password.');
//Here we compare the password for re-hashing the password.
const validPassword = await bcrypt.compare(req.body.password, user.password);
if (!validPassword) return res.status(400).send('Invalid Email or Password.');
//const token = jwt.sign({_id: user._id}, config.get('jwtPrivateKey'));
const token = user.generateAuthToken();
//res.send(token);
return res.redirect('http://127.0.0.1:8081/en/UserSite/profile.html');
});
You can send ONE response per http request so you would have either res.send(token) or res.redirect('http://127.0.0.1:8081/en/UserSite/profile.html');, but not both since they are each sending a separate http response.
Which one you want depends entirely upon what you want the result of this http request to be. That isn't something we can determine for you.
Is there a reason for me to have res.send(token) in the below code?
Yes, if you want the http request to return the token so it can be used by the caller.
I have commented it out. Is this needed for testing Postman?
Again, this depends only upon what you want the result for your http request to be. This should have nothing to do with Postman. It has to do with the design objective for your http request and what result you want the client to receive.
When this is being called, then is it a good practice to redirect to the site I want after it like return res.redirect('http://127.0.0.1:8081/en/UserSite/profile.html');? Or do I need to think about extra settings, but for now, I can leave this as it is...
Again, this depends upon what the design objective is for this route is which you have not shared. The code looks like it is generating a token that you don't seem to do anything else with so if you don't return the token to the client, I don't know what the point of the entire route would be.
Typically a JWT token like this would be used for programmatic access to a REST API. For general browser access, you would store some sort of sessionID in a cookie and then you may redirect after login and the cookie can remain in effect to indicate this is a logged in client. To be useful by itself a JWT token has to be returned to the client and then the client has to present that token on future http requests. This is something that a browser does not do by itself for general web page browsing so this would be used for programmatic access (such as Ajax calls).

How to make HTML auth form and JSON Web Tokens communicate together in Ionic/Angular

I'm working on an Ionic application.
On the one hand I have an auth basic form in which people fill in their username and password. On the other hand I'd like to implement authentification with JSON Web Tokens and Node JS.
The workflow would be this one : as soon as a user fills in his credentials, they will be sent with a POST request. If these credentials are correct, the user can access to the application and gets an access token as a response.
The thing is that I'm a little bit lost with all that concepts. I built a form and sent informations with a POST request. I managed to create some APIs with Node JS and that's ok. I see how to build a authentified webservice too (e.g : https://github.com/jkasun/stack-abuse-express-jwt/blob/master/auth.js).
But I concretely don't understand the links between the html form and the authorisation check part..
To be clearer, how is it possible to make the html part and the Node JS scripts communicate together ?
Before posting that question I made many researches and found many stuff on building an authentified API. But there was very few advice on how to make it communicate with the client part (I mean the form), which is what I have to do.
If anyone has any ressources (document, Github examples..) on that, I'll greatly appreciate. But I would be very happy too if someone try to make me understand these concepts. I guess I have to improve my knowledge on all that so that I could test some POCs.
Many thanks in advance !
JWT General flow:
1- Authenticate using a strategy (You done it)
2- Deliver an accessToken along with response (You done it)
3- The client MUST store this accessToken (LocalStorage is the best place, not cookies: They are vulnerable to csrf attacks)
4- On every request you are going to make to a protected area (where user is supposed to be authenticated and authorized), make sure to send you accessToken along with it, you can put it on Authorization header, a custom header, directly in body of the request... Basicaly just make sure to send it properly.
5- On the server receiving client requests, you NEED to verify that token (You verify it by checking the signature of the accessToken).
6- If he is authorized, great, if not, send back an HTTP Unauthorized Error.
Here is my implementation using an accessToken on a header + passportjs-jwt:
Client code
To store token:
localStorage.setItem('accessToken', myAccessToken);
To send it:
const myAccessToken = localStorage.getItem('accessToken');
{
headers: {'Authorization', `Bearer ${myAccessToken}`}
}
Server code
1- Configure passport
passport.use('jwt', new JwtStrategy({
jwtFromRequest: jwtPassport.ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: myAccessTokenSecret,
passReqToCallback: true
}, (req, payload, done: (err?, user?) => void): void {
User
.findOne({where: {id: req.params.id}})
.then((user: User) => {
if (!user) {
return done(new Error(`No user found with id: ${req.params.id}`), null);
}
return done(null, user);
})
.catch((e: Error) => done(e, null));
}));
Pay attention to callback: If your callback is called, it means that passport has successfuly verified the token (It is valid). In my example, i get the user details in database and this is the user that will be returned and put in req.user object passed to my controller below:
2- Finally, the controller route (protected area):
.get('/users/:id', passport.authenticate('jwt'), (req, res, next) => {
// do stuff in protected area.
}
And that's it. If you want more security, check refreshTokens implementation.
I used passport because i found it relevant in my case, but you can write your own handler, by using jsonwebtoken and just calling its "verify" function.
You can find documentation of passport jwt strategy here => http://www.passportjs.org/packages/passport-jwt/

Preventing man-in-the-middle attacks with user authentication (Node/Vue/Passport)

I currently have a webapp I'm writing in Node/Vuejs with Passport handling authentication, and I've run into a problem. I was thinking about how I have authentication currently set up and I realized I had a glaring security hole.
In short, I have my Vuex store hitting a local API endpoint /api/me. That endpoint does a simple return of req.user. For the sake of brevity, a typical response looks like this:
{
username: 'Bob',
roles: [] // normal user has no roles,
email: 'someguy#bob.com'
}
My admin route /admin has a beforeEnter check, as shown below, that incorporates this check using the Vuex store, so I can have a cached version of user data accessible on the frontend.
{
path: '/admin',
name: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
store.dispatch('getMe').then(() => {
if (store.getters.user.roles && store.getters.user.roles.includes('administrator')) {
next();
return;
}
next({ path: '/' });
});
}
}
Here's the thing though - I realized that someone could easily game the system. In fact, I tried it myself with a test, non-Adminstrator account, and I was able to get in by returning the following from a local server set up for this purpose in Postman:
{
username: 'Super Admin Joe',
roles: ['administrator'] // normal user has no roles,
email: 'admin#bob.com'
}
And viola! The user now has full access to admin pages.
My question is, how could I prevent against this?
I need to check that the user is authenticated on every page, but a potential attacker could quite easily proxy any request (in this case it's /api/me) to make themselves any user they want. They can login normally with their own account, open the Network tab and copy the response payload, then change the user data as they wish. There needs to be some sort of encryption between the frontend and backend when checking a users' logged-in status, I believe.
I tried thinking about how I could prevent this from happening, but anything on my end (server-side, at least) seems useless as any request could easily be redirected to an attacker's local machine.
Any advice on how to "sign" my requests to make sure they aren't being proxied? Thanks in advance!
You shouldn’t have to be signing the response body of an api request. The typical way to do authentication is to establish a signed session cookie that acts either as an identifier to session information in an external database, or contains session information itself. This cookie should be in the header of your response and passport should give you a way to administer this cookie without you even realizing it.
This way the user can’t tamper with the information sent from the server in a way that’s easy to detect, and since it’s a cookie it will automatically be sent with each request by your browser (although if you’re using some AJAX library you may have to explicitly specify you’d like to send the cookie). What MadEard was referring to in the comment is where the cookie information is able to be accessed using passprt which is the ‘user’ property in the ‘req’ object.
After reading your github files:
server.get("/admin", function(req, res){
if(req.user && req.user.roles.includes("administrator")){
//user is an administrator, render the admin panel view
}else{
//is not an admin, redirect or send error message
}
});
In every Express route, after authentication with Passport, you have the req.user object.
It is established by checking the request cookie connect.sid, and checking which session this cookie belongs to on the server.
As such, you can trust that in any Express route, the object req.user contains the information relevant to that cookie and you can act upon it.
A little note: doing server-side validation should become a reflex for you over time.
The client is meant to display information. If, at any point, you are making the client take any decision that could be a security liability, take a step back and think it again.

How should I implement a token based authorization API in Node.js and Redis?

I'm working in a web app which handle resources from a Mongo database, for such resources I'd like to offer an API, so a future mobile application can seize it or consume it from a raw client.
However I'd like to have web app consuming same API, here is where I get a bit confused about how to properly implement this.
Here is what I've done so far:
API Auth:
app.route('/api/auth/')
.post(function (request,response) {
var email = request.body.email;
var password = request.body.password;
var login = new Account({"local.email":email,"local.password":password});
Account.findOne({"local.email":email}, function (err,user) {
if (err) {
response.send(500);
}
if (!user) {
response.send(404);
}
else {
user.validPassword(password, function (err,matched) {
if (err) {
response.send(500);
}
if (matched) {
var uuidToken = uuid.v4();
redisClient.set(uuidToken,user._id,redis.print);
redisClient.expire(user._id,100);
response.send(uuid);
}
else {
response.send(403);
}
});
}
});
});
So basically I receive consumers username and password, I authenticate it against database, If it matches I reply a token, (actually an UUID). That token gets stored at Redis paired with the user id in databse. Every future request to any API route will verify for such token existance.
Here I wonder:
How should I manage the token TTL, and renewal upon future requests?
How can I control requests per time windows limits?
Is there any security caveat in the approach I'm taking?
Website Auth:
Basically I perform SAME username-password authentication against database and I then:
1. Start a new server session.
2. Naturally, offer back a cookie with session ID.
3. I create then the Redis UUID and user ID record, which API will check. I guess this is OK as there's any sense in requesting POST /api/auth authenticating again.
Here I wonder:
Is this a best approach?
Should I include any token salt to distinguish a pure API consuming request from a request from web app?
Is there any security caveat in the approach I'm taking?
Should I include more tokens?
This is example of POST /login:
app.route('/login')
.post(function (request,response,next) {
var email = request.body.email;
var password = request.body.password;
var login = new Account({"local.email":email,"local.password":password});
Account.findOne({"local.email":email}, function (err,user) {
if (err) {
response.redirect('/error');
}
if (!user) {
var cookie = request.cookies.userAttempts;
if (cookie === undefined) {
response.cookie('userAttempts',1);
}
else {
response.cookie('userAttempts',(++cookie));
}
response.redirect('/');
}
else {
user.validPassword(password, function (err,matched) {
if (err) {
// Redirect error site or show err message.
response.redirect('/error');
}
if (matched) {
var session = request.session;
session.userid = user._id;
var uuidToken = uuid.v4();
redisClient.set(uuidToken,user._id,redis.print);
redisClient.expire(uuidToken,900);
response.cookie('email',email);
response.redirect('/start');
}
else {
var cookie = request.cookies.passwordAttemps;
if (cookie === undefined)
response.cookie('passwordAttemps',1);
else {
var attemps = ++request.cookies.attemps
response.cookie('passwordAttemps', attemps)
}
response.redirect('/');
}
});
}
});
})
I think I could get rid of using and writing a typical session implementation and depend somehow on the similar token based auth the API has.
What you have there is on the right track and basically replaces some of the functionality of cookies. There are a few things to consider though, and you've touched on some of them already.
While using a UUID (v4 I'm guessing?) is good in that it's nondeterministic and "random", on its own the token is worthless. Should redis lose data the token no longer has any context. Nor can you enforce expirations without help from redis. Compare this to a JWT which can carry context on its own, can be decrypted by anybody with the correct key, can handle expirations, and can enforce further common application level constraints (issuer, audience, etc).
Rate limiting. There are a number of ways to handle this and few of them are tied directly to your choice of token scheme aside from the fact that you'd probably use the token as the key to identify a user across requests in the rate limiter.
Transparently passing the token in both a web app and on other clients (mobile app, desktop app, etc) can be a huge pain. In order to access private resources the user will need to pass the token in the request somewhere, likely the headers, and in the case of a web app this means manual intervention on your part to include the token in each request. This means hand coded ajax requests for all authenticated requests. While this can be annoying, at least it's possible to do, and if you're writing a single page app it's likely you'd do that anyways. The same can be said for any mobile or desktop client. Since you already have to make the HTTP request directly in code anyways, why does it matter? Now imagine the scenario where an HTTP GET endpoint, which returns an html page, can only be accessed with proper authentication. In the case of a web app the user is very likely going to access this via a browser redirect or by typing it directly into the URL bar. How is the token added to the request? Other than using cookies, which you're explicitly not using because mobile and desktop clients do not implement them, this is not really possible. However, if your API clients can always modify the HTTP request structure this isn't really a problem.
Now for a shameless plug, our team has a library we use for this. It's mostly used internally and as such is pretty opinionated on its dependencies (express, redis), but hopefully it can help you here. In fact, that library is pretty much just a JWT wrapper around what you have in place. If you decide to use it and notice any issues or deficiencies feel free to file any issues on github. Otherwise there are a whole bunch of other JWT based session management modules on npm that look promising. I would check those out regardless as there are very likely better modules out there than ours. Again, ours is used internally and came about from a pretty specific set of use cases so the chances that it captures all of yours are pretty slim. On the other hand, it sounds like you're using a similar stack so maybe the shoe fits.
If you do use ours it may seem odd that there's a split in the API surface on that module in that you can choose to store data directly in the JWT claims or in redis. This was deliberate and I think your examples illustrate a good use case for both sides. Typically what we do is store the user's email and name in the JWT claims, then store more dynamic session data in redis on their session. For example, upon logging in you'd add the issuer, audience, and user's email to the JWT claims but leave off anything related to "userAttempts". Then upon failed attempts you would add or modify the "userAttempts" on the session data stored in redis related to that JWT. Once a JWT is set it's not possible to modify its contents without generating a new one, so be aware that if you decide to keep relatively dynamic data in the JWT you'll have a constant exchange of old and new JWT's between the server and client.

Resources