te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Unable to set cookies with Spring Boot on the serve side - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to set cookies with Spring Boot on the serve side - Stack Overflow

programmeradmin1浏览0评论

I'm using Spring Boot on server side. When I'm adding cookie to response it adds Set-cookie header with right value but when browser receives response it displays that header but won't set the cookie. Also Postman stores all cookies fine.

Spring

public ResponseEntity<?> authenticate(@RequestBody AuthenticationRequest request, HttpServletResponse response) throws Exception {
        Cookie cookie = new Cookie("token", "COOKIE_VALUE");
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        response.addCookie(cookie);
        return ResponseEntity.ok("Connection succeeded");
    }

JSfetch (from React app from different port)

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({"username":"TestUser","password":"pwd"});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://IP_ADDRESS:8080/authenticate", requestOptions)

Chrome's seeing cookie in the headers

But it won't add it to the storage

So does Firefox. What did I miss? Is there a solution to this? I'm using my internet ip address in fetch with port 8080 - not localhost. But localhost didn't do the trick either.

UPD. It seems working though when the ports are the same. I tried to return jsp page instead and that page executes the fech statement and it has stored the cookie. So solution to this is probably to pile react app and put it on the server. Anyway how to deal with cookies when the ports are not the same?

I'm using Spring Boot on server side. When I'm adding cookie to response it adds Set-cookie header with right value but when browser receives response it displays that header but won't set the cookie. Also Postman stores all cookies fine.

Spring

public ResponseEntity<?> authenticate(@RequestBody AuthenticationRequest request, HttpServletResponse response) throws Exception {
        Cookie cookie = new Cookie("token", "COOKIE_VALUE");
        cookie.setHttpOnly(true);
        cookie.setSecure(false);
        response.addCookie(cookie);
        return ResponseEntity.ok("Connection succeeded");
    }

JSfetch (from React app from different port)

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({"username":"TestUser","password":"pwd"});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("http://IP_ADDRESS:8080/authenticate", requestOptions)

Chrome's seeing cookie in the headers

But it won't add it to the storage

So does Firefox. What did I miss? Is there a solution to this? I'm using my internet ip address in fetch with port 8080 - not localhost. But localhost didn't do the trick either.

UPD. It seems working though when the ports are the same. I tried to return jsp page instead and that page executes the fech statement and it has stored the cookie. So solution to this is probably to pile react app and put it on the server. Anyway how to deal with cookies when the ports are not the same?

Share Improve this question edited Jun 8, 2020 at 11:50 Blogger 2015 asked Jun 8, 2020 at 11:28 Blogger 2015Blogger 2015 1291 gold badge2 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Ok, changing this in spring boot

@CrossOrigin

to this

@CrossOrigin(origins = "http://MY_IP_ADDRESS", allowCredentials = "true")

saved my day. I still don't get it why it didn't work when I set the headers manually as follows in the post mapping method

response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Origin", "http://MY_IP_ADDRESS");

Chrome has changed its recent policies not to support localhost or development cookies, so you have to work around and play it with HTTP cookie

 ResponseCookie resCookie = ResponseCookie.from(cookieName, cookieValue)
            .httpOnly(true)
            .sameSite("None")
            .secure(true)
            .path("/")
            .maxAge(Math.toIntExact(timeOfExpire))
            .build();
    response.addHeader("Set-Cookie", resCookie.toString());

This thing works for me but, make sure it only works for https (not HTTP) and this thing is a makeover for development purposes only, once if you host your server chrome allows response cookies else it just blocks all kinds of HTTP cookies.

Cookies are accessibles only if the JS is provided from the same origin (host:port).

You may use URL rewriting approach to use the same origin for your assets and API. You may look at devServer if your are using Webpack.

Consider LocalStorage that offer more modern approach to deal with it as well.

Regards.

发布评论

评论列表(0)

  1. 暂无评论