Man*_*ith 12 java spring cors angular
大家.我是Angular 2和Spring Framework的新手.我正在尝试使用授权标头(基本身份验证)的简单获取请求.
我正在使用Spring Boot(1.2.6.RELEASE),这也是相关的.我的CORS配置如下所示.
@Component
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", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, authorization, x-auth-token");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
Run Code Online (Sandbox Code Playgroud)
这是从客户端看起来的样子
this.headers.append('Authorization', 'Basic dXNlcjphZG1pbg==');
return this.http
.get(`http://localhost:8080/api/login?username=${username}`, {headers : this.headers} )
.map(response => response.json().data as any);
}
Run Code Online (Sandbox Code Playgroud)
我一直在:
XMLHttpRequest无法加载 http:// localhost:8080/api/login?username = user.预检的响应具有无效的HTTP状态代码401
请帮助,我不知道我错过了什么......我已经检查了很多帖子但是无法到达那里......
小智 8
当http方法为OPTIONS时,避免过滤并设置状态200
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
Run Code Online (Sandbox Code Playgroud)
小智 7
这可能是非常晚的,但这可以解决一些问题,经过长时间我找到了答案
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
public void configure( WebSecurity web ) throws Exception
{
web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
}
}
Run Code Online (Sandbox Code Playgroud)
如果有人遇到类似的情况,使用Spring Boot,Spring Security和客户端,比如angular 2/4,我在这里发布了调查结果.
对于那些正在寻找简短答案的人,你必须配置两件事:
使用Spring Boot,启用全局CORS的推荐方法是在Spring MVC中声明并结合细粒度@CrossOrigin配置:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
}
Run Code Online (Sandbox Code Playgroud)然后,在使用Spring Security时,您必须在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Run Code Online (Sandbox Code Playgroud)干杯!!!
| 归档时间: |
|
| 查看次数: |
9404 次 |
| 最近记录: |