【问题标题】:CORS blocked Angular 7 and Spring 5CORS 阻止了 Angular 7 和 Spring 5
【发布时间】:2020-02-02 07:48:17
【问题描述】:

我正在使用 Spring Security 和 Angular 7 项目运行 Spring 5,并尝试连接前端,但不断收到此错误消息。我应该注意这些项目是我计算机上的两个不同目录

操作系统后端 > 春天

操作系统前端 > 角度

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.

我在 stackoverflow 上经历了一堆线程,但没有一个会有所帮助。

从我收集到的问题是我的 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;
    }

}

弹簧控制器

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

还有我的 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 }
    );
  }

任何帮助都会很棒

【问题讨论】:

  • 仔细阅读您的错误信息。
  • 我尝试将 Access-Control-Allow-Origin 添加到 angular 的 header 对象中,但仍然出现错误
  • @hrdkisback 谢谢这让我去某个地方,但似乎仍然无法登录。认为问题可能出在 Angular 方面

标签: java angular spring spring-boot spring-mvc


【解决方案1】:

Spring 提供了一种开箱即用的解决方案,可将 OPTIONS 请求排除在授权检查之外

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

}

cors() 方法会将 Spring 提供的 CorsFilter 添加到应用程序上下文中,从而绕过 OPTIONS 请求的授权检查。

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 2019-06-17
    • 2020-01-15
    • 2018-09-12
    • 2021-06-20
    • 2018-10-18
    • 1970-01-01
    • 2021-03-13
    • 2019-01-27
    相关资源
    最近更新 更多