Search code examples
angularjwtangular2-jwt

Should we base heavily on local jwt token expiry date to authenticate user


I am learning angular2 by following some tutorials on the web. When making a login page using jwt token, lots of examples approach like: - when user inputs email and password, submit event will call authentication api - successed authentication will return a token with expiry date in payload. This token is stored in localstorage - restricted routes navigation will check authenticated user by getItem from localstorage, check token existence and expiry date

My problem is: I can easily go to jwt.io with the token in localstorage, change the expiry number to something else later, copy the new generated token and manually paste back to localstorage item

My thought: Call api tokenValidation before any route navigation, bit it seems will introduce lots of server calls

Appriciate your thoughts


Solution

  • No, you can't do that. The whole point of JWT tokens is that they are cryptographically signed, using a key that only the server knows. So if you try to tamper with the expiry date or anything else in the token, the server will detect that the signature does not match, and will reject the token.

    So yes, you'll be able to go to the guarded route, but as soon as you try to make an HTTP request, you'll get an error from the backend (or at least you should get one). The client-side guard is not really a security measure: the code of the component is available anyway in the downloaded bundle. It's an ergonomic measure: if the user can't access a route, he/she can be automatically redirected to the login page, for example.