[英]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.