非敏感信息—透明传输

后端接收前端登陆请求

@PostMapping("/user/login")
    @ResponseBody
    public ApiRestResponse login(@RequestBody Map<String,String> map,HttpServletRequest request) throws ServletException, IOException {
 
        String verifyCode = (String) request.getSession().getAttribute("kaptchaVerifyCode");
        String verificationCode = (String) map.get("verificationCode");
    String username = (String) map.get("username");
        String password = (String) map.get("password");
        if (verificationCode == null || verifyCode == null || !verificationCode.equalsIgnoreCase(verifyCode)) {
            return ApiRestResponse.error(EmSystemExceptionEnum.VERIFICATION_CODE_ERROR);
        }
        if (password.length() < 8) {
            return ApiRestResponse.error(EmSystemExceptionEnum.PASSWORD_TOO_SHORT);
        }
        User user = userService.login(username, password);
        user.setPassword(null);
//        获取当前userId
        currentUserId = user.getUserId();
        Algorithm algorithm = Algorithm.HMAC256(Constant.JWT_KEY);
        String token = JWT.create()
                .withClaim(Constant.NAME,user.getName())
                .withClaim(Constant.USER_NAME, user.getUsername())
                .withClaim(Constant.USER_ID, user.getUserId())
                .withClaim(Constant.PEOPLE_ID, user.getPeopleId())
                //过期时间
                .withExpiresAt(new Date(System.currentTimeMillis() + Constant.EXPIRE_TIME))
                .sign(algorithm);
 
        HashMap<String, Object> responseData = new HashMap<>();
        responseData.put(Constant.TOKEN, token);
        return ApiRestResponse.success(responseData);
    }

下发token,注意token里是非敏感信息,比如存储用户名,单位名称、用户id等等

这样前端可以直接解析使用

当然,前端可以将token信息发送给后端,让后端解析,一般适用于敏感信息的获取才使用

比如,token里含有用户名,通过后端解析token得到用户名,后端通过用户名查询得到用户信息再返回给前端,实现了非敏感信息到敏感信息的转换

敏感信息获取

首先是将登陆信息存储起来使用,并发送给后端

后端使用Map接收数据,并进行JWT加密,将信息发给前端

代码在上面非敏感数据传输里面

前端获取Token

在上面,已经把token存入了cookie里

是这样导入的,我们点入看看

import { getToken, setToken, removeToken } from ’@/utils/auth’

查看浏览器:

发送给后端,获取详细信息

后端代码:

/**
 * @param token 令牌
 * @return 用户信息
 */
@GetMapping("/user/user_info")
@ResponseBody
public ApiRestResponse userInfo(@RequestParam("token") String token){
    Long userId = JWT.decode(token).getClaim(Constant.USER_ID).asLong();
    Long peopleId = JWT.decode(token).getClaim(Constant.PEOPLE_ID).asLong();
    String username = JWT.decode(token).getClaim(Constant.USER_NAME).asString();
    Map ResponseList = null;
    ResponseList = new LinkedHashMap();
    People people = peopleService.selectByPrimaryKey(peopleId);
    Department department = departmentService.selectByPrimaryKey(people.getDepartmentId());
    ResponseList.put("people", people);
    ResponseList.put("department", department);
    ResponseList.put("username",username);
    return ApiRestResponse.success(ResponseList);
}

vuex获取数据

首先,在需要数据的Vue页面导入:

import { mapGetters } from ‘vuex’

结果