use*_*743 11 java rest spring spring-mvc spring-security
我正在使用spring mvc实现REST API端点.我试图发回一个带有cookie值的HTTP响应.这相当于我在ruby SINATRA中需要做的事情:
response.set_cookie('heroku-nav-data', :value => params['nav-data'], :path => '/')
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所尝试的,但是没有用:
@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);
}
Run Code Online (Sandbox Code Playgroud)
我该怎么办 ?谢谢.
Pie*_*nry 25
虽然可以使用原始Set-Cookie标头设置cookie ,但使用Servlet API会更容易:
将HttpServletResponse参数添加到控制器方法中,Spring将传递相关实例; 然后使用addCookie方法:
@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);
}
Run Code Online (Sandbox Code Playgroud)
如果需要,您还可以向cookie对象添加更多参数:
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);
Run Code Online (Sandbox Code Playgroud)
use*_*743 10
我终于找到了解决方案:
HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","key="+"value");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();
Run Code Online (Sandbox Code Playgroud)
您可以将Spring API用于Cookie:org.springframework.http.HttpCookie:
HttpCookie cookie = ResponseCookie.from("heroku-nav-data", nav_data)
.path("/")
.build();
return ResponseEntity.ok()
.header(HttpHeaders.SET_COOKIE, cookie.toString())
.body(id);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30988 次 |
| 最近记录: |