Java Spring:在 REST 调用响应中插入 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24642508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:39:03  来源:igfitidea点击:

Spring :Inserting cookies in a REST call response

javaspringrestspring-mvcspring-security

提问by user3242743

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 :

我正在使用spring mvc实现 REST API 端点。我正在尝试发回带有 cookie 值的 HTTP 响应。这相当于我需要在 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);    

}

What should I do ? thanks.

我该怎么办 ?谢谢。

回答by user3242743

I finally found the solution :

我终于找到了解决方案:

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","key="+"value");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();

回答by Pierre Henry

While it is possible to set a cookie using a raw Set-Cookieheader, it will be easier to use the Servlet API :

虽然可以使用原始Set-Cookie标头设置 cookie ,但使用 Servlet API 会更容易:

Add the HttpServletResponseparameter to your controller method, Spring will pass the relevant instance; then use the addCookiemethod :

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);    

}

You can also add more parameters to the cookie object if needed:

如果需要,您还可以向 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);

回答by vbezhenar

You can use Spring API for Cookie: org.springframework.http.HttpCookie:

您可以将 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);

回答by Gaurav Bhagat

Hey Here is the Example of how to add cookie to response object and reading the cookie from response object using @CookieParam

嘿,这是如何将 cookie 添加到响应对象并使用 @CookieParam 从响应对象读取 cookie 的示例

package com.ft.resources;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;
@Path("/cookie")
public class CookieResource {

@GET
@Path("/write")
public Response write() {
    //create cookie
    NewCookie c1=new NewCookie("uname","gaurav");
    NewCookie c2=new NewCookie("password","gaurav@123");
    //adding cookie to response object
    return Response.ok().cookie(c1,c2).build();
}

@GET
@Path("/read")
public Response read(@CookieParam("uname") String uname,@CookieParam("password") 
String password) {
    System.out.println(uname);
    System.out.println(password);

    String msg="Username:"+uname;
    msg=msg.concat("</br>");
    msg=msg.concat("Password:"+password);
    return Response.ok(msg).build();

}
}