我已经使用 Angular 和 SpringBoot 创建了一个应用程序,用于 Spring Security 的基本身份验证,但我收到 401 错误..我是 SpringBoot 新手
@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated()
.and()
//.formLogin().and()
.httpBasic();
}
}
“从源“http://localhost:4200”访问“http://localhost:8080/hello-world/path-variable/MSD”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检的响应请求未通过访问控制检查:它没有 HTTP 正常状态。”
我在 anglat7 和 spring boot 上也遇到了同样的问题,我通过添加以下配置解决了问题
@Configuration
public class SpringDataRestConfiguration extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.getCorsRegistry().addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("GET", "POST", "PATCH", "PUT", "DELETE");
}
}
您可以尝试以下方法 在
controller
的顶部,您可以添加 @CrossOrigin(origins = "*", allowedHeaders = "*")
或根据需要进行自定义
...
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
public class UserController {
// Methods
}
...
请尝试上述解决方案,如果不起作用请告诉我
编辑1: 您还可以尝试使用
CORS
选项创建过滤器:
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class SimpleCORSFilter implements Filter {
private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
public SimpleCORSFilter() {
log.info("SimpleCORSFilter init");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
// HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
请尝试使用
filters
方法,如果不起作用请告诉我