Springboot [前后端分离] +jwt 登录验证

springBoot + Vue + jwt 验证

深入理解:jwt详解

报错问题:jwt报错问题

1 导入依赖:

  <!--   导入jwt    -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.1</version>
        </dependency>

2 JwtUtil工具类

package com.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.demo.entity.Admin;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
//    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    /**
     * 密钥
     */
    private static final String SECRET = "my_secret";

    /**
     * 过期时间
     **/
    private static final long EXPIRATION = 1;//单位为秒

    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(Admin admin) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        System.out.println(expireDate.getTime());
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("id", admin.getId())//userId
                .withClaim("userName", admin.getAdmin())//userName
                .withClaim("password", admin.getPassword())//password
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static boolean verifyToken(String token) {
        try{
            DecodedJWT jwt=JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}

3 Vue index.js 路由

//每一次切换路由都执行这个守卫
router.beforeEach((to,from,next)=>{
  if(to.path.startsWith("/login")){
    window.localStorage.getItem("access-admin")
    next()
  }else{
    let admin=JSON.parse(window.localStorage.getItem("access-admin"))
    //判断 admin 是否有值
    if(!admin){
      next({path:"/login"})
    }else{
      // 校正token的合法性
      axios.post("http://localhost:8181/demo/parseToken",admin).then(data=> {
        console.log(data.data)
        if(!data.data){
          next({path:"/login"})
          localStorage.remover("access-admin")
        }
      })
    }
   next()
  }
})
export default router;

4 Login.vue

 login() {
      this.$refs.formLabelAlign.validate((visible) => {
        if (visible) {
          axios.post("http://localhost:8181/demo/login", this.formLabelAlign).then(data => {
            console.log(data.data.token)
            if (data.data != null&& data.data!="") {
              window.localStorage.setItem("access-admin",JSON.stringify(data.data.token));
              this.$message({
                message: '登录成功!',
                type: 'success'
              });
            }else{
              this.$message({
                message: '用户名或密码错误',
                type: 'error'
              });
            }

          })
        } else {
          console.log("error")
          return false;
        }
      })
    },

5 Controller 层

 /**
     * 登录生成token
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public Admin getLogin(@RequestBody Admin admin){
         Admin ad=indexService.queryAdmin(admin);
        if(ad !=null ){
            //添加token
            String token =JwtUtil.createToken(admin);
            ad.setToken(token);
            return ad;
        }
       return null;
    }
    /**
     * 校正token
     * @param token
     */
    @PostMapping("/parseToken")
    public boolean parseToken(@RequestBody String token){
        return JwtUtil.verifyToken(token);
    }

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值