Home > front end >  Angular Spring Boot - Can't send cookies over HTTPS
Angular Spring Boot - Can't send cookies over HTTPS

Time:02-16

I have an Angular 12 front-end application communicating with a Spring Boot back-end one. APIs shall be called passing a CSRF token using a cookie, but it seems like my logic is only working for localhost.

Please find the following snippets of code:

  • Angular cookie set through ngx-cookie-service:
this.cookieService.set(key, value, {
   secure: environment.apiHost.startsWith('https'),
   sameSite: environment.apiHost.startsWith('https') ? 'None' : undefined
});
  • Angular interceptor called before each request:
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // Handle cookies
    request = request.clone({
      withCredentials: true
    });
    return next.handle(request).pipe(
      ...
    );
}
  • Spring Boot CORS general configuration:
List<String> allowedOrigins = new ArrayList<>();
allowedOrigins.add("http://localhost:4200");
allowedOrigins.add("https://<host_name_not_localhost>");

config.setAllowCredentials(true);
config.setAllowedOrigins(allowedOrigins);
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/api/**", config);

return new CorsFilter(source);

I honestly don't understand if the issue lays in the front-end or in the back-end part... Again, sending cookies over HTTP (localhost) works fine, while the Cookie attribute doesn't appear when debugging the call over HTTPS.

Do you have any advice on this?

Thank you in advance.

CodePudding user response:

The only reason here could be that while creating cookie you are not setting domain with domain of backend. You can do something like

var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth()   12);
document.cookie = cookieName  "="   cookieValue   ";expires="   myDate 
                    ";domain=.example.com;path=/";

In the above case example.com is your domain of backend. or by using cookies api, refer here :- https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API

CodePudding user response:

I decided to get rid of the cookies and pass the information in the request header, which seems to be a much more secure approach. Plus, I can control the allowed headers from the back-end itself.

  • Related