繁体   English   中英

Spring 启动 + angular 代理 - 403

[英]Spring boot + angular proxy - 403

在设置一个小型应用程序来测试各种事物时,我遇到了一个我无法解决或解释的奇怪行为。

我的 spring 启动(版本 2.4.2)应用程序公开了一个 rest 端点/用户。 我已将上下文路径设置为 /api(通过在 application.properties 中设置 server.servlet.context-path=/api)。

我尝试使用以下配置禁用 CORS、CSRF、..

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer  {
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors().disable()
                .cors().disable()
                .httpBasic().disable()
                .formLogin().disable()
                .authorizeRequests()
                .antMatchers("/user/**").permitAll()
                .anyRequest().permitAll();
    }
}

为了公开端点,我创建了这个 controller:

@RestController
public class UserController {
    @GetMapping("/user")
    public User getUser() {
        return User.builder().name("George").build();
    }
}

我的端点在 http://localhost:8080/api/user 上可用,并按预期给出以下结果:

{"name":"George"}

为了在 angular 11 应用程序中测试一些东西,我创建了一个代理并在我使用 npm 启动时附加它。

代理配置:

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": "true"
  }
}

在我的浏览器中,每当我调用端点(通过端口 4200 直接输入 url)时,我得到一个 403。尝试访问组件中的 api 也会给出这个 403:

  ngOnInit(): void {
    this.http.get("/api/greeting").subscribe(resp => {});
  }

但是,在我的日志中,我看到 angular 应用程序正确代理到后端: [HPM] GET /api/user -> http://localhost:8080

如果我从 spring 启动应用程序中删除上下文路径 (/api) 并改用 / ,我什至在将代理更改为后得到 404:

{
  "/api": {
    "target": "http://localhost:8080",
    "secure": false,
    "logLevel": "debug",
    "pathRewrite": {"^/api" : ""}
  }
}

我确实认为这与 CORS/CSRF 有关,但我无法解释上述行为。 我的问题是:我做错了什么,如何避免 angular 4200 端口上的 403/404?

谢谢,

科恩

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM