Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Mvc Api: Set cookie then 302/303 Redirect loses the cookie

I have an API action that returns a HttpResponseMessage. API address is like: http://localhost/login?authcode=xxx

The API action does some login authentication and redirects the user to either register or the welcome page. Code goes like:

var response = new HttpResponseMessage();
var cookie = new CookieHeaderValue("token", "ThisIsTheTokenNeeded");
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
response.StatusCode = HttpStatusCode.Found;
response.Headers.Location = new Uri("http://localhost/welcome.html");
return response;

In welcome.html, I use "document.write(document.cookie)" and cannot see the cookie named "token". Some how it got lost. Could anyone tell me how to get this done or this architecture is not correct after all?

like image 363
Lionet Chen Avatar asked Aug 26 '15 06:08

Lionet Chen


1 Answers

I found the answer. The scope is not set. In my original code the following line is missing.

cookie.Path = "/";

Because redirecting to another page, even if under the same domain, the cookie is not valid across different pages. If path is not set, then the cookie is only valid with the original request targeting http://localhost/login?authcode=xxx

Today I learnt that I need to carefully examine the domain and the path attribute of the cookie before claiming that somebody ate it.

like image 148
Lionet Chen Avatar answered Sep 19 '22 14:09

Lionet Chen