I have a login service which passes user login information to my application when I login. This will call first page of my application on successful login. The user info is passed as part of a cookie in this request.
I am trying to read these cookies from the request in my Web API request using the below code.
CookieHeaderValue getAccessUserInfo = request.Headers.GetCookies("GAUSERINFO").FirstOrDefault(); if (getAccessUserInfo != null) { userInfo = getAccessUserInfo["GAUSERINFO"].Values.Get("corporate_id"); Logger.Info(string.Format("User Cookie {0}", userInfo)); return userInfo; }
But if I am trying to read the same cookie from javascript or angular js, I am not able to see that cookie in the collection. Below is the code I am using to read the cookie in angular js.
console.log($document[0].cookie);
This is the cookie I can see from the result. The cookie I am expecting is GAUSERINFO along with the below cookies.
Is there a way to read these cookies from angular js or atleast pass that request body to the API so that I can read the cookie in my API using C# code.
1 Answers
Answers 1
JavaScript doesn't have access to HTTP only cookies for security reasons. In order to prevent XSS attacks, generally user session/login information should be HTTP only. If an attacker were to get the user's session information, they could impersonate the user. If you want to expose user info like corporate_id
to the client side, it can be in a separate cookie that is not marked as HttpOnly.
From MSDN for HttpCookie.HttpOnly:
Stolen cookies can contain sensitive information identifying the user to the site, such as the ASP.NET session ID or forms authentication ticket, and can be replayed by the attacker in order to masquerade as the user or obtain sensitive information. When an HttpOnly cookie is received by a compliant browser, it is inaccessible to client-side script.
To use corporate_id
client side, create a separate cookie with the only the information you need client side and when you create it in your C# code be sure to set HttpOnly
to false.
Edit: If your use case is to forward the cookie along to your API using Angular's $http service, there's additional configuration you can do for it which is detailed in this answer: https://stackoverflow.com/a/17065576/6950124
The summary of it being that you need to set $httpProvider.defaults.withCredentials = true;
and potentially also configure your web server to send back the header Access-Control-Allow-Credentials: true
when the browser initially requests the page. This lets the browser know that your JavaScript code can have partial access to the HttpOnly cookies.
The underlying browser code for making the AJAX call should forward HttpOnly cookies if you have everything configured properly.
0 comments:
Post a Comment