Setting cookie from java spring boot rest API to angular. Changing port

Discussão em 'Angular' iniciado por Beach Bum Bob, Dezembro 30, 2024.

  1. I have a small Rest API built with Spring Boot and an angular (18) front end. What I want is to get a cookie from the back end sent to the front end. When I do another call from the front end to the back end I want that cookie to be send to the back end.

    The back end is running on port 8080 and de front end on port 4200. I have looked thru a lot of answers here on stackoverflow and tried to follow numerous tutorials and blogs.

    The cookie is used to identify a client. I do not want a session cookie or a cookie to secure my service, that is a task for the future.

    My rest api has @RestController, @RequestMapping("/api") and @CrossOrigin(origins = "*", allowedHeaders = "*", methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE }) annotations.

    First I call en endpoint called getnewid.

    @GetMapping("/getnewid")
    public String getNewID(HttpServletRequest request, HttpServletResponse response,
    @CookieValue(value = Util.CLIENT_ID_COOKIE_NAME, defaultValue = "") String cookieValue)
    throws CabinException {

    Cookie cookie = Util.getNewID(request.getRemoteAddr(), request.getHeader("User-Agent"), cookieValue);

    response.addCookie(cookie);
    response.setStatus(200);

    return cookie.getValue();

    }


    That calls a Util class to generate a new cookie.

    String tmpCookieClientID = UUID.randomUUID().toString();
    Cookie clientIDCookie = new Cookie("cabinCTRLclientID", tmpCookieClientID);
    clientIDCookie.setDomain("localhost");
    clientIDCookie.setMaxAge(60 * 60 * 24 * 365);
    return clientIDCookie;



    If I call the endpoint directly in Firefox I get the cookie with the "correct" host.

    [​IMG]

    If I call the endpoint from my Angular app, I the the "wrong" host.

    [​IMG]

    The following is from the angular service and the code that calls the service

    getNewKey(): Observable<string> {
    return this.httpClient.get<string>(this.baseURL + "getnewid");
    }



    getNewKey() {
    this.subs.add(this.clientService.getNewKey().subscribe(key => console.log(key))
    );
    }


    Any help is greatly appreciated.

    Continue reading...

Compartilhe esta Página