Are JWT encryptions safe if they are accessible to client javascript? If not, how do I use them to authenticate my web socket connections?
tl;dr - yes it is ok to use JWT for web socket connections, if certain regulations are kept in mind
Let's start by summarizing what a JSON Web Token (JWT
) is. A JWT
is structured out of three parts: Header, Payload and the Signature.
The Header contains the type of the token and the signing algorithm , i.e. HS256 or RSA. The Header is Base64Url encoded.
The Payload contains claims and can also include custom data like a user id from a database. The Payload is as well Base64Url encoded.
The Signature (the last part of the token) is created out of signing the Header, the Payload, and a Secret
that only you know of, using the specified algorithm.
So knowing that, we can say that the contents of the token (the header and the payload) is not secure and therefore shouldn't contain sensitive data. But the fact that the token is signed with a secret
only you know of (your server) makes it very secure for the purpose of what it is used for. Because even if the token is used from the client side, only YOU can give out these tokens and only YOU can create valid tokens. One can not simply fake tokens that would work in your api. Still someone could steal the token on the client side of things but keeping a short expiration time of the token works in your favour.
As long as you don't use long-live tokens or even infinite valid tokens (expiration time) I would say it's a solid solution. Normally JWT is used in a REST API environment, so the user first authorizes using an authentication endpoint, with username and password for example, and then gets handed out a valid JWT.
I would suggest the same for establishing the web socket connection (in your case socket.io). Something like this ( of course this depends on your backend situation ) :
// client
const axios = require('axios');
const io = require('socket.io-client');
const { token } = await axios.post('/auth/login', credentials);
const socket = io("ws://example.com/", {
auth: {
token: "123"
}
});
// server
// socket.io middleware
io.use((socket, next) => {
const token = socket.handshake.auth.token;
// ... check token or whatever
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With