简体   繁体   English

CORS 阻塞 Angular 7 和 Spring 5

[英]CORS blocked Angular 7 and Spring 5

I'm running a Spring 5 with Spring Security and Angular 7 project and trying to wire the frontend but keep getting this err message.我正在运行 Spring 5 和 Spring 安全和 Angular 7 项目并尝试连接前端但不断收到此错误消息。 I should note the projects are two different directories on my computer我应该注意项目是我计算机上的两个不同目录

OS backend > spring操作系统后端 > spring

OS frontend > angular操作系统前端 > angular

Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:4200' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

I've gone through a bunch of threads here on stackoverflow but none would help.我在stackoverflow上经历了一堆线程,但没有一个会有所帮助。

From what i've gathered the issue is my spring security config从我收集到的问题是我的 spring 安全配置

SPRING SECURITY FILE SPRING 安全文件

package com.starter_kit.auth;

import com.starter_kit.auth.Auth.CustomizeAuthenticationSuccessHandler;
import com.starter_kit.auth.Company.CompanyRepo;
import com.starter_kit.auth.Users.UserRepo;
import com.starter_kit.auth.Users.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    // code

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetailsService userDetailsService = mongoUserDetails();
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/dashboard/").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
                .loginPage("/login").failureUrl("/login?error=true")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("/**"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

Spring Controller Spring Controller

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping(path = "/login", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UserDetails login(@RequestBody User user) {
        return userService.loadUserByUsername(user.getEmail());
    }
}

and my ANGULAR TS HTTP CALL和我的 ANGULAR TS HTTP CALL

private loginAuth: string = "http://localhost:8080/login";
  public headers = new HttpHeaders({ "Access-Control-Allow-Credentials": "true" })

  public loginUser(user: any) {
    return this.http.post(
      this.loginAuth,
      user,
      { headers: this.headers }
    );
  }

any help would be great任何帮助都会很棒

Spring provides an out of the box solution to exclude OPTIONS requests from authorization checks Spring 提供了一种开箱即用的解决方案,可将 OPTIONS 请求排除在授权检查之外

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().authorizeRequests() ...

}

The cors() method will add the Spring-provided CorsFilter to the application context which in turn bypasses the authorization checks for OPTIONS requests. cors() 方法将 Spring 提供的 CorsFilter 添加到应用程序上下文中,从而绕过 OPTIONS 请求的授权检查。

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

相关问题 已解决 - 从 Java 写入 Angular 9 套接字 Spring - 被 CORS 策略阻止 - SOLVED - Write to Angular 9 Socket from Java Spring - Blocked by CORS Policy Angular 前端和 Java Spring 引导后端中的 CORS 策略阻止了请求? - Request blocked by CORS policy in Angular frontent and Java Spring Boot backend? 春季应用程序中的CORS策略阻止了来自角度应用程序的请求 - Requests from angular app blocked by CORS policy in spring app CORS 被阻止 - Spring 启动和反应 - CORS blocked - Spring Boot and React Angular 6 + Spring Boot:错误:“来自源‘http://localhost:4200’已被 CORS 策略阻止” - Angular 6 + Spring Boot: Error: "from origin 'http://localhost:4200' has been blocked by CORS policy" Java Spring 引导 Webflux cors 被阻止 - Java Spring Boot Webflux cors blocked Spring Boot&Angular 5 - CORS - Spring Boot & Angular 5 - CORS Spring 安全 CORS:来源已被 CORS 策略阻止 - Spring Security CORS: Origin has been blocked by CORS Policy 带 Angular 的弹簧靴。 CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:8080/”处的 XMLHttpRequest - Spring boot with Angular. Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:4200' has been blocked by CORS policy Spring Boot JWT CORS 与 Angular 6 - Spring Boot JWT CORS with Angular 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM