The functions and principles of Token
1. Token of what
The Token is issued by the server when the client logs in for the first time and serves as a Token for the client to make requests. It is used as an authentication mechanism for authentication during interaction. After the first login, the server generates a Token and returns the Token to the client. No need to bring a username and password again.
2. The function of Token
- The Token is completely managed by the application, so it can bypass the same-origin policy
- Tokens protect against CSRF (Cross-site Request Access) attacks
- Tokens can be stateless and can be shared across multiple servers
- Use Token to reduce the strain on the server and reduce frequent queries to the database.
3. Token authentication process
- A user sends requests using a user name and password
- Program validation
- The program returns a signed token to the client
- The client stores the token and uses it for each request sent
- The server side validates the token and returns data
4. Storage location of Token
-
Stored in localStorage
// Store token to ls const {token} = res.data; window.localStorage.setItem(‘jwtToken’, token);
Advantages: Unlimited storage, always stored in the browser.
Disadvantages: Vulnerable to XSS attacks because LocalStorage can be accessed by javascript. So you can duplicate the request header in one unified place, so that each request has the token in the header. When the token expires, the back end will return 401. At this point, you can operate in the front end code to return to the login page and clear the token in localStorage. (Applicable to Ajax requests or API requests, which can be easily stored in localstorage) In addition, the application is required to ensure that the Token is only transferred over HTTPS.
- Store it in cookies
Advantages: Protects against CSRF attacks, because CSRF can only carry cookies in the request, where the corresponding value must be taken out of the cookie and placed in the authorization header. In fact, cookies cannot be fetched across sites (the same origin policy), so CSRF attacks can be avoided. (Suitable for Ajax requests or API requests, you can easily set the auth header)
5. Token processing expiration time
In my vUE project, I stored the Token in localStorage and dealt with Token expiration. I did this:
created() { if (localStorage.jwtToken) { const decoded = jwt_decode(localStorage.jwtToken); Const currentTime = date.now () / 1000; If (decoded. Exp < currentTime) {this.$router.push('/login'); // Other processing... } else{// No expiration processing; }}Copy the code