Java登陆第四十四天——跟写微头条遇到的问题

微头条项目链接

作为JavaWeb的收官之作,这里记载了写项目时遇到的问题。

前提:使用maven进行依赖管理

1.JJWT导入依赖太少

最初只导入了

<dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.11.5</version>
        </dependency>

出现异常Have you remembered to include the jjwt-impl.jar in your runtime classpath?
于是上网搜索,还需要额外导入以下两个依赖

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.11.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.11.5</version>
        </dependency>

2. JJWT密钥太短

异常The signing key's size is 32 bits which is not secure enough for the HS512 algorithm.
jwt 0.9.1 之后的版本对于密钥安全性要求更高(体现在 secret 密钥的长度要达到一定的位数)。

于是修改代码

JwtUtil类

   private static long tokenExpiration = 24 * 60 * 60 * 1000;
//private static String tokenSignKey = "123456" 加密太短了 随便加点
    private static String tokenSignKey = "dsiofayasdiufyiouqweyhruio2q3yo512435y3hpsaiafhp9uisrdoufiosduriou1io23u4i1o2u3io1p2u3ipoudsiopfuipaosdpufpioau1231242141";

3.代码优化

这是我写的

    protected void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求头
        String token = req.getHeader("token");
        //根据token解密后的uid查询用户
        NewsUser realUser = userService.findByUserId(JwtUtil.getUserId(token));
        Result result = null;
        //用户存在
        if (realUser != null) {
            HashMap<String, Object> map = new HashMap<>();
            //密码不返回
            realUser.setUserPwd("");
            map.put("loginUser", realUser);
            result = Result.ok(map);
        }
        WebUtil.writeJson(resp, result);
    }

没有检验token直接就去操作数据库,会加大数据库的压力,也会导致无效的查询。

修改代码

    protected void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求头
        String token = req.getHeader("token");
        Result result = null;

        //使用短路与 第一个布尔表达式不成立直接就F了
        //isExpiration判断是否失效,T是失效,F是有效,所以取反
        if (token != null && (!JwtUtil.isExpiration(token)) ) {
            //根据token解密后的uid查询用户
            NewsUser realUser = userService.findByUserId(JwtUtil.getUserId(token));
            //用户存在
            if (realUser != null) {
                HashMap<String, Object> map = new HashMap<>();
                //密码不返回
                realUser.setUserPwd("");
                map.put("loginUser", realUser);
                result = Result.ok(map);
            }
        }
        WebUtil.writeJson(resp, result);
    }
posted @ 2024-04-25 22:13  rowbed  阅读(7)  评论(0编辑  收藏  举报