Spring Boot 无法写出 Cookie

Spring Boot Java Cookie About 1,420 words

问题描述

在使用了前后端分离、Spring SecuritySpring SessionSpring Boot后端项目(Undertow作为web容器)后,当返回的body包含了中文且大于15KB时(不确定是否是这个原因),返回的response header里没有Set-Cookie字段,导致前端无法保存SESSION

发现问题

Spring SecurityonAuthenticationSuccess认证成功后,HttpServletResponse写出用户信息时使用了PrintWriterwrite(String content)方法,部分代码如下。

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    PrintWriter printWriter = response.getWriter();
    printWriter.write(objectMapper.writeValueAsString(result));
    printWriter.flush();
    printWriter.close();
}

解决方法

PrintWriterwrite(String content)方法替换为response.getOutputStream()write(byte[] b)方法即可。

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    response.getOutputStream().write(objectMapper.writeValueAsBytes(result));
}

具体原因

具体原因目前还没有来得及细追,考虑是Content-Length计算字符时的问题,因为两个write方法一个是字节数组,一个是字符串,可能在转换过程中有编码问题。并且使用的web容器是Undertow而非Tomcat,也不确定是Spring Session还是Undertow原因。

希望有大神能留言帮忙解惑,万分感谢。

参考

https://blog.csdn.net/oKuZuoZhou/article/details/95192745

Views: 3,522 · Posted: 2020-04-21

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh