Authenticating Json Web Token and Redirect After Login - node.js

I recently read Cookies vs Tokens for Angularjs and implemented the sign in and authentication piece to allow users to sign in from a sign in page. The app is setup to have the account module (responsible for sign in's, account registration, profile, etc) as a separate page which will redirect to the SPA for the main application.
After successful sign on the token is sent back to the sign in page client as a JWT and the sessionStorage / localStorage values are set via js. Finally the user is redirected (also via js) to the main application. The issue is since I am redirecting via js the header can not be set, which obviously fails the auth in the main app when loading the page (Since my auth middleware is higher than both static and auth api requests). If I attempt to redirect from the server after a form post rather than returning the token via JSON on success, the sessionStorage will not be set via js as described in the blog post.
I've come to a couple of ideas and wanted to get input on which if either is good for best practice.
From the server set a response authenication cookie 'http only' (all our browser requirements allow this) cookie which is read on the next request to the main application. The cookie would then be read by the server and allow the secured static assets to be served. My initial thought was setting a cookie defeats the purpose of using a Authorization header on every request since there is a time the cookie could then be read even if it's removed on the first api request.
Allow the previously mentioned static assets to load without authentication (html, css, application js) and on the first internal API request (which in the application is required almost immediately on load) which will then have access through Angular's $http interceptors to set the request Authorization header. The same interceptor can then redirect to the sign in page if a 401 is sent back.
I thought the second would be a simpler approach due to only needing to move the auth middleware under the static file middleware and then updating the http interceptor in Angular, but thought it might be bad practice to have static files be able to load and then redirect after the fact. Any input is appreciated.

In response to your point 1
... My initial thought was setting a cookie defeats the purpose of using a
Authorization header on every request since there is a time the cookie
could then be read even if it's removed on the first api request.
The use of the authorization header is not mearnt to be mutually exclusive to the use of cookies. The idea is to use it when it best suits the problem like in single page applications and native mobile applications. However since it does depend on some kind of client storage, preferably sessionStorage, it is recommended to even sometimes use cookies for the purpose of storing the token if there are issues with the usage of sessionStorage like in old browsers. Hence as long as you use the cookie for storing the token but NOT for authentication, you have not defeated the purpose. Refer to point 1 in the follow up article
https://auth0.com/blog/2014/01/27/ten-things-you-should-know-about-tokens-and-cookies/
If you are wondering "but if I store the token in the cookie I'm back
to square one". Not really, in this case you are using cookies as a
storage mechanism, not as an authentication mechanism (i.e. the cookie
won't be used by the web framework to authenticate a user, hence no
XSRF attack)

Related

is it possible to only recieve cookies on a particular route, rather than all the routes?

I'm implementing an auth service, where I'm using the concept of access and refresh token. Storing refresh token as httponly cookie on the client side. I want to ask, how can i make only certain api routes to have cookie in their req. like, the refresh JWT token should only be sent over /auth/refresh route only.
Cookies have these options to control when they are sent, which you can set when creating them:
Domain: auth.mycompany.com
Path: /auth/refresh
So it is really a sesign question to structure server routes accordingly. Cookies cannot support multiple paths.
Generally OAuth cookies are sent from front channel requests (browser redirects) and not used for back channel requests (Ajax calls) where the browser is likely to drop them anyway.
I would avoid building to an Auth server yourself - it is a complex component - aim to use a free system such as Curity Community Edition or Keycloak instead.

CSRF Protection with Firebase Email/Password Authentication

I am working on deploying my Node.js app into production. We had been running into some CSRF issues but after looking deeper into the problem and learning more about CSRF attacks, I'm wondering if we even need to perform these checks.
Our API is whitelisted from our CSRF checks so our mobile apps that rely on the API can run properly (we're working on securing that currently). On the web frontend, we allow our users to register/log in and create/edit their data. We use Firebase's email/password authentication system to perform authentication (https://firebase.google.com/docs/auth/web/password-auth). As I understand it, this means we don't have to worry about CSRF attacks on registering and logging in because Firebase handles that. My question is: if we make sure our users are authenticated with Firebase on each Post route in our app, does that mean we don't have to worry about CSRF attacks?
CSRF becomes an issue when you are saving a session cookie. Firebase Auth currently persists the Auth State in web storage (localStorage/indexedDB) and are not transmitted along the requests. You are expected to run client side code to get the Firebase ID token and pass it along the request via header, or POST body, etc. On your backend, you would verify the ID token before serving restricted content or processing authenticated requests. This is why in its current form, CSRF is not a problem since Javascript is needed to get the ID token from local storage and local storage is single host origin making it not accessible from different origins.
If you plan to save the ID token in a cookie or set your own session cookie after Firebase Authentication, you should then look into guarding against CSRF attacks.

Authorization (and security, in general) for web and mobile apps of the same service

Help me to understand how to implement proper security for web and mobile apps, which would be enough for my case.
What I have:
Backend. Some sort of Stateless REST API, which consumes and produces JSON text. Does not store any kind of state.
Web application. Main portal to the service functionality.
Mobile applicaiton. Provides a reduced a set of functions to users of the service
I am not going to store any state on the backend. Instead, I am going to delegate this to both mobile and web browser applications.
Now here comes the question of security. How do I properly secure that?
Since session mechanism does not really work for me, I decided to go with JWT.
In my JWT I am going to store user Id and some other information like, for instance, user's privilegies.
For mobile app, I am going to send this token as a part of a response and the app will store it inside its secure store.
Each request it will send this token as Authorization Header.
For web app, I am going to send this token via HttpOnly cookie. This token, thus, will be included in every request from the client.
The problem now is a possible CSRF-attack. To address that I thought of the following. Each user "session" will be associated with CSRF token.
Since I can't store this token on the server (remember, stateless API), I can send it as encrypted (again, with JWT) token to the client via HttpOnly cookie and non-crypted in a regular cookie.
Now, every request the web client will use non-crypted token from the cookie and send it back to the server. The server will check if this token matches from the Encrypted one which is stored in HttpOnly cookie.
Also, I am going to use different URL endpoints for web and mobile web apps. What for? In order to keep auth mechanisms described above separate - I believe this will help me to keep the service secure.
Do you think it is an OK solution? What problems do you see here?
Thanks in advance.
In general, what you described looks good and pretty standard. However, if I understand correctly, the CSRF protection is flawed.
To make sure I understand correctly: a csrf token would be stored in an encrypted httpOnly cookie, only to be sent back to the server as reference. Another cookie would have the same value but unencrypted, in a plain (non-httpOnly) cookie, and the server would compare these two. What's the point? An attacker would still be able to create a webpage to have a user make an request to your website, and both cookies would still be sent.
The reference cookie is ok to be in the httpOnly cookie for reference, but the other one should not be a cookie. It could for example be a request header value that you add to all requests. The client could receive it in a response, but not as a cookie. With jQuery in the web app, you can use the beforeSend hook to add it to all subsequent requests as a header. This way an attacker could not make valid requests from another domain.

How do you handle navigation in a token-secured web application?

I have a rather conceptual question, I'm sure it's fairly stupid, but I can't figure it out.
So I am building a simple node.js app to learn, I want to make a web app which is has a set of REST web APIs for everything (including authentication), and then the presentation.
For authentication I am using token-based auth with PassportJS.
So when a user wants to access the site, he'll obtain a token from the authentication API, in turn he'll need to pass this token in a HTTP Header on each request to the app.
My question is, how is this handled in the code? When the app gets the token (for example from a login page which hits the auth API), should it attempt to store it in the local machine (for example LocalStorage, or Cookie) and then on each new page fetch it and use it in a Header? Should each page's javascript attempt to load the token from the local storage automatically? I tried looking for an example, but haven't found a complete one that deals with how you handle navigation when you're depending on sending a header on every single request (that you want authenticated).
Thanks!
Once the user is authenticated return a secure session cookie which will be stored by the user's browser. Now on every request, this cookie will be sent by the browser to your application automatically, which you can check in your backend code (typically controller) to verify the existence of user session.

How do I use bearer tokens with regular not-ajax requests?

I might be going nuts... I have the Nancy.StatelessAuth Owin middleware for validating JWTs in the Authorization header of cross-domain ajax requests.
But before I get to there, I would like to show some simple web pages to locally logged-in users, reusing, if possible, the same authorization pipeline.
I have a login page returning a JWT cookie, as recommended by Stormpath. For ajax, I can easily set the Authorization header in javascript, pulling the value from the cookie. But for regular web pages, I would like the StatelessAuth middleware to pull the token from the cookie. Is this reasonable? Do I need to write a middleware upstream of StatelessAuth to pull the token from the cookie and put it in a header, as this thing does for query strings?
Ok for the moment, this seems to be a much more reasonable approach. I'll have cookie middleware for locally logged users accessing pages, and jwt middleware for cross domain services, then a backstop to lock out requests that are cookieless and tokenless and not whitelisted.

Resources