【问题标题】:Cross-orgin doesn't work with Spring boot跨域不适用于 Spring Boot
【发布时间】:2018-07-04 02:03:26
【问题描述】:

我已经使用 spring-boot 和 angular5 构建了一个简单的应用程序,我为没有 spring-security 的 Controller 启用了跨域,该应用程序运行良好,但是当我只是 spring-security 跨域的依赖项时没有不工作,那我该怎么办?

控制器

   @RestController
   @RequestMapping(ResourceConstants.Product_URL)
   @Api(description = "Porduct and Categories resources")
   @CrossOrigin
   public class ProductResources {

    @Autowired
    private CategoryRepo cateRepo;



    // Categories Resources
    @RequestMapping(method = RequestMethod.GET, value = "/AllCategories")
    @ApiOperation(value = "Return All Categories")
    public List<Category> getAllCategories() {

        return cateRepo.findAll();// .stream().
        // filter((c)->c.getActive()==1)
        // .collect(Collectors.toList());
    }}

我的 Angular 5 代码

import { Component, OnInit } from '@angular/core';
import { CategoryService } from '../services/category.service';


import {Http, Response} from "@angular/http";
import { Observable } from 'rxjs/Observable';
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
  providers: [CategoryService]
})

export class HeaderComponent implements OnInit {

  currency = [];
  languages = [];
  links = [];
  constructor(private http: Http) {

    this.currency = ['USD', 'Egp'];
    this.languages = [
      'Arabic',
      'English'
    ];
    this.links = ['SignUp', 'Profile', 'Settings', 'SignIn'];

  }

  ngOnInit() {

console.log("Welcome");
    this.getAll()
            .subscribe(
            data => console.log(data),
            err => {
                // Log errors if any
                console.log(err);
            });
  }

  getAll(): Observable<any> {


    //noinspection TypeScriptValidateTypes
    return this.http
        .get('http://localhost:8080/rest/api/product/AllCategories')
        .map(this.mapRoom);
}

mapRoom(response: Response): any[] {
    return response.json().content;
}


}

在 google chrome 上运行 angular 5 时出现此错误

GET http://localhost:8080/rest/api/product/AllCategories 401 ()

 Failed to load http://localhost:8080/rest/api/product/AllCategories: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

我应该添加什么?

【问题讨论】:

  • 您如何为您的 Angular 5 应用程序提供服务?您需要 Angular 5 的 CORS 以允许 localhost:8080

标签: angular spring-boot cors


【解决方案1】:

由于您在添加 spring-security 之前已经使用它,我假设您已经在 Angular 5 中设置了代理以访问后端(因为它们位于不同的端口上)。

为了让 CORS 与 Spring Security 一起使用,您需要以这种方式配置 CorsConfigurationSource bean:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
    return source;
}

这只是基本配置,您还可以使用 CorsConfiguration 类中的 setAllowedOrigins 和 setAllowedMethods 方法更具体地指定允许的方法/来源。

有关此的春季文档:https://docs.spring.io/spring-security/site/docs/current/reference/html/cors.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 2015-04-13
    • 2018-10-18
    • 2020-05-02
    • 2014-12-30
    • 2014-09-08
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多