Angular7:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
Posted
技术标签:
【中文标题】Angular7:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头【英文标题】:Angular7 : has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource 【发布时间】:2019-12-05 09:24:17 【问题描述】:我尝试访问 URL: http://localhost:8080/hello-world/path-variable 从 Angular 到 Spring Boot。在添加 Spring Security 之前项目很好。我在 Spring Boot 中使用了基本身份验证安全性。所以,我需要在发送请求之前添加标题以进行授权。我已经添加了 Angular 标题从 Spring Boot 访问资源时,它向我显示错误,例如:
这是一个服务类:
import Injectable from '@angular/core';
import HttpClient, HttpHeaders from '@angular/common/http';
export class HelloWorldBean
constructor(public message:String)
@Injectable(
providedIn: 'root'
)
export class WelcomeDataService
constructor(private httpClient:HttpClient)
executeHelloWorldBeanService()
return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean');
console.log("hello world bean service executed");
executeHelloWorldBeanServiceWithPathVariable(name)
console.log("hitting to get data")
let basicAuthHeaderString=this.createBasicAuthenticationHeader();
console.log(basicAuthHeaderString);
let headers=new HttpHeaders(
Authorization: basicAuthHeaderString
)
//i have added headers here in the URL
return this.httpClient.get<HelloWorldBean>(
`http://localhost:8080/hello-world/path-variable/$name`,
headers);
console.log("hello world bean service executed");
createBasicAuthenticationHeader()
let username='ashwin'
let password='karki'
let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password);
return basicAuthHeaderString;
我尝试通过将用户名和密码添加为 let basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password);
来发送用户名和密码,但它说我被 CORS 政策阻止了。
在这里,我在我的 spring boot 中添加了:
spring.security.user.name=ashwin
spring.security.user.password=karki
在这个安全配置类中,我禁用了 csrf():
package com.ashwin.rws.basic.auth;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
.anyRequest().authenticated()
.and()
//.formLogin().and()
.httpBasic();
在控制器类中:
package com.ashwin.rws.rest.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ashwin.rws.model.HelloWorldBean;
@CrossOrigin(origins="http://localhost:4200")
@RestController
public class HelloWorldController
@GetMapping(path="/hello-world/path-variable/name")
public HelloWorldBean helloWorldBeanPathVariable(@PathVariable("name") String name)
System.out.print("name is"+name);
return new HelloWorldBean(String.format("Hello world %s", name));
来自网络标签的消息
Request URL: http://localhost:8080/hello-world/path-variable/in28minutes
Request Method: GET
Status Code: 401
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Sat, 27 Jul 2019 08:17:09 GMT
Expires: 0
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm", Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Basic YXNod2luOmthcmtp
Origin: http://localhost:4200
Referer: http://localhost:4200/welcome/in28minutes
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/75.0.3770.142 Safari/537.36
【问题讨论】:
你为什么要用@CrossOrigin(origins="http://localhost:4200")
和http://localhost:8080
之类的东西污染你的生产代码?您的请求不会来自现实生活中的http://localhost:4200
,对吗?如果您的计划是从同一主机提供前端和 API,请使用 Angular CLI 代理支持:angular.io/guide/build#proxying-to-a-backend-server
参考这个***.com/questions/46788969/…
【参考方案1】:
根据你分享的sn-ps代码,我发现这里有两个问题。
1.
executeHelloWorldBeanService()
console.log("hello world bean service executed");
return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean',headers : headers);
您需要在获取 url 中传递您生成的基本授权的标头对象:headers: headers
。
2。
您的请求已由 spring security 验证。所以它抛出一个错误。现在里面
SpringSecurityConfigurationBasicAuth.java
使用
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().and().csrf().disable();
它会起作用的。
【讨论】:
【参考方案2】:请在您的配置方法中添加此属性。
cors().configurationSource(
request ->
CorsConfiguration cors = new CorsConfiguration();
cors.setAllowedMethods(
Arrays.asList(
HttpMethod.GET.name(),
HttpMethod.POST.name()
));
cors.applyPermitDefaultValues();
return cors;
)
)
附加上面的这个属性。 如果需要PUT支持跨域,DELETE请添加。
【讨论】:
请绕过您的安全并首先检查您的 API。以上是关于Angular7:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头的主要内容,如果未能解决你的问题,请参考以下文章
http://localhost:4200' 已被 CORS 策略阻止:对预检请求的响应未通过
本地主机已被 cors 策略请求标头字段内容类型阻止访问控制不允许
ReactJS:对 fetch 的访问已被 CORS 策略阻止