/oauth/token跨域问题,无法获取
参考文章:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 允许跨域访问
* 解决/oauth/token无法跨域问题
* @author NPF
* @date 2020/12/30
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// 1允许任何域名使用
config.addAllowedOrigin("*");
// 2允许任何头
config.addAllowedHeader("*");
// 3允许任何方法(post、get等)
config.addAllowedMethod(HttpMethod.GET);
config.addAllowedMethod(HttpMethod.POST);
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.DELETE);
config.addAllowedMethod(HttpMethod.OPTIONS);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
允许所有资源跨域访问
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 设置系统资源允许跨域访问
* @author HLN
* @date 2020/02/04 08:30
*/
@Configuration
public class WebMvcConfigurer implements WebMvcConfigurer {
/**
* 设置系统资源允许跨域访问
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
.allowedOrigins("*")
//这里:是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
//跨域允许时间
.maxAge(3600);
}
}
OPTIONS类型,访问后台资源报401,提示需要token
/**
* 设置匿名访问地址清单
* @param http
* @throws Exception
*/
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//swagger-ui.html 相关路径可以匿名访问
.antMatchers("/v2/api-docs", "/favicon.ico",
"/swagger-resources/configuration/ui",
"/swagger-resources",
"/swagger-resources/configuration/security",
"/swagger-ui.html",
)
.permitAll()
// 设置OPTIONS类型,不需要认证,解决CORS跨域问题
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/oauth/logout")
//退出成功的业务处理
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
}