springboot操作cookie

司空鸿禧
2023-12-01

在响应中添加cookie


@RequestMapping(value="/casLogin", method= RequestMethod.GET)
public CommonResult<String> casLogin(HttpServletResponse response, @RequestParam String accessToken, @RequestParam String refreshToken) {
        try {
            Cookie accessTokenCookie = new Cookie("access_token", accessToken); //创建Cookie对象,指定名字和值
            Cookie refreshTokenCookie = new Cookie("access_token_Refresh", refreshToken); //创建Cookie对象,指定名字和值
            response.addCookie(accessTokenCookie); //在响应中添加Cookie对象
            response.addCookie(refreshTokenCookie); //在响应中添加Cookie对象
            return CommonResult.success("登录成功!");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
}

从请求中获取cookie

@RequestMapping(value="/casLoginOut", method= RequestMethod.GET)
public CommonResult<String> casLoginOut(HttpServletResponse response, HttpServletRequest request) {
    try {

        String access_token = "";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("access_token")) {
                access_token = cookie.getValue();
            }
        }
        RestTemplate client = new RestTemplate();

        //截取网关ip和port
        String gateWay = StringUtils.substringBeforeLast(gateWayHost, "/");
        StringBuilder sb = new StringBuilder(gateWay);
        sb.append("/logout");
        sb.append("?Authorization=");
        sb.append(access_token);

        String template = client.getForObject(sb.toString(), String.class);
        JSONObject jsonObject = JSONObject.parseObject(template);
        Integer statusCode = (Integer)jsonObject.getJSONObject("meta").get("statusCode");
        Boolean success = (Boolean)jsonObject.getJSONObject("meta").get("success");
        if (statusCode == 200 && success) {
            Cookie access = new Cookie("access_token", ""); //创建Cookie对象,指定名字和值
            Cookie refreshTokenCookie = new Cookie("access_token_Refresh", ""); //创建Cookie对象,指定名字和值

            access.setMaxAge(0); //另有效时间为0则系统会自动删除过期的cookie
            refreshTokenCookie.setMaxAge(0); //另有效时间为0则系统会自动删除过期的cookie
            response.addCookie(access);
            response.addCookie(refreshTokenCookie);
            return CommonResult.success("退出登录成功!");
        }
        logger.error("网关退出登录失败!");
        return CommonResult.failed("退出登录失败!");

    } catch (Exception e) {
        logger.error(e.getMessage());
        return CommonResult.failed("退出登录失败!");
    }
}
 类似资料: