设置API支持跨请求
公司最近尝试用h5来做简单的APP(h5套个Andorid壳),使用的vue.js来写,后台是开放平台方式需要支持跨域。
后台基础框架
使用Spring mvc+Spring Security oauth2+spring boot来做的API框架
spring mvc 设置支持
需要spring mvc 4.2及以上版本
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
.allowCredentials(false).maxAge(3600);
}
}
Spring Security oauth2 设置支持
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//重点是调用http.csrf()开启对csrf的支持
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login", "/logout.do").permitAll()
.antMatchers("/**").authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login.do")
.usernameParameter("name")
.loginPage("/login")
.and()
.logout()
//To match GET requests we have to use a request matcher.
.logoutRequestMatcher(new AntPathRequestMatcher("/logout.do"));
//.and()
//.userDetailsService(userDetailsService());
http.sessionManagement().maximumSessions(1);
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setMaxAge(3600L);
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}