Search code examples
angularapisetcookie

how to get set-cookie from HTTP header request and send it in another API angular


In my angular project, I have a basic signin page where user enters their email and password and on submit, I send the email and password to server and receive a response that contains setcookie which I have to use in the next page which is two-factor authentication. I want to use that cookie in another API call (for two-factor authentication) but I don't know how.

This is my userLogin API call:

userLogin(formdata: Login ): Observable<any> {
    return this.http.post
    (this.ServerUrl + 'Account/login', formdata, { headers: new HttpHeaders({'accept': 'text/plain',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.token,
      }), observe: 'response' , withCredentials: true });
  }

And this is the response cookies that i get from server: Cookies

And this is my user2fa API call:

 user2Fa(formdata: Factor ): Observable<any> {
    return this.http.post
    (this.ServerUrl + 'Account/twoFactorLogin', formdata, { headers: new HttpHeaders({'accept': 'text/plain',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + this.token,
      }), observe: 'response' , withCredentials: true });
  }


Solution

  • You are unable to access the cookie from your Angular code are you? I had faced similar issues in the past but I did not require to make any changes in my code. I had to make some environment-specific changes.

    I do not know the exact environment you are working with, but the following points might help you out with finding a solution:

    1. The login REST API call and the subsequent REST API call, if they being made to the same server/URL domain, the cookies should be automatically sent along with your request in the subsequent requests by your browser.
    2. Check the Headers tab of your response from the login REST API's response. Does the set-cookie entry have an attribute named "HttpOnly"? If this is the case, I doubt whether the cookie will be accessible from javascript code.
    3. If point no. 2 is applicable, is your Angular application running on HTTP and your REST API running on HTTPS? If so, unless your Angular application is running on HTTPS, your browser will not be sending back the received cookie in the subsequent requests. In this case, you may need to use a self-signed certificate to run your Angular application on HTTPS on localhost to test.

    Also, I would suggest you test your current set-up running the Angular application and check if the same behavior is seen.