2
votes

History

Sessions-Cookies Age: As I know JWT use for decrease DB requests. sessions are normally stores in DB and all request need query to authentication the request. In small website and web app it's not a problem but in big apps performance is very important.

JWT Rise: With JWT you can skip this step (query to DB for authentication) and can use valid JWT that's signing with your server. You should send JWT token in all request in header but if this token is stolen the thief can use it to authenticate forever.

To protect this you can add expire time in your JWT but before expire time the thief can use this as user can. Now you can decrease expire time (for example 10 mins) to protect users but after expiring the token real users should login with user and password and this is a nightmare.

The Refresh Token is born: Now we can mixed JWT with cookie concept. refresh tokens are store in DB and you can control this by login and logout. after access token (a JWT token with short age) expired clients sends request to some end point to refresh access token in this end point sever check the DB and search for refresh token. if refresh token in White list (or not in black list) the sever generate new access token and return to clients. Now you can store access token in memory and refresh token in local storage or somethings like this.

XSS attack: local storage is not safe and with XSS attacks hackers can steal your local storage.

httpOnly cookies: You can store JWT tokens in httpOnly cookies. httpOnly cookies set from server and clients can't access this from JS.

CSRF attack: New problem with httpOnly cookies is CSRF attack. CSRF attacks come from sessions-cookie age.

My approach

Refresh tokens is very similar to cookies and now we are using cookie and JWT together access token is traditional JWT token and Refresh token is traditional session's token. every 10 mins (JWT age in my example) we are login with refresh token (or session's token) and between them we use access tokens.

If users send 100 request every 10 mins my DB request for authentication decrease 100x

NOW My Question

Did I understand how to use the JWT?

1

1 Answers

1
votes

Nice explanation, I think you understand it well.

To add to your explanation, you may want to rotate the refresh tokens: after a refresh token is used to obtain a new access token, return a new refresh token and invalidate the old one. This would prevent someone who gained access to the old refresh token from using it.