
axios跨域请求设置并携带Cookies
when the request’s credentials mode is ‘include’.」时说当请求是携带凭据模式(即Access-Control-Allow-Credentials: true、携带Cookie)时,Response的header “Access-Control-Allow-Origin” 的值不能是“但是,接下来在域名oauth.szile.com域名下请求接口时,请
axios跨域请求设置Cookies
书接上回:《axios转发/oauth/authorize未设置cookies问题》
上回实现了axios 在client域名下请求oauth域名并使response返回Set-Cookies的header
但是,接下来在域名oauth.szile.com域名下请求接口时,请求没有携带设置的Cookie,这是问什么? 难道是没有设置成功?
查看Application下Cookie,确实是没有设置成功。
经过搜索查找说 axios的请求必须配置axios.defaults.withCredentials = true,并且Response的Header需要有Access-Control-Allow-Credentials: true。
配置axios
// 创建axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // api的base_url
timeout: 0, // 请求超时时间
withCredentials: true
})
// 或者
// axios.defaults.withCredentials = true;
Response header中写返回了
但却报跨域错误
从console信息「The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard '’ when the request’s credentials mode is ‘include’.」时说当请求是携带凭据模式(即Access-Control-Allow-Credentials: true、携带Cookie)时,Response的header “Access-Control-Allow-Origin” 的值不能是“” 通配符。
经过需改配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter implements InitializingBean {
// *** 此处省略 ***
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(httpServletRequest -> {
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(List.of("*"));
corsConfiguration.setAllowedHeaders(List.of("*"));
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
});
// *** 此处省略 ***
}
}
成功的设置Cookie
总结
- 跨域请求是携带Cookie ,需要配置axios.defaults.withCredentials = true;
- 响应需要携带响应头 Access-Control-Allow-Credentials: true;
- 响应头 Access-Control-Allow-Origin 不能是通配符“*” ,并且需要和请求头Origin 的值一致。
更多推荐
所有评论(0)