我在本地用postman单独测试接口时没问题,能实现正常登录认证授权,但是将接口对接到vue上就出问题了。折磨了两天后终于发现了答案:axsio跨域请求不会携带cookie!而shiro的工作原理又需要一个叫做JSESSIONID的cookie值来找到登录的用户。
浏览器控制台可以看到没有发出cookie:
而postman本地测试是有的:
要解决这个问题,首先在springboot后端中解决跨域问题:
@Configuration
public class CORSFilter {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 注意这里,域最后不写写*,要写具体的值。不然cookie可能用不了
//config.addAllowedOrigin("*");
config.addAllowedOrigin("http://localhost:8080");
config.setAllowCredentials(true);
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedHeader("*");
config.setMaxAge(360000L);
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}
}
在vue axios全局配置中加上这两行:
// create an axios instance
const service = axios.create({
baseURL: "http://localhost:8081",
timeout: 5000,
headers: {
'Content-Type': "application/json;charset=utf-8",
'Access-Control-Allow-Credentials':"true"//1
},
withCredentials:true//2
})
再试试,是不是大功告成了呢?