Spring:在 REST 调用响应中插入 cookie [英] Spring :Inserting cookies in a REST call response
问题描述
我正在使用 spring mvc 实现 REST API 端点.我正在尝试发回带有 cookie 值的 HTTP 响应.这相当于我在 ruby SINATRA 中需要做的:
I am implementing REST API endpoints using spring mvc. I am trying to send back a HTTP response with a cookie value. This is the equivalent of what I need to do in ruby SINATRA :
response.set_cookie('heroku-nav-data', :value => params['nav-data'], :path => '/')
这是我迄今为止尝试过的,但没有奏效:
This is what I have tried so far, but that didn't work :
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> single_sign_on(@RequestBody String body_sso) {
String[] tokens = body_sso.split("&");
String nav_data=tokens[3].substring(9);
String id = tokens[2].substring(3);
String time_param = tokens[0].substring(10);
long timestamp= Long.valueOf(time_param).longValue();
String pre_token = id+':'+HEROKU_SSO_SALT+':'+time_param;
String token = DigestUtils.shaHex(pre_token);
long lDateTime = new Date().getTime()/1000;
if (!((token.equals(tokens[4].substring(6))) && ((lDateTime-timestamp)<300)))
{
return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
}
HttpHeaders headers = new HttpHeaders();
headers.add("heroku-nav-data",nav_data);// this didn't work
return new ResponseEntity<String>(id,headers,HttpStatus.OK);
}
我该怎么办?谢谢.
推荐答案
虽然可以使用原始 Set-Cookie
标头设置 cookie,但使用 Servlet API 会更容易:
While it is possible to set a cookie using a raw Set-Cookie
header, it will be easier to use the Servlet API :
在你的控制器方法中添加HttpServletResponse
参数,Spring会传递相关的实例;然后使用 addCookie
方法:
Add the HttpServletResponse
parameter to your controller method, Spring will pass the relevant instance; then use the addCookie
method :
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<String> singleSignOn(@RequestBody String bodySso, HttpServletResponse response) {
response.addCookie(new Cookie("heroku-nav-data", navData));
return new ResponseEntity<String>(id,headers,HttpStatus.OK);
}
如果需要,您还可以向 cookie 对象添加更多参数:
You can also add more parameters to the cookie object if needed:
final Cookie cookie = new Cookie(this.cookieName, principal.getSignedJWT());
cookie.setDomain(this.cookieDomain);
cookie.setSecure(this.sendSecureCookie);
cookie.setHttpOnly(true);
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
这篇关于Spring:在 REST 调用响应中插入 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!