简体   繁体   English

angular 9 和 spring 启动 2 中请求的资源上不存在“访问控制允许来源”header

[英]No 'Access-Control-Allow-Origin' header is present on the requested resource in angular 9 and spring boot 2

I added spring security to the spring boot application and I have some api end points that needs to be called no matter user login or not.(I mean these are the rest end points where I need to retrieve data in my front side angular). I added spring security to the spring boot application and I have some api end points that needs to be called no matter user login or not.(I mean these are the rest end points where I need to retrieve data in my front side angular).

So,I config it as:因此,我将其配置为:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private UserDetailsService customUserDetailsService;
 
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
         .userDetailsService(customUserDetailsService)
         .passwordEncoder(passwordEncoder());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
           http.csrf().
           disable()
               .authorizeRequests()
               .antMatchers(HttpMethod.OPTIONS, "/**")
               .permitAll()
              .antMatchers("/books").permitAll()
            .antMatchers("/api/v1/search/**").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
               .anyRequest()
               .authenticated()
               .and()
               .httpBasic();
              
    }
 
}

I have all the api exposed from: http://localhost:8080/api/v1/ like:我有所有的 api 暴露于: http://localhost:8080/api/v1/像:

http://localhost:8080/api/v1/books
http://localhost:8080/api/v1/bookcategory

I have configured using .antMatchers("/api/v1/search/**") ,and my config for restendpoint is:我已经使用.antMatchers("/api/v1/search/**")进行了配置,我的 restendpoint 配置是:

@RequestMapping("/api/v1")
@RestController
@CrossOrigin(origins ="http://localhost:4200")
public class BasicAuthController {

    @GetMapping(path = "/basicauth")
    public AuthenticationBean basicauth() {
        System.out.println("hitted here");
        return new AuthenticationBean("You are authenticated");
    }
    
  
}

I allowed the csfr policy using:我允许使用 csfr 策略:

@Configuration
public class RepositoryConfig implements RepositoryRestConfigurer{

    @Autowired
    private EntityManager entityManager;
    
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(entityManager.getMetamodel().getEntities().stream()
                .map(Type::getJavaType).toArray(Class[]::new));
        
        
        //to handle cross origin
        config.getCorsRegistry().addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

BookRepository.java BookRepository.java

public interface BookRepository extends JpaRepository<Book,Long> {

    @RestResource(path = "categoryid")
    Page<Book>  findByCategoryId(@Param("id") Long id,Pageable pageable);
    
    //to get book by searching
    @RestResource(path = "searchbykeyword")
    Page<Book>  findByNameContaining(@Param("xyz") String keyword,Pageable pageable);
}

front side I have angular 9 as:正面我有 angular 9 为:

auth.service.ts auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

   // BASE_PATH: 'http://localhost:8080'
   USER_NAME_SESSION_ATTRIBUTE_NAME = 'authenticatedUser';

   public username: String;
   public password: String;
 
   constructor(private http: HttpClient) {
 
   }
 
   authenticationService(username: String, password: String) {
     return this.http.get(`http://localhost:8080/api/v1/basicauth`,
       { headers: { authorization: this.createBasicAuthToken(username, password) } }).pipe(map((res) => {
         this.username = username;
         this.password = password;
         this.registerSuccessfulLogin(username, password);
       }));
   }
 
   createBasicAuthToken(username: String, password: String) {
     return 'Basic ' + window.btoa(username + ":" + password)
   }

}

//i didnot pasted all the codes. //我没有粘贴所有代码。

So,I get error as when I goto link http://localhost:4200/books:因此,当我转到链接 http://localhost:4200/books 时出现错误:

在此处输入图像描述

The problem is CORS which is a security feature of your browser.问题是 CORS 这是您浏览器的安全功能。 It ensures that only resources form the same domain (and port.) can be accessed.它确保只能访问来自同一域(和端口)的资源。 Your Angular development server and the Tomcat run on a different port which causes the request to be declined.您的 Angular 开发服务器和 Tomcat 在不同的端口上运行,这会导致请求被拒绝。 You have to configure CORS, However.但是,您必须配置 CORS。 you should know what you are doing because you are basically disabling a security feature.您应该知道自己在做什么,因为您基本上是在禁用安全功能。 Usually it is not a problem tho.通常这不是问题。 You can do this by adding the annotation @CrossOrigin to your controller methods or by using the Java configuration, For the second cause: I'm sure you'll easily find it on Google :)您可以通过将注释 @CrossOrigin 添加到您的 controller 方法或使用 Java 配置来做到这一点,第二个原因:我相信您会很容易在 Google 上找到它:)

I have some projects using Angular+SpringBoot with security and I create a specific Bean to handle with CORS and I never have problem.我有一些项目使用具有安全性的 Angular+SpringBoot,我创建了一个特定的 Bean 来处理 CORS,我从来没有遇到过问题。 If you can try, add this method bellow in your WebSecurityConfig class:如果您可以尝试,请在您的 WebSecurityConfig class 中添加以下方法:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200", "http://localhost:8080"));
    configuration.setAllowedMethods(Arrays.asList("GET", "PUT", "POST","OPTIONS", "DELETE"));
    configuration.setAllowedHeaders(Arrays.asList("authorization","content-type"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

CORS (Cross-Origin Resource Sharing) is a security feature of your browser that prevent authorized sites from using Resources from another origin CORS(跨域资源共享)是浏览器的一项安全功能,可防止授权站点使用来自其他来源的资源

in nutshell it happens if your site on x:y origin and requesting resources from a:y, x:b or a:b origins (different port and/or domain)简而言之,如果您的站点位于 x:y 来源并从 a:y、x:b 或 a:b 来源(不同的端口和/或域)请求资源,则会发生这种情况

what exactly happens in nutshell when this is the case简而言之,在这种情况下会发生什么

if you made a get (or post...) request from another origin, the browser will first make an option request to the same endpoint, if it's succeeded and has all the allowing headers it will make the get request, if not it will throw the error specifying why it was denied and don't make the original request如果您从另一个来源发出获取(或发布...)请求,浏览器将首先向同一端点发出option请求,如果它成功并且具有所有允许的标头,它将发出 get 请求,否则它将抛出错误,说明它被拒绝的原因并且不发出原始请求

so we have two cases now, it's either the headers is returned only on the get request, but not the options one, or it's never returned所以我们现在有两种情况,要么仅在获取请求时返回标头,而不是选项之一,要么从未返回

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 和 Spring Boot:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如何通过angular和spring boot解决 - Angular and Spring boot: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to solve it by angular and spring boot Spring 启动 OAuth 客户端配置给出“No 'Access-Control-Allow-Origin' header 存在于请求的资源上。” - Spring boot OAuth Client config giving "No 'Access-Control-Allow-Origin' header is present on the requested resource." CORS 策略:请求的资源上不存在“访问控制允许来源”header Spring 引导 Rest API & VUE - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE <spring boot>请求的资源上不存在“Access-Control-Allow-Origin”header</spring> - <Spring Boot> No 'Access-Control-Allow-Origin' header is present on the requested resource CORS 策略:请求的资源 Spring Boot Rest API 上不存在“Access-Control-Allow-Origin”标头 - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API 请求的资源上不存在Access-Control-Allow-Origin标头 - No Access-Control-Allow-Origin header is present on the requested resource 请求的资源 (Ingress) 上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource (Ingress) 尽管存在请求的资源,但没有“ Access-Control-Allow-Origin”标头存在 - No 'Access-Control-Allow-Origin' header is present on the requested resource despite it is there CORS Spring Security 配置 - 404 请求的资源上不存在“Access-Control-Allow-Origin”标头 - CORS Spring Security configuration - 404 No 'Access-Control-Allow-Origin' header is present on the requested resource Java Spring:请求的资源上不存在“Access-Control-Allow-Origin”标头 - Java Spring: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM