Angular7:已被CORS策略阻止:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

时间:2019-07-27 07:30:34

标签: angular spring spring-boot spring-security angular7

我试图访问URL: http://localhost:8080/hello-world/path-variable从角度启动到Spring Boot。该项目在添加Spring Security之前还不错。我在Spring Boot中使用了基本身份验证安全性。因此,在发送请求之前,我需要添加用于授权的标头。我已经添加了标头从Spring Boot访问资源时出现角度错误,但是它显示了以下错误:

enter image description here

这是一个服务类:

   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;
       }
    }

我试图通过将用户名和密码添加为basicAuthHeaderString='Basic '+ window.btoa(username + ':' + password);来发送用户名和密码,但这是说我被CORS政策阻止了。

在这里,我在春季靴子中加了:

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));
    }

}

enter image description here

“网络”标签中的消息

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

2 个答案:

答案 0 :(得分:2)

我的朋友,根据您分享的代码段,我在这里发现了两个问题……

1)

   executeHelloWorldBeanService(){
       return this.httpClient.get<HelloWorldBean>('http://localhost:8080/hello-world-bean',}`,{headers : headers});
        console.log("hello world bean service executed");
      }

您需要将生成的基本授权传递给标头对象。

}`,{headers : headers}

在获取网址内。

2) Spring Security使您的请求无所适从。所以它的抛出错误。现在里面 SpringSecurityConfigurationBasicAuth.java 使用
http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().and().csrf().disable();

它将起作用。

答案 1 :(得分:0)

请将此属性添加到您的configure方法中。

cors().configurationSource( 
           request -> {             
              CorsConfiguration cors = new CorsConfiguration();                 
              cors.setAllowedMethods(
                Arrays.asList( 
                  HttpMethod.GET.name(),
                  HttpMethod.POST.name()
             ));   
             cors.applyPermitDefaultValues();           
             return cors;   
         })
        })

附加以上属性。 如果您需要支持PUT的交叉原点,请添加DELETE。