我已经构建了一个带弹簧启动的简单应用程序和带有angular5的前端,我启用了控制器的交叉源而没有弹簧安全性应用程序运行良好但是当我只是但弹簧安全交叉来源的依赖性没有& #39;工作,所以我必须做什么?
控制器
@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());
}}
我的角度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;
}
}
在谷歌浏览器上运行角度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.
我应该添加什么?
答案 0 :(得分:1)
由于你在添加spring-security之前已经工作了,我将假设你已经在Angular 5中进行了代理设置以访问后端(因为它们在不同的端口上)。
为了让CORS使用spring安全性,您需要以这种方式配置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