我有一个带有RestController的Spring Boot应用程序,一个自定义安全过滤器和一个Angular 2应用程序,它从spring服务请求数据。
由于Access-Control-Allow-Origin问题,我有一个设置标题的过滤器。
如果我将localhost:4200称为localhost:8080,但它无法从localhost:4200运行到某些ip xx.xx.xx.xx:8080,则可以正常工作。
所以有人有想法吗?
这是我的过滤器:
@Component
public class MyCorsFilter implements Filter {
public MyCorsFilter() {
System.out.println("init filter corsssss");
}
@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");
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() {
}
}
答案 0 :(得分:0)
我有同样的问题。
在控制器中尝试此操作:
@Context
private HttpServletResponse servletResponse;
private void allowCrossDomainAccess() {
if (servletResponse != null) {
servletResponse.setHeader("Access-Control-Allow-Origin", "*");
}
}
然后在你的POST / GET Methode中:
@CrossOrigin
@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
public boolean loginController(@RequestBody User user) throws JSONException, NoSuchAlgorithmException, UnsupportedEncodingException {
allowCrossDomainAccess();
return userService.login(user);
}
致以最诚挚的问候,
答案 1 :(得分:0)
这是一项安全功能。在Spring中,您应该控制谁可以访问您的内容,而不是允许任何来源:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(csrfTokenRepository());
}
...
@Bean
public CsrfTokenRepository csrfTokenRepository() {
CookieCsrfTokenRepository repository = new CookieCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
repository.setCookieHttpOnly(false);
return repository;
}
然后在Angular中更改你的app.module.ts
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http';
export function xsrfFactory() { return new CookieXSRFStrategy('XSRF-TOKEN', 'x-xsrf-token'); }
...
providers: [
...
{ provide: XSRFStrategy, useFactory: xsrfFactory },
...
这样您的REST调用将附加cookie参数。
或者你可以这样做 - 我不建议,但如果你现在不想担心这个问题可能会有用:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}