What are access tokens and refresh tokens?
- Access token: A key that lets you use an app or service for a short time. Example: When you log into Instagram, it gives your app an access token. This token lets you view posts, like photos, and comment for a limited time.
- Refresh token: A special key that can get you a new access token when the old one expires. Example: Netflix uses refresh tokens. When you "Remember me" on login, it saves a refresh token on your device to keep you logged in across sessions.
How to get a new access token with a refresh token
- Your access token expires. Example: You're using a weather app. After 30 minutes, it can't show updates anymore.
- Your app sends the refresh token to the server. Example: The weather app automatically sends its refresh token to the weather service.
- The server checks if the refresh token is valid. Example: The weather service checks if your refresh token is still valid and hasn't been revoked.
- If valid, the server sends back a new access token. Example: If valid, the weather service sends a new access token, and your app can show weather updates again.
Is this secure?
Yes, it's still secure. Here's why:
- Access tokens expire quickly (usually within minutes or hours). Example: A banking app's access token might only last for 5 minutes.
- Refresh tokens can be revoked if needed. The system can have a token revocation mechanism, meaning that refresh tokens and access tokens can be revoked if suspicious activity is detected or if the user logs out. Example: If you log out of all devices on Spotify, it revokes all refresh tokens.
- Refresh tokens can be bound to a specific device or IP address. If the refresh token is used from a different device or IP address, the system may reject the refresh request.
- The server can limit how many times a refresh token can be used. After a certain number of uses, the refresh token will become invalid and the user will have to log in again. Example: A gaming app might only allow its refresh token to be used 100 times before requiring a new login.
- Extra security measures like two-factor authentication can be added. Example: When you log into your email from a new device, it might ask for a code sent to your phone, even with a valid refresh token.
Remember, nothing is 100% secure, but this system helps balance security and convenience.