在前后端分离中,前端的域或端口与后端的域或端口不一致的情况下,浏览器默认会阻止前端请求后端,因此我们为了使前端请求能够得到服务器响应并返回数据,需要做一些设置。
基于springboot+vue
一.CORS服务器端设置
@Configuration
public class MyConfig implements WebMvcConfigurer {
//静态资源URI和位置映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
//设置静态资源缓存1年
.setCachePeriod(3153600);
}
// CORS设置,任何请求,任何来源,任何方法,任何头,允许凭证
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true).maxAge(3600);
}
}
另外,如果采用了springSecurity,则需要进一步进行安全设置,重点内容如下,需要安全级别中启用CORS
//使用Spring Security,请确保在Spring安全级别启用CORS
.cors()
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
private MyUserDetalisService myUserDetalisService;
public MySecurityConfig(MyUserDetalisService myUserDetalisService) {
this.myUserDetalisService = myUserDetalisService;
}
//http安全配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() //所有请求拦截
.antMatchers("/static/**").permitAll() //放在所有拦截的前面放行不需要拦截的资源
.antMatchers("/login").permitAll() //放行登录
.antMatchers("/logout").permitAll() //放行注销
.antMatchers("/reg").hasAnyAuthority("REGUSER")//此页需要权限
.anyRequest().authenticated() //除上所有拦截需要用户认证
.and()
.formLogin().loginProcessingUrl("/login")
//登录成功后的返回结果
.successHandler(new AuthenticationSuccessHandlerImpl())
//登录失败后的返回结果
.failureHandler(new AuthenticationFailureHandlerImpl())
.and()
.logout().logoutUrl("/logout")
//登出后的返回结果
.logoutSuccessHandler(new LogoutSuccessHandlerImpl())
.and()
//使用Spring Security,请确保在Spring安全级别启用CORS
.cors().and()
.csrf().disable(); //关闭csrf校验
}
//认证管理器配置
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetalisService)
//查询时需要密码加密后和数据库做比较
.passwordEncoder(new BCryptPasswordEncoder());
}
}
二、前端中
在axios配置中也需要启用凭证,否则axios请求会被后端安全拦截,转向/login请求
axios.defaults.withCredentials = true