Basic Auth and JWT

I am currently running a Node.js application with support for APIs and files (I know that nginx can handle this, but I should not have used it first).

I just use it to have a basic basic auth, which happens to be not so simple.

Here is my nginx configuration:

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 file /etc/nginx/.htpasswd just user:encryptedpassword and good.

With this configuration, when I go to my IP address:

  • asks the user and password
  • starts page loading
  • (sometimes) asks for user and password again
  • finishes page loading

So far, so good, even if he requested the password twice.

The Node.js application has JWT authentication, when I log in, the website reloads and from here it asks for unlimited time for the user and password (basic auth) while I click on the login. JWT is in my local storage. If I click cancel in the base auth request, the JWT will be deleted and I will be logged out and it will ... request the base auth again.

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

This is rather difficult to explain, and I cannot show you the site. In short, the main problem is that the JWT (from the Node.js application) is removed.

+5
source share
1 answer

When I realized that the problem was related to the conflict between Basic Auth and JWT (like @Curious suggested in the command), and that both of them use the Authorization header, the solution was pretty easy.

I am setting up the front-end application to send the JWToken through the user header **JWTAuthorization** , so when the request hits the server, it contains both the Authorization and JWTAuthorization . Then it is quite simple, after the basic auth is passed, I just replaced the headers (here in the Node.js application, based on Koa):

 app.use(function *(next) { this.headers.authorization = this.headers.jwtauthorization; yield next; }); 
+5
source

Source: https://habr.com/ru/post/1240952/


All Articles