我使用 Angular
+ Spring Boot2
+ Spring Security
技术栈。为了允许跨域请求,我创建了一个名为 WebMvcConfigurer
的配置文件:
@Component
@Profile("dev")
class DevWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**").allowedMethods(ALL);
registry.addMapping("/oauth/token").allowedMethods(ALL);
}
}
创建安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
.antMatchers("/login", "/security/**").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll()
.and().csrf().disable();
}
}
但是,当我尝试从Angular发出请求时:
Request URL: http://localhost:8080/oauth/token
Request Method: OPTIONS
Status Code: 401
我收到了401错误代码。我该怎么解决?我找到的所有示例都归结为编写如下过滤器:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
response.setHeader("Access-Control-Max-Age", "3600");
if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
但这是一些糟糕的东西。我们为所有OPTIONS
请求设置状态,表示一切正常。这是什么意思?
我的DevWebMvcConfigurer
只在配置文件为dev
时创建。我该如何将OPTIONS
请求权限添加到它中呢?