Can not access cookies in spring jersey based application - java

I am working on spring security implementation module and i need to set and get few cookies. i have tried creating cookies by using (javax.servlet.http.Cookie) and (javax.ws.rs.core.NewCookie) both are working fine for setting cookies, i can see the cookies in the browser but when i am trying to access them, it does give me only JSESSIONID, i need to access other cookies also.
This is how i am setting the cookies, and in both ways i will save the cookies successfully on the browser:
Cookie cookieOne = new Cookie("SERVLETCOOKIE", "TESTING COOKIES");
NewCookie cookieTwo = new NewCookie("WSRSCOOKIE", "TESTING COOKIES");
when i try to access the cookies, i have tried both #Autowired and #Context as below, but i can only get JSESSIONID cookie.
#Autowired HttpServletRequest request;
and
#Context HttpServletRequest request;
and i am trying to access the cookies as below :
Cookie[] cookieList = request.getCookies();
if(cookieList !=null && cookieList.length >0){
for(int i=0;i<cookieList.length;i++){
Cookie cookie = cookieList[i];
if(cookie.getName().equals("SERVLETCOOKIE")){
String value1 = cookie.getValue();
logger.info("cookie found. value ="+value1 );
}
if(cookie.getName().equals("WSRSCOOKIE")){
String value2 = cookie.getValue();
logger.info("cookie found. value ="+value2 );
}
}
}
It would be great if someone help me point out the way i can get all the other cookies.

The question is a few years old. However today I had a similar problem.
The solution was: If you are using the Apache http connector then the jersey cookie api seems not to be supported.
Try to get the cookies over the Apache api:
public static Cookie getCookie(final ClientRequestContext clientRequestContext, final String key){
final CookieStore cookieStore = ApacheConnectorProvider.getCookieStore(clientRequestContext.getClient());
return cookieStore.getCookies().stream().filter(c->c.getName().equals(key)).collect(CollectorUtil.singletonOrNullCollector());
}

Related

Cookie not showing up in request

I'm working with Spring and have 2 controllers, one of them is:
#RequestMapping("/meni/{id}")
public String meni(#PathVariable String id, Model model, HttpServletRequest request, HttpServletResponse response){
cookie = new Cookie("fake_session",id);
cookie.setMaxAge(30*60);
response.addCookie(cookie);
return "meni";
}
Then in the 'meni' static HTML page, I have a post request that goes to:
#PostMapping("/index/{id}")
public void post(#PathVariable String id,#RequestBody TestDTO testDTO, HttpServletResponse response, HttpServletRequest request){
Cookie [] cookies = request.getCookies();
for (int i=0;i<cookies.length;i++){
Cookie cookie = cookies[i];
if (cookie.getName().equals("fake_session")){
System.out.println("Same cookie!");
}
}
However, the if never gets passed. If i go to the get controller twice, it recognizes the cookie, but if i go the post controller, it the if does not get passed. Everything else is running smoothly in the post controller, it does all its other tasks well.
I go to the Post controller by clicking a button that calls a ajax function in my java script that sends a POST request to that URL. Am I suppose to do something with the cookie there maybe ? I always go to the GET controller before going to the post controller so that the cookie gets created.
Try using Spring MVC's #CookieValue(value = "fake_session", defaultValue = "default") to access data set within any HTTP cookie in your post method.

How to configure java restassured library not to reuse the cookies

Am trying the reuse the restassured get call in the testng api tests, but the restassured instance in using the cookies received from the previous response.
Tried RestAssured.reset(); but this doesn't help in flushing the cookies we got from earlier request/response.
Reason for this question - As the get endpoint behaves differently if there is a session cookie exist on the request.
#Test // TestNG test
public void test_1(){
//Set Cookie
Cookie cookie = new Cookie.Builder("COOKIENAME","COOKIEVALUE").setDomain("*.com").setPath("/").setExpiryDate(SOMELATERDATE).build();
RestAssured.baseURI = https://ENV_URL;
Response response = RestAssured.given().log().all()
.cookies(new Cookies(cookie)).when().get("/END_POINT").then().extract().response().prettyPeek();
RestAssured.reset();
}
#Test // TestNG test
public void test_2(){
//Set Cookie
Cookie cookie = new Cookie.Builder("COOKIENAME", "COOKIEVALUE").setDomain("*.com").setPath("/").setExpiryDate(SOMELATERDATE).build();
RestAssured.baseURI = https://ENV_URL;
// Still Reuses the cookie received from previous response
Response response = RestAssured.given().log().all()
.cookies(new Cookies(cookie)).when().get("/END_POINT").then().extract().response().prettyPeek();
RestAssured.reset();
}
Use CookieFilter. If you want to exclude the a particular cookie you can use the following code.
#Test
public void sampletest(){
CookieFilter cookieFilter = new CookieFilter();
Response response = RestAssured.given().
cookie("foo", "bar").
filter(cookieFilter). // Reuse the same cookie filter
// if "foo" is stored in cookieFilter it won't be applied because it's already applied explicitly
expect().
statusCode(200).
when().
get("/y");
}

Cookie not getting set in browser via spring rest redirect api in httpserveletrresponse in client browser

I'm trying to set cookie in client browser while redirecting from my Spring rest api controller to app home page (hosted somewhere else) by specifying URI of home page.
But it seems cookie coming in response headers but not getting set in cookie database.
and here are the values of domain and path;
domain = localhost
path = /
isSecure = false/true based on env.
I've tried lot of things to make it work, few of them are below;
domain = localhost:8080 [ as my ui code running on 8080 port ]
domain = < ip >:8080
domain = xyz.com [ i've mention an entry in my host file with 127.0.0.1:8080 xyz.com
Any one pls help, its been stuck quite a while.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ResponseEntity<?> ssoLoginAndFetchUserInfo(#RequestParam(value = "code", required = true) String code,
#RequestParam(value = "state", required = true) String state, HttpServletResponse response) {
try {
normalLog.info("sso/login api invoked with code {} and state {}", code, state);
final SSOUserInfoHostInfoWrapper info = ssoServices.ssoFetchUserInformation(code, state);
normalLog.info("info fetched {}", info);
response.addCookie(CommonUtil.createCookie(SSOContants.UserInfoConstants.IDENTITY_TOKEN,
info.getUserInfo().getTokenInfo().getId_token(), info.getHostInfo().getHostname(),
info.getUserInfo().getTokenInfo().getExpires_in(), IDENTITY_COOKIE_NAME, "/",
info.getHostInfo().isSecure()));
response.addCookie(
CommonUtil.createCookie(SSOContants.UserInfoConstants.USER_NAME, info.getUserInfo().getUserName(),
info.getHostInfo().getHostname(), info.getUserInfo().getTokenInfo().getExpires_in(),
USERNAME_COOKIE_NAME, "/", info.getHostInfo().isSecure()));
response.addCookie(
CommonUtil.createCookie(SSOContants.UserInfoConstants.USER_ID, info.getUserInfo().getUserId(),
info.getHostInfo().getHostname(), info.getUserInfo().getTokenInfo().getExpires_in(),
USERNAME_COOKIE_ID, "/", info.getHostInfo().isSecure()));
response.addCookie(
CommonUtil.createCookie("authentication_token", "sdfsdfsdf",
info.getHostInfo().getHostname(), info.getUserInfo().getTokenInfo().getExpires_in(),
"authentication_token", "/", info.getHostInfo().isSecure()));
// Redirect to app login page
response.setHeader("Location", info.getHostInfo().getAppHomePageURI());
return new ResponseEntity<>(HttpStatus.FOUND);
} catch (Exception e) {
return super.returnSpringError(e);
}
}
Utility method
public static Cookie createCookie(final String name, final String value, final String hostname, final int expiresIn,
final String comment, final String validToPath, final boolean isSecure) {
Cookie c = new Cookie(name, value);
c.setPath(validToPath);
c.setDomain(hostname);
c.setVersion(1);
c.setComment(comment);
c.setMaxAge(expiresIn);
c.setSecure(isSecure);
return c;
}
Few screenshots for what is heapping ;
The issue is fixed. From the day one i doubt its all due to "domain".
Don't know yet why putting "localhost" in domain does not working, probably DNS not getting resolved.
Here how i resolved it;
I made an entry in /etc/hosts file with below entry
127.0.0.1 xx.yy.zz-r.com
And then use domain as ".zz-r.com" and access all the ui page via
xx.yy.zz-r.com:8080/----------
and it worked.
Encountered same problem. My case was to pass redirect from backend to frontend with attached cookies. Within one main domain. There's no success with code
cookie.path = "/"
cookie.domain = "domain.com"
cookie.maxAge = 60
cookie.isHttpOnly = false
response.addCookie(cookie)
But everything run when I changed to
response.setHeader("Set-Cookie", "customCookie=value; Path=/; Max-Age=60; Domain=domain.com")

Creating a cookie inside a jax-rs endpoint

I have a jax-rs endpoint. The purpose of the endpoint is to authorize a user. I need to login details inside a cookie. Below I have mentioned the related part of my code.
public Response authorize(#Context HttpServletRequest request) throws URISyntaxException {
if (authnResult.isAuthenticated()) {
//TODO create a cookie to maintain login state
Cookie authCookie = new Cookie(FrameworkConstants.COMMONAUTH_COOKIE, "test");
authCookie.setSecure(true);
authCookie.setHttpOnly(false);
authCookie.setMaxAge(5 * 60);
}
EDIT:
This is my first time when creating cookies. I followed some tutorials. In these tutorials it has added the created cookie to the response. But inside the endpoint I can't access the response. So how can I create the cookie? Please advice me.
Updated code:
public Response authorize(#Context HttpServletRequest request) throws URISyntaxException {
NewCookie cookie = new NewCookie("CookieName","CookieValue");
Response.ResponseBuilder builder = Response.ok("Cool Stuff");
builder.cookie(cookie);
Response response=builder.build();
Cookie[] cookies = request.getCookies();
}
what I need to know is how to access the newly created cookie.
You can create a javax.ws.rs.core.NewCookie. There are a bunch of different constructors, just go through the API docs.
Then you can add cookies through ResponseBuilder#cookie(NewCookie). So for example:
#GET
public Response getCookie() {
NewCookie cookie = new NewCookie("Name", "Value", "path", "domain",
"comment", 300, true, true);
ResponseBuilder builder = Response.ok("Cool Stuff");
builder.cookie(cookie);
return builder.build();
}
UPDATE (with complete example)
#Path("cookie")
public class CookieResource {
#GET
public Response getCookie(#CookieParam("A-Cookie") String cookie) {
Response response = null;
if (cookie == null) {
response = Response.ok("A-Cookie: Cookie #1")
.cookie(new NewCookie("A-Cookie", "Cookie #1"))
.build();
return response;
} else {
String cookieNum = cookie.substring(cookie.indexOf("#") + 1);
int number = Integer.parseInt(cookieNum);
number++;
String updatedCookie = "Cookie #" + number;
response = Response.ok("A-Cookie: " + updatedCookie)
.cookie(new NewCookie("A-Cookie", updatedCookie))
.build();
return response;
}
}
}
After 38 requests, you can see the result. I used a Firefox plugin Firebug. You can see the sent cookie #37, and returned cookie #38
If you need help trying to access the cookie from the client (as suggested in your comment), that may be suitable for another question on SO. Maybe off topic for this discussion, as it will rely on another technology. If this is not what you are looking for, then maybe a better explanation of exactly what you are trying to accomplish would help.

encodeRedirectURL changes some characters

I have an Interceptor on Struts2, and I want for some pages to redirect to the ssl version of them.
Example: http://localhost/xhtml/path.do?ossesionid=value1 to https://localhost/xhtml/path.do?ossesionid=value1
For doing this I created a Interceptor that does this:
public String intercept(ActionInvocation invocation) throws Exception {
// initialize request and response
final ActionContext context = invocation.getInvocationContext();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final HttpServletResponse response = (HttpServletResponse) context
.get(StrutsStatics.HTTP_RESPONSE);
// check scheme
String scheme = request.getScheme().toLowerCase();
// check method
String method = request.getMethod().toUpperCase();
// If the action class uses the SSLProtected marker annotation, then see
// if we need to
// redirect to the SSL protected version of this page
if (invocation.getAction() instanceof SSLProtected) {
if (HTTP_GET.equals(method) && SCHEME_HTTP.equals(scheme)) {
// initialize https port
String httpsPortParam = request.getSession().getServletContext().getInitParameter(HTTP_PORT_PARAM);
int httpsPort = httpsPortParam == null ? HTTPS_PORT : Integer.parseInt(httpsPortParam);
response.setCharacterEncoding("UTF-8");
URI uri = new URI(SCHEME_HTTPS, null, request.getServerName(), httpsPort, response.encodeRedirectURL(request.getRequestURI()), request.getQueryString(), null);
log.debug("Going to SSL mode, redirecting to " + uri.toString());
response.sendRedirect(uri.toString());
return null;
}
}
My problem is that I expect this
https://localhost/xhtml/path.do?ossesionid=value1
and got
https://localhost/xhtml/path.do;jsessionid=value1?osessionid=value1
And I'm Completly lost! help anyone?
i strongly suggest you to use S2-SSL plugin which is more flexible and provides a much better support to handle switch from SSL to non-SSL and vice-versa.
regarding generation of Jsessionid,JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session.You have ways to disable the creation of Jsessionid
There are number of way you can disable the creation of this id, please refer to this discussion thread.
I am still not sure what is the problem you are facing with this session-id as it is a very common case in web applications
is-it-possible-to-disable-jsessionid-in-tomcat-servlet

Categories

Resources