Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protect static files using jwt authentication

I'd like to protect static files with JWT authentication. Is it possible to achieve without cookies? As I know the most common scenario for JWT is to pass token in request body or header, making AJAX call. But when browser requests static files (JS, CSS ... ), there is no way to add body to this request. So the only way is to store jwt token in cookie? Or there are others?

Update

Did you have specific objections to a cookie?

Im reading articles, and everyone is passing jwt token in body or Authorization header. I develop website with admin panel - SPA application, so Im wondering, should I protect html, bundle.js, css of this panel with cookie or protect only API and make these files public. Just want to know what is the common flow. And I thought, maybe it's possible somehow, to protect these files with Authorization header (like Basic Auth) but using JWT

like image 470
asv Avatar asked Aug 16 '17 20:08

asv


2 Answers

Most often it is unnecessary to protect static assets (e.g. .html, .css, .png, .js, etc.) files and protecting your API endpoints would suffice.

However, if you retrieve the assets (e.g. HTML fragments for an SPA) using AJAX, then you can pass the JWT as a header inside your request and in the backend your web server can inspect the header and return the HTML fragment only if the current user is authorized to access it.

Also you can store the JWT inside local storage and configure your AJAX library to get the token from the local storage and add it to your requests before sending them to the server.

like image 84
Behrang Avatar answered Oct 06 '22 09:10

Behrang


I don't know what questions you exactly means, but I think you want to protect specify static files like personal images or some else.

If like my think, you can .use(jwt) to protect your specify static files before .use(static) files.

for example:

const express = require("express");
const app = express();
const exjwt = require("express-jwt");
const STATIC_PATH = path.join(process.cwd(), "src", "static");

app
  .use("/images", exjwt({ secret: "SECRET" }))
  .use(express.static(STATIC_PATH))

app.get('/', (req, res) => {
   res.send('...') 
});

app.listen(3000);

Like this, user can request your static files except static images files.

like image 24
Jay Lu Avatar answered Oct 06 '22 09:10

Jay Lu