Springboot+vue front and back end separation session cookie invalidation problem

question

Vue is deployed on the local port 81, and springboot is deployed on the local port 80. Cross-domain access is set up for development, but the session is set after the login is successful, and when other interfaces call the session, it fails and displays null.

Solution

The first step is the front end.
Because I use axios on the front end to make http requests, add the following piece of code to the axios page.

Meaning: It indicates whether credentials such as cookies, authorization headers (head authorization) or TLS client certificates should be used to create a cross-site access control (cross-site access-control) request.

What I understand means: when set to true, the same cookie is used even for cross-domain access (not necessarily accurate)

axios.defaults.withCredentials = true;

The second step backend
The backend needs to set information for the header of the response:
here is a filter to do it:

package com.bear.bearspringboot.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "CORSFilter")
public class CORSFilter implements Filter {
    
    


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String origin = req.getHeader("Origin");
        if(origin == null) {
    
    
            origin = req.getHeader("Referer");
        }
        resp.setHeader("Access-Control-Allow-Origin", origin);//这里不能写*,*代表接受所有域名访问,如写*则下面一行代码无效。谨记
        resp.setHeader("Access-Control-Allow-Credentials", "true");//true代表允许携带cookie
        //下面这两个也很关键
        resp.setHeader("Access-Control-Allow-Methods", "*");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
//        resp.setHeader("Access-Control-Expose-Headers", "*");
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
    
    

    }
}

Finally, add @ServletComponentScan to the startup class

Reference:
https://www.cnblogs.com/zimublog/p/10786110.html

Guess you like

Origin blog.csdn.net/weixin_42433157/article/details/106568326