JWT(token)基础使用

这篇博客介绍了JWT(JSON Web Tokens)的基础使用,主要聚焦在JWT如何在Spring和Java环境中实现身份验证和授权。通过学习,读者将理解JWT的工作原理以及如何在实际项目中应用它。
public class JwtUtil {
    //过期时间 30min
    private static final int EXPIRE_TIME = 30;
    //私钥
    private static final String TOKEN_SECRET = "privateKey";
    private static final String USER_NAME = "name";

    /**
     *      签发对象:这个用户的id
     *      签发时间:现在
     *      有效时间:30分钟
     *      载荷内容:暂时设计为:这个人的名字
     *      加密密钥:这个人的id加上一串字符串
     * @param userId
     * @return
     */
    public static String createToken(Long userId) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,EXPIRE_TIME);
        Date expiresDate = nowTime.getTime();

        return JWT.create().withAudience(userId+"")   //签发对象
                .withIssuedAt(new Date())    //发行时间
                .withExpiresAt(expiresDate)  //有效时间
//                .withClaim(USER_NAME, userName)    //载荷,随便写几个都可以
                .sign(Algorithm.HMAC256(userId+TOKEN_SECRET));   //加密
    }
    /**
     * 检验合法性,其中secret参数就应该传入的是用户的id
     * @param token
     * @throws MsgmanageException
     */
    public static void verifyToken(String token, String secret) throws MsgmanageException {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret+TOKEN_SECRET)).build();
            verifier.verify(token);
        } catch (Exception e) {
            //效验失败
            //自定义的一个异常
            throw new MsgmanageException(GlobalConstant.TOKEN_UNAVILABLE);
        }
    }
    /**
     * 获取签发对象
     */
    public static String getAudience(String token) throws MsgmanageException {
        String audience = null;
        try {
            audience = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            //这里是token解析失败
            throw new  MsgmanageException(GlobalConstant.TOKEN_UNAVILABLE);
        }
        return audience;
    }
}
    将你要保存的id存入token,再将token作为对象一部分传入前端

     String token = JwtUtil.createToken(sysUserVo.getId());

     sysUserVo.setToken(token);

     首先拿到token然后在在请求头或者cookies储存token

     例如var token = data.token;

     addCookie("msgToken",token);注意msgToken

     在拦截器中

     要是消息头存储等到token

     String token = request.getHeader("msgToken");
 
     要是cookies存储得到token

     在拦截器种找token,过程是找到所有的cookies,比较名字确认你要的那个cookies,后取值

      public String getTokenFromCookie(HttpServletRequest request){

     Cookie[] cookies = request.getCookies();

      for (Cookie cookie : cookies) {

      if(cookie.getName().equals("msgToken")){

      return cookie.getValue();

      }

      }

      return null;

      }

       下来验证是否前往controller等

      // 如果不是映射到controller方法直接通过

     // ResourceHttpRequestHandler 是静态资源,无需拦截

     // HandlerMethod 是Controller中的方法
 
      if (!(object instanceof HandlerMethod)) {

       return true;

    }

     Method method = handlerMethod.getMethod();

     //检查是否有NoNeedToken注释,有则跳过认证

     if (handlerMethod.getBeanType().isAnnotationPresent(NoNeedToken.class) || 
       method.isAnnotationPresent(NoNeedToken.class)) {

      return true;

    }

      //默认全部检查

    else {

     // 执行认证

     if (token == null) {

       //这里其实是登录失效,没token了
    
     throw new MsgmanageException(GlobalConstant.TOKEN_UNAVILABLE);

     }

       // 获取 token 中的 userId

      String userId = JwtUtil.getAudience(token);

       // 验证 token

       JwtUtil.verifyToken(token, userId);

      return true;

    }

        要是相应的controller要调用上文提到得到 String token 和 String userId 的方法就好了.

谢谢观看,溜了溜了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值