[Other] cookie & session record learning to solve cross-domain login issues

First, the essence of the storage location of Cookie & Session

1, Cookie & Session role

When the same web application repeatedly into different pages, in order to avoid multiple login operation, there is a cookie, a small amount of user information by way of key-value pairs stored on your computer, free of modified so very safe. It created a new mechanism to store session: ways session, session is also a service area for storing data, it exists in the / tmp directory on the server (local server memory address for the next / tep directory of tomcat), all the mechanisms that session based on this session_id, which is used to distinguish which is several times a request issued by a person. Why has to be this way? Since HTTP is a stateless unrelated, a page may be accessed by hundreds of people, and each person's user name is not the same, then the server is how to distinguish the visit of Wang, Xiao Ming that is accessible it? So there will find a unique session_id to bind a user. A user is in a conversation on a session_id, so that thousands of people visit, the server can distinguish in the end who is visited. Landing is usually achieved by storing a cookie session_id, then the specific data stored in session, if the user has logged in, the server saves the session_id in a cookie, the next time again request, will carry the session_id up, according to the server session_id get the user's session data in the session database, the user will be able to know who in the end is, as well as some of the previously saved state.

2, Cookie & Session relationship

① cookie is stored on the client side, server-side session in memory, so the session is safe to coookie.
The information session ② acquisition is acquired through the session cookie stored in the sessionId.
③ because the session is stored in the server, so the session was something growing will increase the burden on the server, we will put some important things on the session, the less important in the cookie .
④ cookie divided into two categories, one is the session cookie and cookie persistence, their life cycle and are consistent with the browser, the browser closed session cookie will disappear, so the session will disappeared, case closed session loss for the server or session expired (default thirty seconds).

3, session works

① a customer's first visit to a page server, the server will assign a session object for the user, and assign a unique ID for this session, and transmits the ID to the client and written to the cookie so that the client and server session to establish one to one relationship;
② when clients continue to access other resources on the server side, the server will not assign a new session object for the client until the client the browser is closed, the session times out or call invalidate () render ineffective, the end of the session the client and the server.
③ When customers visit the site to re-open the browser, the server will re-assign a session object for the client, and reassign sessionID.
use

Two, Cookie & Session common method

1, Cookie common methods:

Note: modify, delete when Cookie, Cookie new all attributes except value, maxAge, such as name, path, domain, etc., should be exactly the same as the original Cookie. Otherwise, the browser will be treated as two different Cookie and Cookie does not overwrite the previous, leading to modify, delete failed.

①cookie creation method
//创建一个cookie并设置过期时间
Cookie cookie = new Cookie("key","value");
cookie.setMaxAge(60*60*24);//设置过期时间,单位为秒
cookie.setValue("newValue");//给当前cookie的value重新赋值
cookie.setComment("这个cookie是用来测试玩的");//对当前cookie进行描述的信息
cookie.Domain(".baidu.com");//这个cookie只能在域名为baidu.com的网站内使用,必须符合pattem域名正则规范(不能跨域!!)
cookie.setHttpOnly(true);//设置为true之后,只能通过http访问该cookie,js无法访问,还可以防止xss读取cookie
cookie.setPath("/");//设置cookie的使用路径,后面紧跟着详解。如果设置为"/shop/",则只有url为"/shop/"的程序可以访问,如果设置为"/",则该域名(服务器)下的所有url都可以访问该cookie。注意最后一个字符必须为"/"
cookie.setSecure(true);//是否使用安全传输协议。为true时,只有当是https请求连接时cookie才会发送给服务器端,而http时不会,但是服务端还是可以发送给浏览器端的
//保存到客户端
HttpServletResponse response;//从浏览器获取到的response,在接口方法的括号里面写这一句话
//HttpServletResponse response = ServletActionContext.getResponse();//ssh项目得到response
response.addCookie(cookie);
②cookie acquisition method
//HttpServletRequest request;//从浏览器获取到的response,在接口方法的括号里面写这一句话
HttpServletRequest request = ServletActionContext.getRequest();//ssh项目得到request
Cookie[] cookies = request.getCookies();//得到该客户端的全部cookie
String username=null;
String pwd=null;
for(Cookie c :cookies){
    if("username".equals(c.getName())&&"pwd".equals(c.getName())){
        username=c.getValue();
        pwd=c.getValue();
        break;
    }
}

2, Session common method

HttpServletRequest request = ServletActionContext.getRequest();//ssh项目得到request
HttpServletResponse response = ServletActionContext.getResponse();//ssh项目得到response
HttpSession session = request.getSession();
session.setAttribute("key","value");//向session中添加一个键值对,如果这个键是会话范围内存在,则更改该value的值。
session.getAttribute("key");//返回value,如果没有这个键值对则返回null
session.removeAttribute("key");//删除指定key的键值对,如果该key不存在则出现异常
session.invalidate();//使session失效,立即使当前会话失效,原来会话中存储的所有对象都不能在被访问
session.getId();//获取当前会话的id,每个会话在服务器端都存在一个唯一标识sessionID,,session对象发送到浏览器的唯一数据就是sessionID,它一般被存储在cookie中
session.setMaxInactiveInterval(60*60*24);//设置会话的生命周期,单位为秒,负数表明会话永不失效
session.getMaxInActiveInterval();//获取会话的最大持续时间,使用时需要处理格式
session.idNew()//用来判断该session是否为新建立的

Three, Cookie & Session encountered pit

1, using ajax to achieve the landing and save the session & cookie;

ajax add the following sentence is not the code, there is no way to enter the ajax method in the current session! ! There is no way to achieve storage function of the current session interface.

$.ajax({
    type:"POST",
    url:'http://localhost:8080/user-login',
    data:$("#from").,
    dataType:'JSON',
    withCredentials: true,//这一句话!
    success:function(){}
    error:function(){}
})
//上面那句话不行就换成下面这个:
//xhrFields: {
//    withCredentials: true
//},

2, cross-domain requests landing and save the session & cookie

Starting with a post cross-domain, out for an afternoon, it was the project manager Tucao: "post What the hell, you pass by post other people do not know what this is!"

function Login() {
        var url = "/do_login";
        $.ajax({
            url: url,
            type: "post",
            data: $("#loginFrom").serialize(),
            success: function (data) {
                console.log(data);
                var json = eval(data);
                var token = json.message;
                console.log(token);
                //token为后端加密后的用户名
                //上面的url为本地请求的地址
                //下面的url为跨域请求的地址,请求完后,2号服务器就存好session和对应的cookie,可直接访问主页而不被拦截
                $.ajax({
                    url:"http://192.168.0.59:8080/userinfo/userinfoAction!getUserBy.action?actoken="+token,
                    type:"get",
                    success:function (data) {
                        console.log("success:"+data)
                    },
                    error:function (data) {
                        console.log("error:"+data)
                    }
                })
            },
            error: function (data) {

            }
        })
    }

3, Cookie the setDomain () method does not cross-domain

I started to think that the cookie setPath () and setDomain () method is very powerful, cross-domain storage have been trying, in the end did not complete the task ran to ask the project manager.
By default, the cookie can only be shared in an application that a cookie can only be obtained by the application that created it.
Want to achieve cross-domain receives a memory write interface on the No. 2 server, the server sends a No. 1 can achieve the purpose of the field directly get request method, of course, in the enterprise application development in this field is certainly that have been encrypted, such as two servers to achieve one of the landing page, the two sides have achieved the landing, so you need to encrypt a user name and a way to get the user name encrypted reached the No. 2 server, no password verification, direct realization landing, the equivalent of landing a third party, of course, this would certainly be encrypted according to the time stamp change, otherwise too unsafe (①post request can not be achieved save session cookie operation and cross-domain request, ② a good encryption algorithm even the authors solution can not be, nor need to solve)

Reference article will not list them too, very grateful!
Published 20 original articles · won praise 1 · views 571

Guess you like

Origin blog.csdn.net/weixin_42295814/article/details/99177320