Can't access cookies from [removed] in JS, but browser shows cookies exist

后端 未结 6 783
时光取名叫无心
时光取名叫无心 2020-11-28 04:38

I can\'t access any cookie from JavaScript. I need to read some value and send them via JSON for my custom checks.

I\'ve tried to access cookies from JS, like it was

6条回答
  •  孤街浪徒
    2020-11-28 05:07

    You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.

    So you either have to disable the httponly flag or you need to find another way to get the data to your javascript.

    By looking at your code it should be easy to disable the http only flag:

    Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
    Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
    Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });
    

    Now you should be able to access the cookie information from JavaScript. However I don't know exactly what kind of data you are trying to get so maybe you can go for another approach instead and for example render some data attribute on the page with the information you need instead of trying to read the cookie:

    console.log(document.getElementById('example').getAttribute('data-info'));
    

提交回复
热议问题