I'm puzzled as to why my set-cookie disappears after I make a subsequent request

Issue arises when logging in through an endpoint results in a response header with a http-only cookie. However, subsequent requests to other endpoints do not include the set-cookie in the headers. Attempts have been made to resolve this problem.

The following is the Angular code within a service.ts file:

private apiUrl = environment.baseUrl +  '/api/v1/login';
private apiUrl2 = environment.baseUrl + '/api/v1/anotherRequest';
login(req: Login): Observable<string> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
    return this.httpClient.post<string>(this.apiUrl,JSON.stringify(req),{ headers })
  }
anotherRequestBeingMade(): Observable<any]> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
   
    return this.httpClient.get<any>(this.apiUrl2,{withCredentials:true})
  }

This demonstrates the setup of an HTTP-only cookie in Fiber using Golang:

cookie := fiber.Cookie{
        Name:     "my_cookie",
        Value:    *value_here*,
        Expires:  time.Now().Add(time.Hour * 24),
        HTTPOnly: true,
        Secure:   true,
        SameSite: "None",
        Path:     "/",
    }

    c.Cookie(&cookie)

Testing in Postman shows the cookie being set in the response header for the login endpoint but not carried over to subsequent requests in the Cookie header when tested in Angular client. Various attempted solutions include:

  • Including {withCredentials:true} inside the get httpClient

  • Resolving CORS issues in the Golang backend

app.Use(cors.New(cors.Config{
       AllowOrigins:     "http://localhost:4200",
       AllowHeaders:     "Origin, Content-Type, Accept",
       AllowMethods:     "GET, POST, PUT, DELETE, OPTIONS",
       ExposeHeaders:    "Set-Cookie",
       AllowCredentials: true,
   }))
  • Attempting to bypass the proxy by setting up a proxy.conf.json and configuring the package.json script as follows:
"start": "ng serve --proxy-config proxy.conf.json",
{
"/api/*": {
  "target": "http://localhost:8080",
  "secure": false,
  "logLevel": "debug"
}
}

Adding an environment.ts file in the src folder of the Angular app:

export const environment = {
    production: false,
    baseUrl: 'http://localhost:8080' // Update according to your backend server URL
  };

Thank you for any assistance provided.

Answer №1

I had overlooked the absence of the withcredentials:true in the httpclient configuration for my login api

login(req: Login): Observable<string> {
    const headers = new HttpHeaders({'Content-Type': 'application/json'});
    return this.httpClient.post<string>(this.apiUrl,JSON.stringify(req),{headers,withCredentials:true})
  }

Answer №2

After logging in using an endpoint, the response header includes a http-only cookie with set-cookie attribute. However, when making requests to other endpoints, the set-cookie is not visible in the request headers.

No need to worry about this. According to the Set-Cookie header rules, it only needs to be set during login and does not have to be repeated for every subsequent request to maintain the cookie's presence.

For clients, the equivalent is the Cookie header. Make sure to check your browser's developer tools to confirm that subsequent requests include the Cookie header.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refreshing display with information received from web socket in Angular 5

On my page, I am receiving an array of data upon page load and displaying it using the *ngFor directive. Additionally, there is a connection established to a Web Socket to receive updated data, which in this case pertains to a timetable for boat trips. The ...

Could the presence of unused components in shared modules be a cause of slowdown in my application's

When importing my shared module into my electronic component, I also import it into other categories like video games and toys. However, some components within the shared.module may not be used once imported. Will these unused components in my shared mod ...

Tips for preserving data in Angular form fields

Within my angular application, a scenario exists where two pages are involved. On the initial page, users input data into a form and proceed by clicking "continue" which leads them to the subsequent page. The following page features a back button that ena ...

"Debating Angular: Comparing the Use of Getters and Methods in

To prevent cluttering the *ngIf directive with logic directly in the template. <div *ngIf="a === 3 && b === 'foo'"></div> I typically create a custom method like this: public isOk(): boolean { return a === 3 & ...

Issue: Failed to access the 'setDir' property of an undefined object

Greetings, I am a newcomer to Ionic/Angular and have been facing a particular issue for over 20 days now. I have created a small app and would like to implement multi-language support with both RTL and LTR directions. I followed the documentation provided ...

Encountering an Angular 12 error 401 upon refreshing the page

Currently, I am working on a login form using angular 12 with Spring Boot that includes basic authentication spring security. When a user successfully logs in, they are directed to the main page which offers CRUD actions as depicted in the images linked be ...

Tips for upgrading Angular ComponentFactoryResolver and ComponentFactory within a service

Currently, I am in search of an alternative for the deprecated ComponentFactoryResolver and ComponentFactory classes in Angular 13. Both the official documentation and another Stack Overflow question recommend utilizing ViewContainerRef. However, my applic ...

Checking for queryParam changes in Angular before ngOnDestroy is invoked

I am looking to conditionally run some code in the ngOnDestroy function depending on changes in the current route. Specifically, when the route changes from /foo to /login?logout=true, and this change is initiated outside of the Foo component. In the ngO ...

Passport.js consistently returns an unauthorized status for every request, even when a valid token is provided, or it author

I am facing issues with my Passport.js functions not authenticating users properly. When I use the current form, it always returns "unauthorized" for all requests: import passport from 'passport' import passportJWT from 'passport-jwt' ...

Pairing a string from a designated set to another string within a designated set using TypeScript

I have received a string from an API and need to generate another string based on it. The possible values for the received string from the API are: "customField" | "customForm" | "customAction". The provided code demonstrates how I am currently handling t ...

Switching services in test cases with ReflectiveInjector

Can the provider be changed using ReflectiveInjector in the same context? I require B to utilize a different value for the second test. A & B are both services... let injector: ReflectiveInjector; beforeEach(() => { injector = ReflectiveInjec ...

Resetting a FormArray property using form.reset() in Angular 2 Model-Driven forms does not properly reset the values

I am facing an issue with my Angular 2 model driven form where the count of items in a property of type FormArray is not reset to the original value when I use the myForm.reset(this._originalValue) method. To see the problem in action, you can check out t ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Personalizing Dialog Title in material-ui

While delving into the world of React and Material-UI, I encountered a challenge in updating the font color in the DialogTitle component. After browsing through various resources, I came across a helpful link that suggested overriding the dialog root class ...

Exploring the use of MockBackend to test a function that subsequently invokes the .map method

I've been working on writing unit tests for my service that deals with making Http requests. The service I have returns a Http.get() request followed by a .map() function. However, I'm facing issues with getting my mocked backend to respond in a ...

The HighCharts is displaying an error message stating "Unable to detect the property 'series' as it is

Is there a way to retrieve all data along with the chart type and other details, but I keep encountering this error: Cannot read property 'series' of undefined. Below are the component.ts and service file: const sampleData: Overview[] = [ ...

Creating a return type for JSON observables in Angular 2 by defining it as an interface or

I want to ensure that my JSON API response is easily organized into a class or interface so that I can always identify the attributes present. The JSON data I am working with is as follows: { "users": [ { "id": "bd3d70fd-03f7-4f5e-9ac1-4cb7221 ...

Creating a channel for communication between sibling components in Angular 4 by storing component references in a shared service

I am searching for a way to establish communication between two sibling Angular 4 components. After reviewing the documentation at https://angular.io/guide/component-interaction, my idea revolves around utilizing a service that stores a reference to the c ...

What sets apart `lib.es6.d.ts` from `lib.es2015.d.ts` in TypeScript?

I'm a bit confused about ES6 and ES2015. In TypeScript, there are two type declarations available for them: lib.es6.d.ts and lib.es2015.d.ts. Can someone explain the difference between these two? And which one is recommended to use? ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...