商城-授权中心-首页判断登录状态

3.首页判断登录状态

虽然cookie已经成功写入,但是我们首页的顶部,登录状态依然没能判断出用户信息:
在这里插入图片描述

这里需要向后台发起请求,根据cookie获取当前用户的信息。

我们先看页面实现

3.1.页面JS代码

页面的顶部已经被我们封装为一个独立的Vue组件,在/js/pages/shortcut.js
在这里插入图片描述

打开js,发现里面已经定义好了Vue组件,并且在created函数中,查询用户信息:
在这里插入图片描述

查看网络控制台,发现发起了请求:
在这里插入图片描述

因为token在cookie中,因此本次请求肯定会携带token信息在头中。

3.2.后台实现校验用户接口

我们在leyou-auth-service中定义用户的校验接口,通过cookie获取token,然后校验通过返回用户信息。

  • 请求方式:GET
  • 请求路径:/verify
  • 请求参数:无,不过我们需要从cookie中获取token信息
  • 返回结果:UserInfo,校验成功返回用户信息;校验失败,则返回401

代码:

/**
  * 验证用户信息
  * @param token
  * @return
  */
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN")String token){
    try {
        // 从token中解析token信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
        // 解析成功返回用户信息
        return ResponseEntity.ok(userInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 出现异常则,响应500
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}

3.3.测试

在这里插入图片描述

在这里插入图片描述

页面效果:
在这里插入图片描述

3.4.刷新token

每当用户在页面进行新的操作,都应该刷新token的过期时间,否则30分钟后用户的登录信息就无效了。而刷新其实就是重新生成一份token,然后写入cookie即可。

那么问题来了:我们怎么知道用户有操作呢?

事实上,每当用户来查询其个人信息,就证明他正在浏览网页,此时刷新cookie是比较合适的时机。因此我们可以对刚刚的校验用户登录状态的接口进行改进,加入刷新token的逻辑。

/**
  * 验证用户信息
  * @param token
  * @return
  */
@GetMapping("verify")
public ResponseEntity<UserInfo> verifyUser(@CookieValue("LY_TOKEN")String token, HttpServletRequest request, HttpServletResponse response){
    try {
        // 从token中解析token信息
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());
        // 解析成功要重新刷新token
        token = JwtUtils.generateToken(userInfo, this.properties.getPrivateKey(), this.properties.getExpire());
        // 更新cookie中的token
        CookieUtils.setCookie(request, response, this.properties.getCookieName(), token, this.properties.getCookieMaxAge());

        // 解析成功返回用户信息
        return ResponseEntity.ok(userInfo);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 出现异常则,响应500
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}

猜你喜欢

转载自blog.csdn.net/shenzhen_zsw/article/details/92777979