我使用Angular
+ Spring Boot2
+ Spring Security
。我为允许WebMvcConfigurer
创建了CORS
配置:
@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
的请求权限?
答案 0 :(得分:1)
您应将/oauth/token
添加到配置中。
http.cors().and().authorizeRequests()
// add the "/oauth/token" permitAll
.antMatchers("/login", "/security/**","/oauth/token").permitAll()
.anyRequest().authenticated()
.and().formLogin().permitAll()
.and().csrf().disable();