SpringBoot is the simplest implementation of JWT

What is JWT

Json web token (JWT), is an open standard based on JSON ((RFC 7519) that is implemented to pass statements between web application environments. It defines a concise, self-contained method for communicating between two parties The form of JSON object can safely transmit information. Because of the existence of digital signature, the information is trusted. JWT can use HMAC algorithm or RSA public and private key pair to sign.

JWT official website: https://jwt.io

The main application scenarios of JWT

Identity authentication In this scenario, once the user completes the login, the JWT is included in each subsequent request, which can be used to verify the user's identity and to verify the access rights of routes, services, and resources. Because of its very small overhead, it can be easily transferred in systems of different domain names, and this technology is currently widely used in single sign-on (SSO). Information exchange It is a very safe way to use JWT to encode data between the two parties of the communication. Since its information is signed, it can ensure that the information sent by the sender is not forged.

JWT structure

JWT consists of three parts:

Header 头部(标题包含了令牌的元数据,并且包含签名和/或加密算法的类型)
Payload 负载 (类似于飞机上承载的物品)
Signature 签名/签证

These three pieces of information text are connected together to form a JWT string.

like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

Next, we use springboot to realize the generation of jwt tokens

Adding pom dependencies will need to use json later, so we will introduce them together

 <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.51</version>
        </dependency>
    <dependency>

Add controller and service and entity classes. For the convenience of not operating the database, we use a fixed username and password. The overall result is as follows

Insert picture description here

controller

@RequestMapping("/user")
@RestController
public class UserController {
    
    

    @Autowired
    private UserService userService;

    @PostMapping(value = "/login")
    public String login(@RequestBody User user){
    
    
        return userService.login(user);
    }
}

Implementation class

public class UserServiceImpl implements UserService {
    
    
    public static final String USERNAME = "admin";
    public static final String PASSWORD = "admin";

    @Override
    public String login(User user) {
    
    
        //忽略查询数据库
        if (USERNAME.equals(user.getName()) && PASSWORD.equals(user.getPassword())){
    
    
            //创建用户令牌信息
            Map<String, Object> map = new HashMap<>();
            map.put("role","USER");
            map.put("success","SUCCESS");
            map.put("username",user.getName());
            //创建用户Token
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(map), null);
            //现在就可以存储tonken了,为了方便直接存到cookie里面去
            Cookie cookie = new Cookie("Authoriztion", token);
            cookie.setDomain("localhost");
            cookie.setPath("/");
            return token;
        }
        return "登录失败";
    }

    @Override
    public List<User> getUserInfo() {
    
    
        return null;
    }

}

The JwtUtil class is the main code code as follows, which encapsulates the information for generating token

public class JwtUtil {
    
    
    //令牌有效期 1小时
    public static final Long JWT_TTL = 3600000L;

    //jwt令牌信息
    public static final String JWT_KEY = "mzjmc";


    public static String createJWT(String id, String subject, Long ttlMillis){
    
    
        //指定签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //当前系统时间
        long currentTimeMillis = System.currentTimeMillis();
        //令牌签发的时间
        Date date = new Date(currentTimeMillis);
        //如果令牌的有效期为空则默认一小时
        if (ttlMillis == null){
    
    
            ttlMillis = JWT_TTL;
        }
        //令牌过期时间
        long expMillis = currentTimeMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        //生成秘钥
        SecretKey secretKey = generalKey();
        //封装jwt信息
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setId(id); //唯一ID
        jwtBuilder.setSubject(subject); //主题信息
        jwtBuilder.setIssuer("admin");  //签发者
        jwtBuilder.setIssuedAt(date); //签发时间
        jwtBuilder.signWith(SignatureAlgorithm.HS256, secretKey); //算法及签名秘钥
        jwtBuilder.setExpiration(expDate);  //过期时间

        return jwtBuilder.compact();
    }

    /**
     * 生成秘钥
     * @return
     */
    public static SecretKey generalKey(){
    
    
        byte[] encode = Base64.getEncoder().encode(JWT_KEY.getBytes());
        return new SecretKeySpec(encode, 0, encode.length, "AES");
    }
}

Next, we can test to obtain token information by logging in. The username and password are specified as admin

First come the wrong set

Insert picture description here

Another set of right

Insert picture description here

Isn't it simple, 2020-1024 is still very happy to celebrate the festival today

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/mzjmc123/article/details/109262697