簡體   English   中英

Cors Auth SpringBoot

[英]Cors Auth SpringBoot

我正在使用 springboot 和 angular。 嘗試使用 JWT 登錄,當使用郵遞員發送 http 時,請求沒問題,但是當嘗試使用 Angular 發送相同的 http 時,我收到下一個錯誤:

從源 'http://localhost:4200' 訪問 XMLHttpRequest at 'http://localhost:8080/login' 已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:它沒有 HTTP好的狀態。

zone-evergreen.js:2845 POST http://localhost:8080/login net::ERR_FAILED

當我發送除登錄以外的請求時,它們工作正常我知道需要一個 cors 所以代碼是下一個:

@EnableGlobalMethodSecurity(securedEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().csrf().disable().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().cors();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("*"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

但錯誤是一樣的。

您可以在 angular 應用程序中使用 proxy.conf.json。

這是示例proxy.conf.json

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

然后你可以使用http://localhost:4200/api/path-be你的 BE

http://localhost:4200是您的 Angular 應用程序。 /api如果您向/api/*發出請求,那么角度代理配置將重定向到您在proxy.conf.json定義的proxy.conf.json

記得將proxy.conf.json添加到你的angular.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular-hands-on:build",
            "proxyConfig": "proxy.conf.json"
          },

重啟你的 Angular 應用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM