I'm trying to save an httpOnly cookie returned by an ASP.NET Core API with a jwt token in an Angular application, but as far as know (and I could verify that with some tests), it is not possible to save it via Javascript, so I can't do something like that:
this.httpClient.get("https://localhost:5001/token", {withCredendials: true}).subscribe(result => {
//logic to extract cookie from result
document.cookie = cookie;
});
This is my controller code:
[HttpGet("token")]
public HttpResponseMessage Token()
{
//some logic to get the token
var cookie = new CookieHeaderValue("token", token);
cookie.HttpOnly = true; //Without that line the JS code works and I can see the cookie in Chrome DevTools
cookie.Secure = true;
var response = new HttpResponseMessage();
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return response;
}
My Angular app is running on https://localhost:4200 and my API in https://localhost:5001
So, how can I do that?
CodePudding user response:
I was doing it wrong in the API side, instead of returning the cookie in the HttpResponseMessage I needed to add the cookie in the Response of the HttpContext:
HttpContext.Response.Cookies.Append("token", token, new CookieOptions { HttpOnly = true, Secure = true })
In that way the Set-Cookie header of the response is set and now it is working fine.