【问题标题】:Angular7 : has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resourceAngular7:已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】: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

【问题讨论】:

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


【解决方案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。
    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 2021-12-27
    • 1970-01-01
    • 2020-04-16
    • 2021-04-28
    • 2022-06-21
    • 2022-07-19
    • 2020-02-12
    相关资源
    最近更新 更多