Can not access cookie on one endpoint, but can on other

Viewed 34

I need your help on this matter. It looks like I have the Schrodinger's cookie!

I am using Spring Boot with Java. I can successfully create the cookie like this:

public String createNewCookie(HttpServletResponse response) {
        // create a cookie
        String newToken = AccountsService.generateRandomCode(6);
        Cookie cookie = new Cookie("clrToken", newToken);
        cookie.setMaxAge(10 * 365 * 24 * 60 * 60); // expires in 10 years
        cookie.setSecure(true);
        cookie.setHttpOnly(true);

        //add cookie to response
        response.addCookie(cookie);

        return newToken;
    }

I can easily fetch created cookie and read its value (token) in one of my controllers like this:

@PostMapping(value = "/public/save",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Operation(summary = "Save new affiliate click into database")
    public ResponseEntity<AffiliateClickDto> saveAffiliateClick
            (@RequestParam Long serviceId,
             @CookieValue(value = "clrToken", defaultValue = "") final String token) {
        return new ResponseEntity<>(affiliateClickService.saveAffiliateClick(serviceId, token), HttpStatus.OK);
    }

But I can not fetch that same cookie from another endpoint in my other controller.

@GetMapping(value = "/public/servicesByFilters",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Operation(summary = "Get all Providers Services for filters")
    public ResponseEntity<List<ServiceResultPageDTO>> getAllProvidersServicesForFilters
            (@RequestParam final Map<String, String> params,
            @CookieValue(value = "clrToken", defaultValue = "") final String token) {
        return new ResponseEntity<>(services.getAllProvidersServiceForFilters(params, token), HttpStatus.OK);
    }

I get an empty String for The String token parameter value.

I allso tried to use the loop to iterate through cookies, but I do not get my "clrToken" at this second endpoint. I can access some other cookies.

public String readAllCookies(HttpServletRequest request) {

        String token="";

        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies) {
            if (Objects.equals(c.getName(), "clrToken")) {
                token = c.getValue();
                break;
            }
        }

        return token;
    }

Who eat my cookie??? :D Does anyone have idea what is happening here? If you need some other info, please ask.

0 Answers
Related