My application backend runs on Django Rest Framework and and frontend on Angular.
I'm already using JWT for authentication and that works fine.
My requirement is to call a specific API (Not authentication related), which gets me some details in plain text. I don't want it in plain text, So I was thinking I would create a JWT Token and send it in response and decode it in frontend using the secret key.
I achieved the decoding part using jwt-decode without the secret. My concern is, if an attacker intercepts my response and modifies the token, How do I tackle that situation?
This is how I decoded the token in angular
try {
decoded = jwt_decode(token);
return decoded;
} catch (Error) {
return null;
}
Is there a way I could verify/decode my token with secret in Angular? something like:
data = jwt.decode(encoded_token, 'SECRET_KEY', algorithms=['algo']) # Python Code
Kindly guide me here. If there are any other methods to achieve what I Want please let me know
CodePudding user response:
I don't want it in plain text, So I was thinking I would create a JWT Token and send it in response and decode it in frontend using the secret key.
A JWT token is usually plain-text. There are two types of JWTs - JWS (signed JWTs) and JWE (encrypted JWTs). The latter has the content encrypted, so no one can read it unless they have the key for decryption. Encryption is hard to configure and manage, though, so JWEs are not used very often. You need a really strong reason to be using JWEs. Signed JWTs (JWS) are more common. In fact, when people use the term JWT, they usually mean JWS. A signed JWT is integrity-protected. Using the signature you can verify that the JWT hasn't been changed by an attacker, but they are plain-text. Anyone can read the content of the JWT, they just can't modify it.
Also remember that an Angular app has all of its code available to users, which means it can't hold any secrets. If you put a secret in your Angular app, then anyone will be able to read that secret and use it to decrypt your JWEs, or forge new JWSs, if you're using symmetric signing (e.g. the HS256 algorithm).
I achieved the decoding part using jwt-decode without the secret. My concern is, if an attacker intercepts my response and modifies the token, How do I tackle that situation?
If you're concerned about a Man-in-the-middle attack, so that someone will modify the response from your server, then all you need is an HTTPS connection. If you connect to your API using HTTPS, then you're sure that no one modified the response, nor read it.
If you're concerned that your response will get modified after HTTPS is terminated (e.g. a malicious code running in the browser), then you can use JWS to ensure the integrity of the response. You just have to remember to use asymmetric signing, so that the Angular app only keeps the public key.
I don't know which library for JWTs are you using in Angular, but I think all of them are capable of verifying signatures, so that shouldn't be a problem.