0
Follow
0
View

Can you send cookies across domains and jump to login through Java and the front end?

lwaooo0777 注册会员
2023-02-27 11:27

Little witch referred to bing and GPT part of the content write :
Yes, you can use Java and front-end to achieve cross-domain send cookies and jump to log in to the target website. To do this, you need to create a project locally and write Java code and front-end code in the project.

Specifically, first, you need to create a Java Web project locally and add a Servlet to the project to handle cross-domain requests. The HttpServletResponse object is then used to write the cookie into the response header, and the HttpServletRequest object is used to read the data in the cookie and pass the data to the front end.

Next, in the front-end code, the XMLHttpRequest object is used to send a cross-domain request to the Java Servlet to get the data in the cookie. Then, the obtained data is taken as parameters, and the window.location.href method is used to jump to the target website to realize the function of sending cookies across domains and jumping to login.

//Java Servlet 代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // 设置cookie
    Cookie cookie = new Cookie("username", "admin");
    cookie.setMaxAge(60 * 60 * 24);
    response.addCookie(cookie);

    // 读取 cookie 中的数据
    Cookie[] cookies = request.getCookies();
    String username = null;
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (c.getName().equals("username")) {
                username = c.getValue();
            }
        }
    }

    // 向前端返回数据
    response.setContentType("text/plain; charset=utf-8");
    response.getWriter().write(username);
}  
// 前端 JavaScript 代码 
var xhr = new XMLHttpRequest();  // 创建 XMLHttpRequest 对象 
xhr.open('GET', 'http://localhost:8080/servlet', true);  // 跨域请求 servlet 
xhr.withCredentials = true;  // 请求带上 cookie 信息 
xhr.send();  // 发送请求 
xhr.onreadystatechange = function() {  // 注册回调函数 
    if (xhr.readyState == 4 && xhr.status == 200) {  // 成功请求到数据 

        // 读取 cookie 中的数据 
        var username = xhr.responseText;

        // 跳转到目标网站并带上 cookie 数据 
        window.location.href = 'http://www.example.com/?username=' + username;  

    }  
};  

The answer is not easy, so take it.

dengfei698 注册会员
2023-02-27 11:27

Generally, browsers do not allow cookies to be sent across domains because of security restrictions. However, you can allow cookies to be sent across domains by setting Access-Control-Allow-Credentials: true in the request header.