1.使用IP
无论是前端还是后台,都需要使用ip进行发送请求,不要使用localhost
2.前端配置传递cookie
import axios from 'axios
axios.defaults.headers['Content-Type']='application/json;charset=utf-8'
const service = axios.create({
baseURL:"http://127.0.0.1:7788/api",
timeout:10000,
withCredentials:true //跨域请求时是否需要使用凭证
})
3.后台cors过滤时候,配置允许跨域
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//代表当前类中所有的请求都允许跨域访问
registry.addMapping("/*")
// 配置哪个域 允许跨域访问
.allowedOrigins("http://127.0.0.1:8080")
//允许跨域
.allowCredentials(true)
// 许所有的请求方式
.allowedMethods("*")
// 允许任意请求头
.allowedHeaders("*");
}
}
4.shiro过滤器放行Options请求
配置shiro的自定义拦截器用来放行全部的OPTIONS,请求我们现在的跨域方式是cors
原理:当我们需要跨域请求的时候,此时会首先发送一个请求方式为OPTIONS类型的请求到后台获取后台是否允许跨域的认证: 代码发送的请求 GET http://127.0.0.1:7788/api/emp/getInfo ===> 跨域实际的请求 OPTIONS http://127.0.0.1:7788/api/emp/getInfo 获取当前请求是否允许跨域 GET http://127.0.0.1:7788/api/emp/getInfo
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyShiroFilter extends FormAuthenticationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
HttpServletRequest req = (HttpServletRequest) request;
if (StringUtils.equalsAnyIgnoreCase(req.getMethod(), HttpMethod.OPTIONS.name())) {
return true;
}
return super.isAccessAllowed(request, response, mappedValue);
}
}
5.将过滤器加入到shior配置中
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//...
//自定义拦截器
Map<String, Filter> filters = new LinkedHashMap<>();
filters.put(authc.name(), new MyShiroFilter());
factoryBean.setFilters(filters);
return factoryBean;
}