SpringBoot开发(2)——登录

  1. 在pom中添加jwt依赖
    <!--jwt依赖-->
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
     <!--解决jdk版本过高,jwt有问题-->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
  2. 在cxsbg包下建立utils包,在utils包中新建生成token的类
    package com.cxsbg.utils;
    
    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.JwtBuilder;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import java.util.Base64;
    import java.util.Date;
    import java.util.UUID;
    
    public class JwtUtil {
        //有效期
        public static final Long JWT_TTL=60*60*1000L;//一个小时
        //设置密钥明文
        public static final String JWT_KEY="cxs";
    
        /**
         * 创建token
         * @param id
         * @param subject
         * @param ttlMillis 最长有效期
         * @return
         */
        public static String createJWT(String id,String subject,Long ttlMillis){
            SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;
    
            long nowMills=System.currentTimeMillis();//当前时间
            Date now=new Date(nowMills);//当前时间
            if(ttlMillis==null){
                ttlMillis=JwtUtil.JWT_TTL;
            }
            long expMillis=nowMills+ttlMillis;//最长过期时间
            Date expDate=new Date(expMillis);//最长过期时间
    
            SecretKey secretKey=generalKey();//密钥
    
            JwtBuilder builder= Jwts.builder()
                    .setId(id)//唯一的ID
                    .setSubject(subject)//可以是json数据
                    .setIssuer("sg")//签发者
                    .setIssuedAt(now)//签发时间
                    .signWith(signatureAlgorithm,secretKey)//使用对应的加密算法和密钥签名
                    .setExpiration(expDate);//设置过期时间
            return builder.compact();
        }
    
        /***
         * 生成加密后的密钥
         * @return
         */
        private static SecretKey generalKey() {
            byte[] encodedKey= Base64.getDecoder().decode(JwtUtil.JWT_KEY);
            SecretKey key=new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
    
            return key;
        }
    
        /***
         * 解析jwt
         * @param jwt
         * @return
         * @throws Exception
         */
        public static Claims parseJWT(String jwt) throws Exception{
            SecretKey secretKey=generalKey();
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }
    
        public static void main(String[] args) throws Exception {
            //获得token
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), "zhangsan", null);
            System.out.println(token);
    
            //解析token
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            System.out.println(subject);
        }
    }
    
  3. 写对应的登录controller,如果登录成功,需要把生成的token传递给前端
    package com.cxsbg.controller;
    
    import com.cxsbg.domain.ResponseResult;
    import com.cxsbg.domain.SystemUser;
    import com.cxsbg.service.SystemUserService;
    import com.cxsbg.utils.JwtUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    import java.util.UUID;
    
    @RestController
    @RequestMapping("/sys_user")
    public class SystemUserController {
        @Autowired
        private SystemUserService systemUserService;
    
        @PostMapping("/login")
        public ResponseResult login(@RequestBody SystemUser systemUser) {
            //校验用户名和密码是否正确
            SystemUser loginUser = systemUserService.login(systemUser);
            HashMap<String, Object> map;
            if (loginUser != null) {
                //登录成功,获取token
                String token = JwtUtil.createJWT(UUID.randomUUID().toString(), String.valueOf(loginUser.getId()), null);
                map = new HashMap<>();
                map.put("token", token);
            } else {
                return new ResponseResult(300, "登录失败");
            }
            return new ResponseResult(200, "登录成功", map);
        }
    }
    
  4. 如果登录成功,前端将对应的token存储到本地
    //存储token到本地
    localStorage.setItem("token",res.data.data.token);

发表评论

邮箱地址不会被公开。 必填项已用*标注