16

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

}

What should I do ? thanks.

user3242743
  • 1,751
  • 5
  • 22
  • 32

5 Answers5

40

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

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

}

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);
Pierre Henry
  • 16,658
  • 22
  • 85
  • 105
  • may I please ask you for help in a similar question related to cookie and the basic authentication? https://stackoverflow.com/questions/54554510/how-to-add-authentication-cookie-to-the-rest-api-response-using-spring-security – The Coder Feb 08 '19 at 10:45
20

You can use Spring API for 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);
vbezhenar
  • 11,148
  • 9
  • 49
  • 63
14

I finally found the solution :

HttpHeaders headers = new HttpHeaders();
headers.add("Set-Cookie","key="+"value");
ResponseEntity.status(HttpStatus.OK).headers(headers).build();
Kerem Baydoğan
  • 10,475
  • 1
  • 43
  • 50
user3242743
  • 1,751
  • 5
  • 22
  • 32
  • Sadly, this does not include additional values that ensure that your cookie will only be used under particular domains and/or in secure context. As a result, it is up to clients to choose those values. – Dragas Jul 11 '19 at 06:51
  • You can configure any cookie options in that string: Example: headers.add("Set-Cookie","key="+"value"+";Max-Age=3600;Secure; HttpOnly"); – Dub Nazar Mar 23 '20 at 18:40
0

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

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

}
}
0

Alternatively you can use

HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.COOKIE, cookie-name + "=" + cookie value);
ResponseEntity.status(HttpStatus.OK).headers(headers).build();
gihan-maduranga
  • 4,381
  • 5
  • 41
  • 74