Disabling sessions in nodejs Passport.js - javascript

I just discovered about Tokens for authentication which allows session/stateless servers and starting out with MEAN. Looks amazing.
Right now, I'm using Passport.js to authenticate users (via Email, Facebook, Google,...), which stores information into the server session like all the tutorials say:
// required for passport
app.use(express.session({
secret : 'superscret',
expires: new Date(+new Date + settings.session.sessionTimeout),
store: new MongoStore({})
})); // session secret
app.use(passport.initialize());
app.use(passport.session({}));
Is it possible to still use Passport.js but instead of storing the session, sends back a token to monitor if the user has access.
Question: How can disable sessions for passport? (I know how to send the token and listen for it).

I suggest using satellizer, de-facto standard library for token based authentication in AngularJS. It implements token based authentication only and is much easier to get working for your purposes. It also has good server examples, including Node.js server example.

passportjs supports disabling of the sessions. Docs passport
After successful authentication, Passport will establish a persistent login session. This is useful for the common scenario of users accessing a web application via a browser. However, in some cases, session support is not necessary. For example, API servers typically require credentials to be supplied with each request. When this is the case, session support can be safely disabled by setting the session option to false.
app.get('/api/users/me',
passport.authenticate('basic', { session: false }),
function(req, res) {
res.json({ id: req.user.id, username: req.user.username });
});

Related

Nodejs authorization approaches

Before I have to say that I've found some post related this question but not fully answered.
So I implement a nodejs REST API server, DB with mongoDB, however about authentication i understand the idea, with jwt token it work perfect.
/api/login
you get response with token. now you can request resource with this token
for example.
api/posts/:user_id
get all your posts...No problem! query with mongoose findBy.. bla bla!
so for authorization in this case it's easy, check for query param user_id is equal to token (token parse with user_id). boom resources is secure.
but in case that I have some resources they're not reference by user_id, What is best practice to protect this resources?!
example
api/settings/:settings_id/emails
imagine that I know the setting_id of other user, and i authenticated with token. so how server will know this resources is not allowed for me?
First, you should do more to protect the token in the first place. When you issue a token after a user logs in you should store their token on either web storage like sessionStrorage if https is enforced or use an httpOnly cookie (You can add a user-agent/geoip fingerprint in addition to the user_id upon signing this token to add an additional layer of security). Then, when a user makes a request for a protected resource, you can match the fingerprint and user_id you signed the token with to the user they are making the request in behalf of.
You could use something like passport-jwt as a middleware in express to require authentication on routes. In passport, you define an extractor handler that basically tells it where to look to see if the user has a token and if they do and it validates it adds the req.user property that you can use on subsequent requests to determine the user_id of the token bearer. So basically with this approach, you know the user_id on every request which lets you compare that with the user information they are requesting.
app.post('/settings/:settings_id/emails', passport.authenticate('jwt', { session: false }),
function(req, res) {
res.send(req.user.id);
}
);

What is the best way to access the JWT from node?

I have implemented JWT authentication using Node.js. When the user signs in, Node.js signs/creates a JWT and sends it back. Thereafter, it is stored in the localStorage. Now, this is probably where I am going wrong, but... to move forward, I make use of the express router, and within the router code (which is obviously at the node level) I want to be able to access the token (which is in localStorage) so that I can make a call to the API for further data. However, I just realised that localStorage is at the client-end and that node/express/router doesn't recognise localStorage. So I am stuck. Obviously, I am doing something fundamentally wrong... I should not need to access localStorage from the express router file. Perhaps, I should really be making the API calls not from the express router file, but from client side.
Any hints/directions?
localstorage is bad way to save token. you should save token in cookies and use then where you want.
EXAMPLE:
new Cookies(req,res).set('access_token',token,{
httpOnly: true,
secure: true // for your production environment
});
and then read:
var token = new Cookies(req,res).get('access_token');
You need to send the JWT that is stored on the client side every time you make an API request to the server side.
https://jwt.io/introduction/
Scroll down to the section How do JSON Web Tokens work? The JWT should be sent in the header of the API calls in the form:
Authorization: Bearer <token>
How you do this depends on how exactly you'll send the HTTP requests to the API, but it should be pretty simple in any respects. You can find out about how to add Headers to an angular $http request at this link:
https://docs.angularjs.org/api/ng/service/$http
Then it's up for each of your authenticated express routes to check the headers, pull the JWT out, ensure that it's valid, and then proceed with the request (or halt it if the JWT is invalid).

How to manage JWT when Cookies are disabled

I've been reading articles about JSON Web Token (which is completely new to me) and its safe mechanism to transmit information between parties in order to avoid server Sessions.
I'm building a web app from scratch using Java, Tomcat, Jersey framework for Web Services and JOSE4J for the JWT.
Many articles advice to use Cookies httpOnly instead of localStorage
I've already created a restful method like this with a cookie and the jwt
#GET
#Path("/authenticate")
#Produces(MediaType.APPLICATION_JSON)
public Response authenticate(
#HeaderParam("username") String username,
#HeaderParam("password") String password) throws JSONException,
IOException, JoseException {
Service service = Service.getInstance();
EmployeeProfile employeeProfile = service.authenticate(username, password);
// Temporarily httponly and secure as false to test
NewCookie cookie = new NewCookie("jwt", service.getToken(), null, null, null, 900, false, false);
return Response.status(200).cookie(cookie).entity(employeeProfile).build();
}
return Response.status(204).entity(null).build();
}
When I run my webapp in Chrome I can see that the cookie was saved correctly.
Now I can use this token to call further restful methods with no need to authenticate again, but what if Cookies are disabled? I cannot retrieve the cookie as I tested in incognito mode. In that case I can verify if cookies are enabled and warn the user to enable them in order to proceed with the login process.
To check cookies I do this:
$.cookie('test_cookie', 'cookie_value', { path: '/' });
if ($.cookie('test_cookie') !== 'cookie_value') {
//Cookies are disabled. Show a modal.
}
But this is very restrictive. So I wonder what would be my alternative to retrieve the jwt from server? I am not very sure about this, but should I change the controller to send the jwt as a part of the response in json and keep it in the localStorage even if this can expose my token to XSS attacks? However, using cookies can be also susceptible to CRSF attacks but not if I set httpOnly and secure properties to true, but in that case I won't be able to read the cookie with javascript. I am confused about this.
Thanks in advance.
You are right , You need to change your controller and send the JWT is part of the response as well as the cookies with flag httpOnly due securities, but the question is are decrypting JWT in client side and using some value from there. if "No", then no need to send JWT as part of the response.. if "Yes", better take out all that values from the token and send a separate json object in response header.

Token based authorization in nodejs/ExpressJs and Angular(Single Page Application)

In my application,while registering the users i am saving username,password and jwt generated token with these fields in MONGO DB.When user tries to login with correct credentials then i will send the response with stored token.Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.But I found some issues regarding this procedure:
I am generating same token for one user every time.So if any third person is able to get the token then he can access the restricted page.
Am i wasting space in db by storing the generated token in MONGODB
Can Anyone access the token stored in localstorage other than the user.
for each and every request in my single page application,I am again querying mongodb to get the token for that user and validating.Here,I am checking both client side and server side.
I am using jwt to generate tokens,Node,Express,Mongoose in my application
Am i following the good procedure.If not,can you please provide the solution for my approach or any new approach.
I have searched many sites for token based authorization and session based authorization,But nothing worked for me.
Note:I am beginner for Nodejs,AngularjS
You should store token in advanced key-value cache tool like: Redis
That would improve performance remarkably.
You will get token from database for 1st time then it should be stored in Redis. I used to set token as key and username as value. Next request , the token will be given from cache. with Redis you can set expire for token.
When a user registers, you would need to generate a JWT like you're doing now. That's OK. You don't need to save it to the database however. You didn't ask but I assume that the password should not be stored in clear text. You can use something bcrypt to encrypt before saving it to the database.
When user tries to login with correct credentials then i will send the response with stored token
Yes, that's correct way to do.
Then at client side(In my controller) i am using the localstorage to store the token so that i can send the same token for each and every request sent by the client.
Yes, on the client side, you can save the JWT to local storage and send it in subsequent requests to the server.
Now your bullet points:
So that you won't have the same JWT each time, you can include an "exp" claim in the payload (I'm assuming you're using something like jwt-simple to generate a JWT). Something like:
var payload = {
sub: account.username,
exp: moment().add(10, 'days').unix()
};
var token = jwt.encode(payload, "secret");
You don't need to store the JWTs in the database. In some cases, the token issuers (the authorization servers) are not the same as the resource servers. The resource servers only receives the JWTs in a request but there's no way for the resource servers to touch the database used by the authorization servers. Side note: If you eventually need to support refresh tokens, i.e. the JWTs that you hand to the clients will need to eventually expire, then you can store the refresh token in a database. Refresh tokens are not the same as JWTs (access tokens). The complexity to support refresh tokens will increase.
Local storage is not where you store passwords, but it can be used to store JWTs. For that very reason, a JWT must and should expire after a certain time.
Not sure what you mean by saying you check both client side and server side. When the client needs to access a resource (again it's fair to assume that the resource server might not be the same as the authorization server), the only thing that the resource server is passed is the JWT. Anyone can decode a JWT. For example, try to paste your JWT on this site http://jwt.io/. That's why a JWT should not contain any sensitive data. But if the resource server knows the secret that the authorization server uses when it encode the JWT, the resource server can verify the signature. Back to your third bullet, that's why it's OK to store the JWT in local storage of the client.
Update I'm updating this to answer to some of your questions in the comment box.
User clicks on 'Login' button triggers the Angular controller to post a request to the server, something like:
$http.post(url, {
username: $scope.username,
password: $scope.password
}).success(function(res) { ... })
Server receives the POST request, it checks username/password, then it generates a JWT, and sends back to the browser. Note that it does not have to save the JWT to the database. The code would be something like
var payload = {
sub: account.username,
exp: moment().add(10, 'days').unix()
};
var token = jwt.encode(payload, "secret");
res.status(200).json({
token: token
});
Back on the client side, in the success() callback above, now you can save the JWT in local storage:
.success(function(res) { $window.localStorage.setItem('accessJWT', res.token) })
The user is now authenticated. Now when user wants to access a protected resource, user don't have to provide username/password. With the JWT which can be retrieved from local storage, the client can now put the JWT in the Authorization header of the request using the bearer scheme, and sends the request to the server. In code, it would like:
headers.Authorization = 'Bearer ' + token;
The server receives the request. Again, this server receiving this request does not have to be the same as the server which generates the JWT above. The 2 servers can be in 2 different continents. Even if you save the JWT above, that does not do any good to this server which can not access the database where the JWT is stored. But this server can pull out the bearer token from the header of the request, validates the token and carries on with the normal tasks.
Hope this helps.
You do not want to store the JWT in mongoose because it appears in headers when logging in. You first generate a token then hash it using a module like crypto.
There are different ways to do this and they all use Passport which handles the tokens. Here's an example project Satellizer
I would recommend you generate the angular-fullstack project. Then go through the server/auth folder and the client/account folder. You will see how to securely handle authentication in a MEAN based app.

Facebook login with Parse client site, use user object with Express js

I am trying to create a login procedure with the Parse and Facebook Javascript SDK. The authentication works without a problem on the client side, but I need to access the user object (created by Parse SDK) on the server side too. How can I do this the most elegant way? I thought when I log in into Facebook via Parse a cookie is set and so I can access the user object from the server. Or should I do the login process server side? Any recommendations?
I'm facing the same problem. Turns out that you can use either server-side auth or client-side auth. You cannot mix-and-match the two. Have a look at their official blog post about sessions.
var parseExpressCookieSession = require('parse-express-cookie-session');
// In your middleware setup...
app.use(express.cookieParser('YOUR_SIGNING_SECRET'));
app.use(parseExpressCookieSession({ cookie: { maxAge: 3600000 } }));
// Making a "login" endpoint is SOOOOOOOO easy.
app.post("/login", function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function() {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect("/login");
});
});
Also, I came across this when digging through the doc:
You can add Parse.User authentication and session management to your
Express app using the parseExpressCookieSession middleware. You just
need to call Parse.User.logIn() in Cloud Code, and this middleware
will automatically manage the user session for you.
You can use a web form to ask for the user's login credentials, and
log in the user in Cloud Code when you receive data from this form.
After you call Parse.User.logIn(), this middleware will automatically
set a cookie in the user's browser. During subsequent HTTP requests
from the same browser, this middleware will use this cookie to
automatically set the current user in Cloud Code.
...
When you work with user data, you should use HTTPS whenever possible.
To protect your app and your users, the parseExpressCookieSession
middleware requires you to use HTTPS. For your convenience, we also
provide a parseExpressHttpsRedirect middleware for redirecting all
HTTP requests to HTTPS.

Categories

Resources