Know the token
1. Token is a computer term:
A token is a special frame that controls the media that a site occupies, distinguishing data frames from other control frames. Token is actually more commonly referred to as a password. Before some data transmission, the password must be checked. Different passwords are authorized for different data operations. Token based authentication method
2. In the case of complete separation of the front and rear ends,
The general idea of implementing token verification in the Vue project is as follows:
1. When logging in for the first time, the front end adjusts the login interface of the back end and sends the user name and password
2. The back-end receives the request, verifies the user name and password, verifies successfully, and returns a token to the front-end
3. The front-end gets the token, stores the token to localStorage and VUEX, and jumps to the routing page
4. Each time the front end hops to the route, it will judge whether there is a token in the localStroage. If there is no token, it will jump to the login page; if there is, it will jump to the corresponding route page
5. Add a token in the request header every time you adjust the back-end interface
6. The back end determines whether there is a token in the request header. If there is a token, it will get the token and verify the token
7. If the front-end gets the status code 401, it clears the token information and jumps to the login page
Third, specific issues
-
How do I generate a token?
-
How do I verify a token?
Lead to JWT
What is JWT:
JsonWebToken, generally speaking, is used as a token of web application in the form of JSON. It is used to securely transfer information between parties as JSON objects. Data encryption and decryption can be completed during data transmission.
What can JWT do?
Authorization: Using the most common scheme of JWT, once the user is logged in, each subsequent request will include JWT to allow the user to access routes, services, and resources of that token;
Information exchange: less used;
Why JWT?
Traditional authentication methods:
HTTP is a stateless protocol, if the user to our application provides a user name and password for user authentication, so the next time a request, the user will be shown on a user authentication, because based on HTTP protocol, don’t know is which users to send request, so in order to make our application which is able to identify the user sends a request, Only one copy of user login information can be stored on the server. This login information will be sent to the browser after login, and the browser will save it as a cookie, so that the server can identify the user in the next request. This is the traditional session-based authentication.
Problems with traditional certification:
- After each user is authenticated, records should be made on the server for the next identification. Seesion is usually stored in memory. As the number of users increases, the overhead of the server will become significantly larger.
- After user authentication, the server makes authentication records. If the records are stored in memory, the user must access the server next time to obtain authorized resources. This limits the load balancing capability and application expansion capability in distributed applications.
- User identification based on Cooke may be solved and users are vulnerable to cross-site request forgery attacks.
- In front and back end separation system: increased deployment complexity, usually a user request to be forwarded multiple times, if the session, each carry the SESSION ID to the server, increasing the pressure on the server.
Jwt-based certification process:
1. The front-end sends its user name and password to the back-end through a Web form. This process is usually an HTTP POST request.
2. After verifying the user name, the backend takes other information such as the user ID as the JWT Payload. The other headers are encoded in Base64 respectively and signed to form a JWT string. Send the response to the front-end and store it in localStorge or SessionStorge, exit and log in and delete it.
3. The front-end puts JWT in the Authorization bit in the HTTP header for each request. (Solve problems with XSS and SCRF)
4. The backend checks the validity of JWT through the built-in method of JWT.
5. Information contained in JWT can also be obtained for other logical operations.
The advantage of JWT
Terseness: Send through the URL or POST parameter or in the HTTP header, because the amount of data is small and the transmission speed is fast
Self-contained: The load contains the information required by the user, avoiding multiple database queries
Because the tokens are stored on the client in JSON encryption, JWT is cross-language and can be supported on any Web
No need to store session information on the server, especially for distributed microservices
Structure of JWT:
token String ===> header.paylod.singnature
Header load signature
Header: Consists of two parts: the token type and the algorithm used to sign, such as HMAC, SHA256, which uses Base64 encoding to form the first part of the JWT structure.
Payload: Payload. Messages can be put in, and JWT is also encoded in Base64
Signature: The first two parts are Base64 encoded and can be unlocked directly by the front end to see what’s inside. The Signature takes the encoded Header and payload and a key that we provide, and then signs it using the specified algorithm to ensure that the JWT has not been modified
JWT consists of three parts
Use of JWT:
1. Introduce dependency on Java-jwt
2. Generate a token
Calendar Instance = Calendar. getInstande(); instance.add(Calendar.SECOND,90);
String token = JWT.create()
.withClaim("username"."Zhang") // Add load information
.withExpiresAT(instance) // Set the expiration time
.sing(Algorithm.HMAC256(! "" #%sdf*")) // Set the signature
Copy the code
3. Parse data based on tokens and signatures
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(! "" #%sdf*")).build;
DecodedJWT decodeJWT = jwtVerifier.verify(token)
Copy the code
4, encapsulated as a tool class to use:
package com.tnt.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
/ * * *@author huangrw
* @program: back-end -netsecurity_exam *@DescriptionJWT utility class *@createTimeFebruary 20, 2021 21:31:00 */
public class JWTUtils {
private static final String SING = ! "" 2323eW@y";
/ * * *@Author huangrw
* @DescriptionTo generate the token *@DateAnd 2021/2/20 *@Param [map]
* @return java.lang.String
**/
public static String getToken(Map<String,String> map){
Calendar instance = Calendar.getInstance();
// The default expiration date is three days
instance.add(Calendar.DATE,3);
// Create JWT Builder
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k,v);
});
String token = builder.withExpiresAt(instance.getTime()) // Specify the token expiration time
.sign(Algorithm.HMAC256(SING)); / / signature
return token;
}
/ * * *@Author huangrw
* @DescriptionAuthentication token *@Date 22:07 2021/2/20
* @Param [token]
* @return com.auth0.jwt.interfaces.DecodedJWT
**/
public static DecodedJWT verify(String token){
returnJWT.require(Algorithm.HMAC256(SING)).build().verify(token); }}Copy the code
5. Verify using interceptors.
package com.tnt.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.javafx.geom.transform.SingularMatrixException;
import com.tnt.util.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/ * * *@author huangrw
* @program: back-end -netsecurity_exam *@DescriptionJWT interceptor *@createTimeFebruary 20, 2021 21:50:00 */
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map<String,Object> map = new HashMap<>();
// To resolve cross-domain issues, all options requests are allowed
if("OPTIONS".equals(request.getMethod().toUpperCase())){
return true;
}
// Obtain the token in the request header
String token = request.getHeader("token");
System.out.println(token);
try {
JWTUtils.verify(token);
return true;
} catch (SingularMatrixException e){
e.printStackTrace();
map.put("msg"."Invalid signature");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("msg"."The token expired");
}catch ( AlgorithmMismatchException e ){
e.printStackTrace();
map.put("msg"."Token algorithm inconsistent");
}catch (Exception e){
e.printStackTrace();
map.put("msg"."The token is invalid");
}
map.put("state".false); // Set the status
// Convert map to JSON Jackson
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json; charset=UTF-8");
response.getWriter().println(json);
return false; }}Copy the code
6. Configure interceptors
package com.tnt.config; import com.tnt.interceptor.JWTInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @author huangrw * @program: Back-end - netSecurity_exam * @description JWT interceptor Configuration * @createTime 2021 02月20 22:03:00 */ @configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { Registry.addinterceptor (new JWTInterceptor()).addPathPatterns("/**") //.exCludePathPatterns ("/**") .exCludePathPatterns ("/ API /user/regist") // Permit administrator login requests .exCludePathPatterns ("/doc. HTML ","/swagger-resources"); // release Knife4j}}Copy the code