Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Auth and JWT

I'm currently running a Node.js application, with an API and files serving (I know nginx could handle it, but I wasn't supposed to use it at first).

I'm simply using it to have a simple basic auth, which happens to be not that simple.

Here is my nginx config:

  upstream nodejsapp {
    server 127.0.0.1:1337;
    keepalive 15;
  }

  server {
    listen 80 default_server;

    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
    proxy_redirect off;

    location / {
      proxy_pass http://nodejsapp;

      proxy_set_header Connection "Keep-Alive";
      proxy_set_header Proxy-Connection "Keep-Alive";
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;
    }
  }

The /etc/nginx/.htpasswd file is just user:encryptedpassword and is good.

With this config, when I go to my IP it:

  • asks me the user and password
  • starts to load the page
  • (sometimes) asks again for user and password
  • finishes to load the page

So far so good, even if it asked twice the password.

The Node.js app has a JWT authentication, when I sign in, the website reloads and from here, it asks indefinitely for the user and password (basic auth), as long I click on login. The JWT is in my local storage. If I click cancel on the basic auth prompt, the JWT is deleted and I'm logged out, and it... asks again for the basic auth.

This is on Chrome. With Firefox and Safari, after the JWT logging, it automatically deletes the token from the local storage (and I'm logged out).

It's pretty difficult to explain and I can't show you the website. In short the main problem is that the JWT (of the node.js app) is deleted.

like image 685
Cohars Avatar asked Jan 19 '16 19:01

Cohars


1 Answers

When I realised that the problem was the conflict between Basic Auth and JWT (as @Curious suggested in the commend), and that they are both using the Authorization header, the solution was quite easy.

I configure my front end application to send the JWToken via a custom header, **JWTAuthorization**, so when the request hits the server, it contains both headers Authorization & JWTAuthorization. Then it's pretty simple, after the basic auth is passed, I just replace the headers (here on the Node.js application, based on Koa):

app.use(function *(next) {
  this.headers.authorization = this.headers.jwtauthorization;
  yield next;
});
like image 90
Cohars Avatar answered Oct 20 '22 04:10

Cohars