JWT (Json web token) Vs Custom Token

2019-03-18 15:47发布

问题:

I was looking through the questions but I did not find anything which could solve my doubt. I found extensive information about JWT, but not much when comparing the advantages JWT could offer over generating a custom token to authentication requests against REST services.

What is the advantage to use a JWT (Json Web Token) over generating a custom generating token ? To generating the custom token I could use some hashing strategy or some unique random number generator.

If I generate a custom token, Could I have any security concerns ? Would you recommend to use any other authentication mecanism ?

Thanks!

回答1:

JWT tokens contain claims, which are statements about the subject (for example the logged in user). These statements can be things like name, email, roles etc. JWT tokens are digitally signed and not vulnerable to CSRF attacks.

These two characteristics make sure that the service receiving the token does not need to go back to the issuing authentication server to verify the validity of the token or get information about the subject.

This increases the ability of a system using JWT tokens to scale in a significant way. JWT tokens do require a secure transportation channel (HTTPS).

The downside of this is that tokens cannot be revoked (as there's no central server guarding over these tokens). That's why tokens typically have a short lifetime.

Tokens holding a session id on the other hand do need to contact the authentication server to validate the token (usually database lookup) and retrieve information on the subject (another database lookup).

Validation of HMAC tokens requires the knowledge of the secret key used to generate the token. Typically the receiving service (your API) will need to contact the authentication server as that server is where the secret is being kept.

HMAC tokens and session ids are typically stored in cookies. Cookies cannot be used for cross-domain service calls and need to be protected against CSRF attacks.



回答2:

From Django REST framework documentation,

JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token.